如何在同一页面上显示两个表单?

时间:2012-10-30 12:03:35

标签: django

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

这是我的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'),

access.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(订单)时:

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

仅显示登录表单

1 个答案:

答案 0 :(得分:1)

如果您在return声明中更改表单变量的名称,即

,该怎么办?
{'formRegister':form}

和另一个:

{'formLogin':form}

<强>更新

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

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

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

其他替代方案包括:

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

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