我想更改以下HTML表单:
@transaction.atomic
def Register(request):
if request.method == "POST":
fname = request.POST['first_name']
lname = request.POST['last_name']
mobile = request.POST['mobile']
"""This section replaces multiple characters with blank value
so that the mobile number has nothing except numeric values
"""
rep = ['+', '-', ' ', '.']
for i in rep:
mobile = mobile.replace(i, '')
company = request.POST['company']
email = request.POST['email']
u = User.objects.create_user(mobile, email, '1234', first_name=fname, last_name=lname)
u.save()
p = UserProfile.objects.create(user=u, company=company, mobile=mobile)
p.save()
return HttpResponse("Registration complete! Please head over to the <a href='/login/'>login page</a> to start using your SMS panel.")
return render(request, "message/register.html", {})
进入Django表单主要是因为我需要学习如何使用它们,我还需要在注册完成之前填写所有字段,我不想要任何可选字段。以下是我从文档中提出的内容。
views.py
@transaction.atomic
def Register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
# I guess this is where I need help. Thanks.
else:
form = RegisterForm()
return render(request, "message/register.html", {'form': form})
register.html
<form method="post" action="">
{% csrf_token %}
{{ form }}
<input type="submit" value="Register"/>
</form>
答案 0 :(得分:1)
在if form.is_valid() == True
django创建了clean_data方法之后,您可以使用该方法将已清理的表单数据调用到您的视图中。
你可能想要这样的东西:
def Register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
fname = form.cleaned_data.get('first_name')
lname = form.cleaned_data.get('last_name')
https://docs.djangoproject.com/en/1.8/ref/forms/api/#django.forms.Form.is_valid
你的Form对象在forms.py中的含义是什么?
答案 1 :(得分:1)
您可以创建表单RegisterForm
,并将移动广告的清算过程添加到clean_mobile
中的forms.py
功能。然后在views.py
中,您可以使用form.cleaned_data
词典访问所有表单数据。
您可以执行以下操作:
<强> forms.py 强>
from django import forms
class RegisterForm(forms.Form):
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
mobile = forms.CharField()
company = forms.CharField(max_length=100)
email = forms.EmailField()
def clean_mobile(self):
mobile = self.cleaned_data['mobile']
rep = ['+', '-', ' ', '.']
for i in rep:
mobile = mobile.replace(i, '')
return mobile
<强> views.py 强>
@transaction.atomic
def Register(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
u = User.objects.create_user(form.cleaned_data['mobile'], form.cleaned_data['email'], '1234', first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'])
u.save()
p = UserProfile.objects.create(user=u, company=form.cleaned_data['company'], mobile=form.cleaned_data['mobile'])
p.save()
return HttpResponse("Registration complete! Please head over to the <a href='/login/'>login page</a> to start using your SMS panel.")
else:
form = RegisterForm()
return render(request, "message/register.html", {'form': form})