0

如何在同一页面上显示两个表单?我会感谢你的帮助

这是我的views.py:

def register_user(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(username=form.cleaned_data['username'], email=form.cleaned_data['email'], password=form.cleaned_data['password'])
            user.save()
            user_profil = UserProfil(user=user, name=form.cleaned_data['name'], last_name=form.cleaned_data['last_name'],city=form.cleaned_data['city'])
            user_profil.save()
            return HttpResponseRedirect('/profile/')
        return render_to_response('access.html', {'formRegister':form}, context_instance=RequestContext(request))
    else:
        form = RegistrationForm()
        return render_to_response('access.html', {'formRegister':form}, context_instance=RequestContext(request))


def login_user(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/profile/')
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if forml.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user_profil = authenticate(username= username, password=password)
            if user_profil is not None:
                login(request, user_profil)
                return HttpResponseRedirect('/profile/')
            else:
                return HttpResponseRedirect('/login/')
        return render_to_response('access.html', {'formLogin':form}, context_instance=RequestContext(request))
    else:
        form = LoginForm()
        context = {'formLogin':form}
        return render_to_response('access.html', context, context_instance=RequestContext(request))

这是我的 urls.py

url(r'^access/$','users.views.register_user'),
url(r'^access/$','users.views.login_user'),

访问.html:

<form action="" method="post">{%csrf_token%}
{{ formRegister.as_p }}
<p><input type="submit" value="Rejestruj"/></p>
</form>

<hr>


<form action="" method="post">{%csrf_token%}
{{ formLogin.as_p }}
<input type="submit" value="Login"/>
</form>

有一个模板(access.html)和两个视图

当我替换 urls.py(order) 时:

url(r'^access/$','users.views.login_user'),
url(r'^access/$','users.views.register_user'),

仅显示登录表单

4

1 回答 1

1

return如果您在语句中更改表单变量的名称怎么办,即

{'formRegister':form}

另一个:

{'formLogin':form}

更新:

在您的 url 文件中,您可以执行以下操作:

url(r'^access/login/$','users.views.login_user'),
url(r'^access/register/$','users.views.register_user'),

仍将使用相同的模板,但使用不同的视图来处理表单。

其他替代方案包括:

  1. 将不同的 URL 放在两个表单的 action 属性中。然后你将有两个不同的视图函数来处理这两种不同的形式。

  2. 从 POST 数据中读取提交按钮的值。您可以判断单击了哪个提交按钮,然后处理逻辑。

于 2012-10-30T12:10:14.257 回答