【问题标题】:Access editing profile only by profile owner using UserPassesTestMixin showing error?仅由配置文件所有者使用 UserPassesTestMixin 访问编辑配置文件显示错误?
【发布时间】:2020-11-23 23:37:50
【问题描述】:

我已经成功地为每个用户创建了个人资料页面,每个用户都应该编辑他们自己的个人资料。在模型中,我使用了 AbstractUser 模型。对于编辑权限,我已经导入了 UserPassesTestMixin。

这是我的 models.py

class Profile(AbstractUser):
    
    name=models.CharField(max_length=30, blank=True)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birthdate = models.DateField(null=True, blank=True)

这是我的 views.py

class ProfileDetailView(DetailView):
    template_name='profile.html'
    model=Profile
    def get_user_profile(self,pk):
        return get_object_or_404(Profile,pk=pk)
    

class ProfileEditView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
    model=Profile
    template_name='profile_edit.html'
    fields=['name','bio','birthdate','location','gender',]
    login_url='login'
    success_url = reverse_lazy('home')
    def get_user_profile_edit(self,pk):
        return get_object_or_404(Profile,pk=pk)

    def test_func(self):
        obj = self.get_object()
        return obj.username == self.request.user

    

问题是当登录的用户想要编辑它的配置文件时,它显示 403 被禁止。没有用户可以编辑他们的个人资料。在测试功能中应该使用什么来解决这个问题?

【问题讨论】:

    标签: django django-models django-views django-templates django-permissions


    【解决方案1】:

    由于Profile是用户模型,这意味着obj应该是request.user

    class ProfileEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
        model=Profile
        template_name='profile_edit.html'
        fields=['name','bio','birthdate','location','gender',]
        login_url='login'
        success_url = reverse_lazy('home')
        
        def get_user_profile_edit(self,pk):
            return get_object_or_404(Profile,pk=pk)
    
        def test_func(self):
            return self.get_object() == self.request.user

    但是你本身并不需要这个,你可以简单地使用 request.user 作为对象本身:

    class ProfileEditView(LoginRequiredMixin, UpdateView):
        model=Profile
        template_name='profile_edit.html'
        fields=['name','bio','birthdate','location','gender',]
        login_url='login'
        success_url = reverse_lazy('home')
        
        def get_object(self, *args, **kwargs):
            return self.request.user

    在这种情况下,视图不需要主键,因为访问该视图的人只会看到他们自己的个人资料进行编辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-02
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多