Accessing request object in django urls.py - python

The question is also inspired from documentation here.
I am using generic view (ListView) in Django in order to list out all the questions, current logged in user has asked. I was curious to do it without creating a View in views.py. So in urls.py I added a path like:
urlpatterns += [
path('myqn/', login_required(views.ListView.as_view(model=models.Question, queryset=models.Question.objects.filter(user__id=request.user.id), template_name='testapp/question_list.html', context_object_name='questions')), name='myqn'),
]
Its giving me that:
NameError: name 'request' is not defined
I know it. Since, request object is passed by the URLConf to the View class/function. So, is there a way, I can access the user.id in this scope.
PS: The code works if I replace user__id=9. It lists out all the questions asked by user-9. :)

You normally do this by overriding the get_queryset method in a subclass of the ListView. So you can create a view:
# app/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.list import ListView
from app.models import Question
class QuestionListView(LoginRequiredMixin, ListView):
model = Question
template_name='testapp/question_list.html'
context_object_name='questions'
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(
user_id=self.request.user.id
)
In the urls.py you then use the QuestionListView
# app/urls.py
from django.urls import path
from app.views import QuestionListView
urlpatterns += [
path('myqn/', QuestionListView.as_view(), name='myqn'),
]
You can define a function or lambda expression with:
import inspect
def custom_queryset(*args, **kwargs):
self = inspect.currentframe().f_back.f_locals['self']
return Question.objects.filter(
user_id=self.request.user.id
)
urlpatterns += [
path('myqn/', QuestionListView.as_view(get_queryset=custom_queryset), name='myqn'),
]
This is however not a good idea. First of all, it inspects the call stack, and if later the ListView is altered, it might not work anymore. Furthermore here this listview will not check if the user has logged in for example. We can not make use of the method resolution order (MRO) to make a call to a super() method.
Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

No, You can't.
The as_view() accepts any class attributes of a view class. In your case, the request object will not accessible from the class
class Foo(ListView):
queryset = Question.objects.filter(user__id=request.user.id)
The above snippet you can't reference the request and hence also in your urls.py
In these kinds of complex situations, we should override the get_queryset(), as you know.

Related

Difference between reverse and reverse_lazy?

I read more projects in Django however I didn't understand!
class SignUpView(generic.CreateView):
form_class = UserCreationForm
success_url = reverse_lazy('login')
template_name = 'signup.html'
like this
reverse(…) [Django-doc] is a function that, for a given view name and parameters, can construct the path. But there is a problem with resolve: it can only work if the urls.py is loaded.
Typically the views.py file is imported by the urls.py, so that means that the views.py is loaded before the urls.py. This thus means that if you call reverse(…) at the class level or in a decorator like #login_required(login_url=reverse('view-name')), it is immediately processed when you the file is loaded. At that point the paths are not yet defined, so that will error.
A solution to this is to postpone evaluation. reverse_lazy(…) [Django-doc] does this. Instead of immediately evaluating it, it simply stores the name of the view, the parameters, etc. and promises to later call reverse when necessary.
If you have a view where the reverse is called in a function for example, then this is usually not a problem, unless the function is called when you load the module of course. So one can for example define a function:
from django.urls import reverse
class SignUpView(generic.CreateView):
form_class = UserCreationForm
template_name = 'signup.html'
def get_success_url(self, *args, **kwargs):
return reverse('login')
This works because here .get_success_url(…) is only called when the view is invoked and was successful. This is long after the paths are loaded.

Is it required to add custom views in admin page in ModelAdmin class when we can do it normally by adding views in views.py and urls in urls.py?

