Django不允许用户访问pag

2024-09-30 04:39:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在视图.py在

class DashboardNewProfile(LoginRequiredMixin, CreateView):
    form_class = ProfileForm
    model = Profile
    queryset = Profile.objects.all()
    template_name = 'profile/profile_create.html'

    def _usercheck(self):
        u = self.request.user
        qs = Profile.objects.all().filter(u)
        if qs is None:
            return HttpResponseRedirect('/profile/create/')
        else:
            return HttpResponseRedirect('/profile/view/')

    def get_form_kwargs(self):
        kwargs = super(DashboardNewProfile, self).get_form_kwargs()
        kwargs.update({'user': self.request.user})
        kwargs.update({'slug': self.request.user.username})
        return kwargs

在网址.py在

^{pr2}$

我该怎么做? 如果登录的用户已经有一个与数据库中的配置文件对象关联的配置文件。我不希望用户访问URL('/profile/create/'),而不是希望用户自动重定向到另一个URL('/profile/view')


Tags: 用户pyselfformreturnobjectsrequestcreate
1条回答
网友
1楼 · 发布于 2024-09-30 04:39:27

为了更改LoginRequiredMixin的功能,您需要重写dispatch方法,该方法检查用户是否登录。看起来您真正想要的是user_passes_test装饰器:

def has_no_profile(user):
    # Receives the request.user object from user_passes_test
    # Note that you need to filter using model_field=value
    # Returns true if the user has no profile, false otherwise
    return not Profile.objects.filter(user=user).exists()

# Method decorator attaches the user_passes_test to the class based view
@method_decorator(user_passes_test(has_no_profile, login_url='/profile/view/'), name='dispatch')
class DashboardNewProfile(CreateView):
    ...

Documentation for user_passes_test

Documentation for method_decorator

Documentation for filtering

请注意,如果您愿意,还有一个UserPassesTestMixin,我只是通常将这些测试分开,以便它们可以在其他视图中使用,并且更喜欢装饰器的外观。在

相关问题 更多 >

    热门问题