我是django的初学者,我想在同一个视图中放两个不同的寄存器。但我也想制作自己的表格,并在动作标签上添加不同的网址。我是用一种形式做的,但是当我把第二种形式用掉时,这不起作用。
这是我的models.py
:
from django.db import models
class userProfile(models.Model):
usermail = models.CharField(max_length=264)
username = models.CharField(max_length=264)
userpass = models.CharField(max_length=264)
class companyProfile(models.Model):
companymail = models.CharField(max_length=264)
companyname = models.CharField(max_length=264)
companypass = models.CharField(max_length=264)
这是我的forms.py
:
from django import forms
from Pruebas_app.models import companyProfile, userProfile
class registerCompany(forms.Form):
companypassconf = forms.CharField()
class Meta():
model = companyProfile
fields = ['companymail','companyname', 'companypass']
labels = {'companymail': '', 'companyname': '', }
widgets = { 'companypass': forms.PasswordInput(),}
class registerUser(forms.Form):
userpassconf = forms.CharField()
class Meta():
model = companyProfile
fields = ['usermail','username', 'userpass']
labels = {'usermail': '', 'username': '', }
widgets = {'userpass': forms.PasswordInput(),}
这是我的template
:
<form action="{ url 'user_register'}" method="post">
<input type="text" name="username">
<input type="email" name="usermail">
<input type="password" name="userpass">
<input type="password" name="userpassconf">
<input type="submit" value="Register">
</form>
<form action="{ url 'company_register'}" method="post">
<input type="text" name="companyname">
<input type="email" name="companymail">
<input type="password" name="companypass">
<input type="password" name="companypassconf">
<input type="submit" value="Register">
</form>
这是我的views.py
:
from django.shortcuts import render
from Pruebas import forms
from Pruebas.forms import registerCompany, registerUser
from django.http import HttpResponse
def user_register(request):
form = forms.registerUser()
regd = False
passmatch = True
if request.method == "POST":
form = registerUser(request.POST)
if form.is_valid():
form_data = form.cleaned_data
print (form_data.get("userpass"))
if form_data.get("userpass") == form_data.get("userpassconf"):
passmatch = True
form.save()
regd = True
print("saved")
else:
passmatch = False
else:
print("error")
red = 'Pruebas/register.html'
regd = False
return render(request, 'Pruebas/register.html', {'registered': regd, "matchPass": passmatch})
我尝试将表单中的数据发送到一个唯一的视图,但我只能从用户注册表中恢复数据。我不知道我做错了什么,或者我要做些什么来使这个工作,请帮忙!
答案 0 :(得分:0)
在表单中,不要定义元类,只显示与使用userpassconf一样的字段。您甚至可以将表单组合成一个表单,然后只需处理视图中的数据,就像您已经在做的那样,但是创建两个实例。类似的东西:
if request.method == "POST":
form = registerUser(request.POST)
if form.is_valid():
form_data = form.cleaned_data
if form_data.get("userpass") == form_data.get("userpassconf"):
passmatch = True
new_user = userProfile()
new_user.usermail = form_data.get("usermail")
new_user.username = form_data.get("username")
new_user.save()
所以基本上你只是创建一个你要保存的模型的实例,并将表单数据分配给它,然后保存它。不要忘记将模型导入视图文件。