Django覆盖自定义登录重定向URL

时间:2017-02-18 14:47:34

标签: python django

我想在登录后将用户重定向到主页面。在我的模板中,我有这个,

<input type="checkbox" name={this.props.id} value={this.props.value} id={this.props.id} />
<label htmlFor={this.props.id}></label> {this.props.text}

问题是用户在登录后无法重定向到主页面,<a href="{% url 'auth_login' %}?next={% url 'main_page' %}">Login and Work</a> 将接管并将用户重定向到我在设置文件中指定的网址。

如何让Django使用模板中设置的settings.LOGIN_REDIRECT_URL网址,而不是强行使用?next

1 个答案:

答案 0 :(得分:1)

以下是如何在登录视图中执行此操作的示例。请注意REDIRECT_FIELD_NAME:

def login(request, login_form=AuthenticationForm, template_name='accounts/login.html',
          extra_context=None):

  form = login_form()

  if request.method == 'POST':
    form = login_form(request.POST, request.FILES)

    if form.is_valid():
      identification, password, remember_me = (form.cleaned_data['identification'],
                                               form.cleaned_data['password'],
                                               form.cleaned_data['remember_me'])
      user = authenticate(identification=identification, password=password)

      if user.is_active:
        signin(request, user)

        redirect_to = login_redirect(request.GET.get(REDIRECT_FIELD_NAME), user)
        return HttpResponseRedirect(redirect_to)
      else:
        return redirect(reverse('profile_disabled', kwargs={'username': user.username}))

  if not extra_context: extra_context = dict()
  extra_context.update({
    'form': form,
    'next': request.GET.get(REDIRECT_FIELD_NAME),
  })

  return ExtraContextTemplateView.as_view(template_name=template_name,
                                          extra_context=extra_context)(request)