According to django docs:
class MyModelAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(MyModelAdmin, self).get_urls()
my_urls = [
url(r'^my_view/$', self.my_view),
]
return my_urls + urls
def my_view(self, request):
# ...
context = dict(
# Include common variables for rendering the admin template.
self.admin_site.each_context(request),
# Anything else you want in the context...
key=value,
)
return TemplateResponse(request, "sometemplate.html", context)
If I am not wrong, we can do the same thing by adding url in urls.py and the views in views.py as it is normally done then, what is the use of introducing this way? I am a newbie to django and I may be missing something here.
Can you please provide an example where we cannot do it in views.py and we must use the above method?
Any guidance/help would be appreciated.
I think I figured out, both of them can be used to do the same thing but the key difference is that the views which you write using above method will belong to admin app while the general views in views.py belongs to the particular app in you have written.
Hence, the url in ModelAdmin need to be called using name admin:url_name since the url goes as admin/my_views/ in given example.

How to implement method in Django REST?

Have the next Django REST question.
I have the view.
class MessageViewSet(viewsets.ModelViewSet):
serializer_class = MessageSerializer
queryset = Message.objects.filter(isread = False)
def mark_read():
queryset = Message.objects.update(isread=True)
return Response({'read':queryset})
And router in urls.py
router = SimpleRouter() router.register(r'api/get_messages', MessageViewSet)
urlpatterns = [
url(r'^$', MainView.as_view(), name='main'),
url(r'^', include(router.urls)) ]
Now i have 'get_messages' page which shows all list.
How can i implement a method which would change 'isread' value of model instanse from False to True, when I visit a 'mark_read' page?
As you can see, i tried to write method in the class. But when i'm trying to call it in urls in this way:
router.register(r'api/mark_read', MessageViewSet.mark_read),
Here comes an error.
assert queryset is not None, 'base_name argument not specified, and could ' \
AssertionError: base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.
Maybe i shouldnt use router, and rewrite view and urls in other way. If u know how to solve this problem, please answer. Thanks.
You can use detail_route or list_route decorators.
from rest_framework.decorators import list_route
class MessageViewSet(viewsets.ModelViewSet):
#list_route()
def mark_read(self, request):
queryset = Message.objects.update(isread=True)
return Response({'read':queryset})
With that mark_read method will be available at api/get_messages/mark_read. And you don't need to create separate router, just use one you created for MessageViewSet
docs reference
Since you are using a model viewset you can directly use put or patch rest method to send the desired value for the desired field as the data.
Ideally in rest get should not change model values. If you really want a different end point put the list_route or detail_route decorator on your mark_read method, and make them a valid call for only a put and/or patch call
from rest_framework.decorators import list_route
class MessageViewSet(viewsets.ModelViewSet):
#list_route(methods=['Patch', 'PUT'])
def mark_read(self, request):
queryset = Message.objects.update(isread=True)
return Response({'read':queryset})
Thanks to #ivan-semochkin and #Shaumux for replies. Advices were really helpful.
That is my route. I used detail_route instead of list_route.
#detail_route(methods=['get','put'], url_name='mark_read/')
def mark_read(self, request, pk=None):
queryset = Message.objects.filter(pk=pk).update(isread=True)
return Response({'read':queryset})
Now 'isread' value is changing wnen i visit 'mark_read' page.
Link: "api/get_messages/pk/mark_read"
Does anyone know, is it posslible to make links looking the next way:
"api/get_messages" - list, "api/mark_read/pk" - changing isread value.
Is it possible to create something like this? "api/mark_read?=pk"

decorate as_view() with extra context

