Django注册:阻止登录(已认证)访问注册页面结果到所有用户的注册页面被拒绝

时间:2019-04-05 18:57:02

标签: view django-views django-authentication django-registration

大家好, 我目前正在将Django-registration-redux用于django项目

为防止高级用户访问“注册”页面和“登录”页面,我需要对服务于这两个页面的 views.py 进行一些更改。  我用

if self.request.user.is_authenticated: return redirect('mainhomepage')

在此链接中建议的注册和登录视图中,我最近在其下方发布了Preventing already authenticated user from accessing the register page

提供的解决方案行之有效,但同时也阻止未登录的用户访问注册页面

这是注册页面的views.py

class RegistrationView(_RequestPassingFormView):
"""
Base class for user registration views.

"""
disallowed_url = 'registration_disallowed'
form_class = REGISTRATION_FORM
http_method_names = ['get', 'post', 'head', 'options', 'trace']
success_url = None
template_name = 'registration/registration_form.html'

@method_decorator(sensitive_post_parameters('password1', 'password2'))
def dispatch(self, request, *args, **kwargs):
    """
    Check that user signup is allowed before even bothering to
    dispatch or do other processing.

    """
    if self.request.user.is_authenticated:
        return redirect('mainhomepage')
    if not self.registration_allowed(request):
        return redirect(self.disallowed_url)
    return super(RegistrationView, self).dispatch(request, *args, **kwargs)

def form_valid(self, request, form):
    new_user = self.register(request, form)
    success_url = self.get_success_url(request, new_user)

    # success_url may be a simple string, or a tuple providing the
    # full argument set for redirect(). Attempting to unpack it
    # tells us which one it is.
    try:
        to, args, kwargs = success_url
        return redirect(to, *args, **kwargs)
    except ValueError:
        return redirect(success_url)

def registration_allowed(self, request):
    """
    Override this to enable/disable user registration, either
    globally or on a per-request basis.

    """
    return True

def register(self, request, form):
    """
    Implement user-registration logic here. Access to both the
    request and the full cleaned_data of the registration form is
    available here.

    """
    raise NotImplementedError

如您所见:我添加了

if self.request.user.is_authenticated:
        return redirect('mainhomepage')

,以便仅将经过身份验证的用户重定向到主主页网址

不过,已认证和未认证的内容都会自动定向到该页面

请采取其他措施来解决此问题。已认证和未认证的都将重定向到该页面。同时, if语句仅表示应将经过身份验证的用户重定向。

短时输入,退出登录后,我将无法再访问注册页面,因为无论登录状态如何,用户都将重定向到主页。因此,无法在页面上进行新的注册...请提供任何帮助?

0 个答案:

没有答案