Restrict `UpdateView` dataset for authenticated user in Class Based Views

倾然丶 夕夏残阳落幕 提交于 2019-12-03 22:46:07

How about something like this:

from django.contrib.auth.views import redirect_to_login


class ProfileUpdate(UpdateView):
    [...]

    def user_passes_test(self, request):
        if request.user.is_authenticated():
            self.object = self.get_object()
            return self.object.user == request.user
        return False

    def dispatch(self, request, *args, **kwargs):
        if not self.user_passes_test(request):
            return redirect_to_login(request.get_full_path())
        return super(ProfileUpdate, self).dispatch(
            request, *args, **kwargs)

In this example, the user is redirected to default LOGIN_URL. But you can easily change it . to redirect user to their own profile.

freezed

To avoid access to data unrelated to the connected user when using Class Based View (CBV), you can use Dynamic filtering and define queryset instead on model attributes.

If you have a book.models with a ForeignKey (named user here) on auth.models.user you can easily restrict acces like this :

# views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView
from books.models import Book

class BookList(LoginRequiredMixin, ListView):

    def get_queryset(self):
        return Book.objects.filter(user=self.request.user)

See more explanation in the documentation about CBV - Viewing subsets of objects

Specifying model = Publisher is really just shorthand for saying queryset = Publisher.objects.all(). However, by using queryset to define a filtered list of objects you can be more specific about the objects that will be visible in the view.

[…]

Handily, the ListView has a get_queryset() method we can override. Previously, it has just been returning the value of the queryset attribute, but now we can add more logic. The key part to making this work is that when class-based views are called, various useful things are stored on self; as well as the request (self.request) this includes the positional (self.args) and name-based (self.kwargs) arguments captured according to the URLconf.

  • your template.html:

{% if request.user.is_authenticated and profile.user == request.user %}
your form
{% else %}
u cannot edit that profile - its not yours...
{% endif %}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!