各位大家好!我有表格问题,下面是代码,任何帮助将不胜感激......
views.py
def my_registration_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],
first_name=form.cleaned_data['first_name'],
last_name=form.cleaned_data['last_name'],
email=form.cleaned_data['email'],
password=form.cleaned_data['password'],)
user.save()
return HttpResponseRedirect(reverse('profile', args=[user.id]))
else:
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
else:
form = MyForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
我的forms.py工作正常
class MyForm(forms.Form):
username = forms.CharField(max_length=25)
first_name = forms.CharField(max_length=25)
last_name = forms.CharField(max_length=25)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput())
这是我的forms.py,当它被替换时,停止显示字段。
class MyForm(forms.Form):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
这里是register.html
<form action="{% url 'register' %}" method="post">{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='Submit' />
</form>
答案 0 :(得分:3)
将forms.Form替换为forms.ModelForm。这应该有用。
class MyForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
答案 1 :(得分:0)
在您的示例中,您没有提到forms.typeField
,请参阅以下示例:
对于你的Html页面,有些事情是这样的:
<form action="/your-name/" method="post">
<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
在forms.py中,您应该有字段
form.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
有关更多示例和参考,请参阅: Django working with forms
答案 2 :(得分:0)
试试这样..
返回render_to_response(&#39; register.html&#39;,{&#39; form&#39;:form},context_instance = RequestContext(request))
形式不是肯定的...而是dict作为对象让我们做这样的迭代...
答案 3 :(得分:0)
试试这个;
form = MyForm(request.POST) if request.method ==&#39; POST&#39;:
这是一个逻辑错误,您的表单应该是最重要的。