如何确保用户仅进入自己创建的对象的DetailView,Listview和UpdateView

时间:2019-05-06 12:47:10

标签: django django-views

我已经创建了一个简单的应用程序,已登录的用户可以在其中提交会议的会话,查看其提交的结果,查看其提交的列表以及编辑其提交(他们不应有权访问其他用户)提交)。我正在使用django的基于类的视图(CreateView,DetailView,ListView,UpdateView)。

但是,我在权限方面苦苦挣扎。除updateview之外的所有视图均有效,但是如果我使用未登录的用户名直接键入url,则可以看到其提交的内容。

我还怀疑权限与我无法使updateview正常工作的原因相同。

我想念什么?有没有更好的方法来避免在网址中使用用户名和插件?我似乎找不到有关如何执行此类操作的任何示例或提示。我是一个初学者,所以可能会错过一些对这里和那里的基础知识的了解。

我试图了解User模型的工作原理,因为我设法找到了一种以受保护的方式创建,查看和编辑用户详细信息的方法。不过,我在那里依赖函数视图,而且似乎无法将这种方法应用于提交应用程序。

models.py

class Hsession(models.Model):

submitter = models.ForeignKey(User, related_name="submittersessions", on_delete=models.CASCADE)
submission_date = models.DateTimeField(auto_now=True)
session_title = models.CharField("session title", max_length=40, default='')
session_description = models.TextField("session description", max_length=350, default='')
slug = models.SlugField(allow_unicode=True, unique=True)

def save(self, *args, **kwargs):
    self.slug = slugify(self.session_title)
    super().save(*args, **kwargs)

def get_absolute_url(self):
    return reverse("submission:detail-single", kwargs={"username": self.submitter.username, "slug": self.slug})

网址:

urlpatterns = [
    path("", views.CreateSubmission.as_view(), name="create"),
    path("by/<username>/<slug>",views.SubmissionDetail.as_view(),name="detail-single"),
    path("by/<slug>/edit",views.EditSubmission.as_view(), name="edit"),
    path("by/<username>/",views.SubmissionList.as_view(), name="list"),
    ]

views.py

class CreateSubmission(LoginRequiredMixin, generic.CreateView):

    fields = ('session_title', 'session_description', 'subject_category')
    model = models.Hsession

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.submitter = self.request.user
        self.object.save()
        return super().form_valid(form)

class SubmissionList(LoginRequiredMixin, generic.ListView):

    model = models.Hsession
    template_name = "submission/user_hsession_list.html"

    def get_queryset(self):

        try:
            self.hsession_submitter = User.objects.prefetch_related("submittersessions").get(
                username__iexact=self.kwargs.get("username")
            )
        except User.DoesNotExist:
            raise Http404
        else:
            return self.hsession_submitter.submittersessions.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["hsession_submitter"] = self.hsession_submitter
        return context

class SubmissionDetail(LoginRequiredMixin, generic.DetailView):

    model = models.Hsession

     def get_queryset(self):
         queryset = super().get_queryset()
         return queryset.filter(
            submitter__username__iexact=self.kwargs.get("username")
         )

class EditSubmission(LoginRequiredMixin, generic.UpdateView):
    model = models.Hsession
    fields = ('session_title', 'session_description', 'subject_category')
    template_name = 'submission/hsession_update.html'
    success_url = 'submission/hsession_detail.html'

forms.py

class UserSubmissionForm(ModelForm):
    class Meta:
        model = Hsession
        fields = ['session_title','session_description', 'subject_category']

class EditSubmissionForm(ModelForm):
    class Meta:
        model = Hsession
        fields = ['session_title','session_description', 'subject_category']

1 个答案:

答案 0 :(得分:0)

您应该这样使用UserPassesTestMixin

from django.contrib.auth.mixins import UserPassesTestMixin

class EditSubmission(UserPassesTestMixin,LoginRequiredMixin, generic.UpdateView):
   model = models.Hsession
   fields = ('session_title', 'session_description', 'subject_category')
   template_name = 'submission/hsession_update.html'
   success_url = 'submission/hsession_detail.html'

   def test_func(self):
       //should return true if he have access
       if self.request.user.is_authenticated:
          slug = self.kwargs['slug']
          obj = self.model.objects.get(slug=slug)
          login_user = self.request.user
          return login_user.pk == obj.submitter.pk
       else:
           return False     

有关更多信息,UserPassesTestMixin