Django - 如何将“POST”信息从一个视图发送到另一个视图

时间:2014-01-17 02:24:35

标签: django django-authentication django-registration http-redirect django-login

我有一份注册表格,如果注册表格填写正确且有效,我想自动登录用户。登录视图位于URL

/login/

这是该URL链接到的登录视图(它是通用登录视图):

def login(request, template_name='registration/login.html',
      redirect_field_name=REDIRECT_FIELD_NAME,
      authentication_form=AuthenticationForm,
      current_app=None, extra_context=None):

    if request.method == "POST":
        form = authentication_form(data=request.POST)
        if form.is_valid():

            # Ensure the user-originating redirection url is safe.
            if not is_safe_url(url=redirect_to, host=request.get_host()):
                redirect_to = resolve_url(settings.LOGIN_REDIRECT_URL)

            # Okay, security check complete. Log the user in.
            auth_login(request, form.get_user())

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()

            return HttpResponseRedirect(redirect_to)

else:
    form = authentication_form(request)

request.session.set_test_cookie()

current_site = get_current_site(request)

context = {
    'form': form,
    redirect_field_name: redirect_to,
    'site': current_site,
    'site_name': current_site.name,
}
if extra_context is not None:
    context.update(extra_context)
return TemplateResponse(request, template_name, context,
                        current_app=current_app)

现在,处理注册的视图是:

def registrationView(request):
    if request.method == 'POST':
    form = RegistrationForm(request.POST)

    if form.is_valid():
        user = User.objects.create_user(
        username=form.clean_data['username'],
        password=form.clean_data['password1'],
        email=form.clean_data['email']
        )
        return HttpResponseRedirect('/login/')

现在,当我重定向到

/login/

在注册视图中,我是否可以将用户名和密码作为“POST”信息发送,以便在到达登录视图时

if request.method == "POST":

评估为真?

1 个答案:

答案 0 :(得分:2)

我认为,您应该将当前用户设置为您的会话,而不是尝试做这样的魔术。

def registrationView(request):
    if request.method == 'POST':
    form = RegistrationForm(request.POST)

    if form.is_valid():
        user = User.objects.create_user(
        username=form.cleaned_data['username'],
        password=form.cleaned_data['password1'],
        email=form.cleaned_data['email']
        )
        login(request, user) 

        return HttpResponseRedirect('...')

查看https://docs.djangoproject.com/en/1.5/topics/auth/default/#django.contrib.auth.login