I want to call class-based generic view with extra context from my method (view). Error that I get is as_view() takes exactly 1 argument (4 given) . I'm using django-userena.
Code that executes this is:
return userena_views.ProfileListView.as_view(request,template_name='userena/profil.html', extra_context=projekti)
In urls.py I have this line:
url(r'^accounts/(?P<username>[\.\w-]+)', userena_views.ProfileListView.as_view(template_name='userena/profil.html', extra_context=Projekat.objects.all), name='userena_profile_list'),
Why are these two different? What am I doing wrong?
this is due to how url functions. you can use kwargs to pass the parameters, and define a url pattern as follows:
url(r'^accounts/(?P<username>[\.\w-]+)', userena_views.ProfileListView.as_view(), name='userena_profile_list', kwargs={'template_name':'userena/profil.html', 'extra_context':Projekat.objects.all}),
EDIT
I misunderstood your question, sorry.
Then, trying to answer your question correctly... your code should be like this:
your_callable_view = userena_views.ProfileListView.as_view()
return your_callable_view(request, template_name='userena/profil.html', extra_context=projekti)
the reason is ProfileListView.as_view() returns a function that have to be called with parameters. url() do this for you, this is why it works in your ulrpatterns and not in your code. The only parameter as_view() is requiring is self.
Class based views can provide extra context data via a get_context_data method.
In the example below from the Django documentation, book_list is added to the DetailView context. The same method works for FormViews as well.
from django.views.generic import DetailView
from books.models import Book, Publisher
class PublisherDetailView(DetailView):
model = Publisher
def get_context_data(self, **kwargs):
# Call the base implementation first to get context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['book_list'] = Book.objects.all()
return context

How to use current logged in user as PK for Django DetailView?

When defining URL patterns, I am supposed to use a regular expression to acquire a PK from the URL.
What if I want a URL that has no PK, and if it's not provided, it will use the currently logged in user? Examples:
visiting /user will get a DetailView of the currently logged in user
/user/edit will show an UpdateView for the currently logged in user
I tried hard-coding the pk= in the Detail.as_view() call but it reports invalid keyword.
How do I specify that in the URL conf?
My sample code that shows PK required error when visiting /user URL:
urlpatterns = patterns('',
url(r'user/$',
DetailView.as_view(
model=Account,
template_name='user/detail.html')),
)`
An alternative approach would be overriding the get_object method of the DetailView subclass, something along the line of:
class CurrentUserDetailView(UserDetailView):
def get_object(self):
return self.request.user
Much cleaner, simpler and more in the spirit of the class-based views than the mixin approach.
EDIT: To clarify, I believe that two different URL patterns (i.e. one with a pk and the other without) should be defined separately in the urlconf. Therefore they could be served by two different views as well, especially as this makes the code cleaner. In this case the urlconf might look something like:
urlpatterns = patterns('',
url(r"^users/(?P<pk>\d+)/$", UserDetailView.as_view(), name="user_detail"),
url(r"^users/current/$", CurrentUserDetailView.as_view(), name="current_user_detail"),
url(r"^users/$", UserListView.as_view(), name="user_list"),
)
And I've updated my example above to note that it inherits the UserDetailView, which makes it even cleaner, and makes it clear what it really is: a special case of the parent view.
As far as I know, you can't define that on the URL definition, since you don't have access to that information.
However, what you can do is create your own mixin and use it to build views that behave like you want.
Your mixin would look something like this:
class CurrentUserMixin(object):
model = Account
def get_object(self, *args, **kwargs):
try:
obj = super(CurrentUserMixin, self).get_object(*args, **kwargs)
except AttributeError:
# SingleObjectMixin throws an AttributeError when no pk or slug
# is present on the url. In those cases, we use the current user
obj = self.request.user.account
return obj
and then, make your custom views:
class UserDetailView(CurrentUserMixin, DetailView):
pass
class UserUpdateView(CurrentUserMixin, UpdateView):
pass
Generic views uses always RequestContext. And this paragraph in the Django Documentation says that when using RequestContext with auth app, the template gets passed an user variable that represents current user logged in. So, go ahead, and feel free to reference user in your templates.
You can get the details of the current user from the request object. If you'd like to see a different user's details, you can pass the url as parameter. The url would be encoded like:
url(r'user/(?P<user_id>.*)$', 'views.user_details', name='user-details'),
views.user_details 2nd parameter would be user_id which is a string (you can change the regex in the url to restrict integer values, but the parameter would still of type string). Here's a list of other examples for url patterns from the Django documentation.

Categories

Resources