I will call cookies before all web page. For this reason, I should create value key before all of the page or module is called. Before any of the page is called, cookie should be constructed first, for my case. How can I manage this? Where should I put request.session['id']=Null so that it will called first before any other page is called?
You need to write a custom decorator to handle the situation.
You can read more about Decorators here: https://docs.djangoproject.com/en/dev/topics/http/decorators/
For example the csrf_exempt decorator allows a request to be processed without the csrf token facility in forms, very useful for JSON based requests.
#csrf_exempt
def new(request):
if request.method == 'POST':
json_data = simplejson.loads(request.raw_post_data)
try:
Similarly have a custom decorator for ensuring cooking and use it as:
#ensure_cookie
def new(request):
...
Writing custom decorators: How to write a custom decorator in django?
You can put this code in process_request or process_view method in custom middleware.
Related
Is this possible to write a decorator to check if a specific request session exists? Like user id. If not redirect to another page. Similar to login_required decorator.
#session_active('user_id')
def HomeView(request):
return HttpResponse('')
I'm trying to handle a POST request from outside of django to path /app/process
When I decorate my view with #login_required the requests come to my view change to /app/process/login?next=/app/process/ and request.POST contains non of my posted data!
What is the problem?
My View is like this:
#login_required
def callback(request):
state = request.POST['State']
EDIT:
If i log request.user in view user is there so he is actually loggedin!
The error should be with the session. The #login_required decorator indicates that all the requests to the view function should be authenticated. So check whether your session object holding the logged user data or not.
just try..
request.POST.get('State')
this may work I guess..
please refer this question too,
Suggested Method to Forward POST Parameters Through login_required Decorator?
What is the best way to get DRF API view data into another Django view?
Currently I am just calling the view through requests module:
response = requests.get('my_api_view')
but is there a cleaner way?
I can also just instantiate the API view class in another view, but this will give me unserialized objects.
Not sure what you mean by getting unserialized objects. You can do the following if you're using function-based views:
def view(request):
# some stuff done
return Response(<result>)
def another_view(request)
return view(request)
If you're views are class based then you can do the following:
class AClassBasedView(SomeMixin, SomeOtherMixin):
def get(self, request):
# do something with the request
return Response(<some result>)
class AnotherClassBasedView(SomeMixin, SomeOtherMixin):
def compute_context(self, request, username):
#some stuff here here
return AnotherClassBasedView.as_view()(request)
Both of these will return a <class 'rest_framework.response.Response'> object which can be passed further.
I'm not sure what exactly you want to achieve but wanting to call a view from another view maybe a sign of bad architecture. It could mean that you have a business logic implemented in the second view which you want to access in the first. Usually the rule of thumb is to move such a common logic somewhere else so it could be used by different views.
Again I don't know what you want to achieve but this is a possibilty.
I was working on an application wherein I created a generic ListView. Now, while defining that view in my urls.py, I read from the documentation that I need to use the as_view() method as follows:
from django.conf.urls import patterns, include, url
from .views import BlogIndex
urlpatterns = patterns(
'',
url(r'^$', BlogIndex.as_view(), name="index"),
)
Now, I didn't really understood what the documentation had to say about this method. Can someone shed some light into this concept?
In Class-based views, you have to call as_view() function so as to return a callable view that takes a request and returns a response. Its the main entry-point in request-response cycle in case of generic views.
as_view is the function(class method) which will connect my MyView class with its url.
From django docs:
classmethod as_view(**initkwargs)
Returns a callable view that takes a request and returns a response:
You just can't use class-based views like you could in normal function-based views.
BlogIndex(request) # can't do this in case of CBVs
The above code is not valid if you want the CBVs to function properly. For that, you need to provide a view which is callable and then pass request to it. For example:
response = MyView.as_view()(request) # valid way
By calling the as_view() function on my view class MyView will give me a view which i will call with request parameter to initiate the request-response cycle.
In your case:
my_callable_view = BlogIndex.as_view() # returns a callable view
<function blog.views.BlogIndex>
Now, call this function and pass the request.
response = my_callable_view(request) # generate proper response
view function have different format than before because :
This view will actually be implemented as a class
We will be inheriting from an existing generic view function that already does most of what we want this view function to do, rather
than writing our own from scratch.
Class method as_view()- this does all the work of creating an instance of the class, and making sure that the right handler methods
are called for incoming HTTP requests.
ref : https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views
Maybe I can try to write the as_view with pseudo-code:
class ViewClass():
#other stuff
def as_view(self):
return self.render(*args)
It return the render function inside the CBV.
So it actually is the same as path('some_path',views.some_view_function,name='some_name')
Of course, there there is actually much more things going on than only render function, for example to verify and save the content inside post queryDict, actually you need def post(): to handle the post, in function you just if request.method == 'POST' they are actually mutual.
To be specific, as_view() just generate a overall function, including if request.method =='POST': #some code Maybe the actual code doesn't work like that, but you could understand it this way if you are not prepared to contribute to django source code yourself.
In a django app I have a decorator called my_dec , I want to use the url of the view that is calling the decorator in the decorator, for example if the code of view is like this :
#my_dec(key)
def my_view
pass
I want something like this :
def my_dec(key)
print #url of "my_view"
how can I access the url of my_view or any other view that is calling the decorator?
Assuming you're using function based views.
In your decorator you can access the request object of your function view.
Here's an example code
def my_dec(func):
def wrapped(request):
print request.path_info
return func(request)
return wrapped
And then you can use this decorator on a view like this:
#my_dec
def my_view(request):
return HttpResponse(...)
This example simply prints out the url associated with your view.
Note that in your view you have access to the entire request object and can fish out any information you want.
This example works on function based views but can easily be modified to work on class-based views as well