我一直在嘗試使用form.py中的表單呈現HTML,但是這不起作用,只是無法加載而沒有錯誤消息。另外,控制檯中也沒有消息,所以我很難解決這個問題。請看看並告訴我哪個部分是錯誤的。Django:Forms.py中的表單不會顯示在HTML中
這是urls.py
url(r'^profile/(?P<username>[-\w.]+)/$', views.profile, name='profile'),
url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'),
url(r'^password_change_done/$', views.password_change_done, name='password_change_done'),
forms.py
class PasswordChangeForm(forms.Form):
oldpassword = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'your old Password', 'class' : 'span'}))
newpassword1 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'New Password', 'class' : 'span'}))
newpassword2 = forms.CharField(max_length = 20, widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm New Password', 'class' : 'span'}))
class Meta:
model = User
fields = ("username",)
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self._meta.model.USERNAME_FIELD in self.fields:
self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True})
def clean(self):
if 'newpassword1' in self.cleaned_data and 'newpassword2' in self.cleaned_data:
if self.cleaned_data['newpassword1'] != self.cleaned_data['newpassword2']:
raise forms.ValidationError(_("The two password fields did not match."))
return self.cleaned_data
def save(self, commit=True):
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
views.py
@login_required
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
print("username is "+username)
if form.is_valid():
#form.save()
update_session_auth_hash(request, form.user)
form.save()
print("A")
return HttpResponseRedirect('/blog/password_change_done/')
else:
update_session_auth_hash(request, form.user)
form.save()
print("B")
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
else:
print("C")
form = PasswordChangeForm(user=request.user)#unbound
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
profile.html(其中password_change應該被加載。)
<h2>password change</h2>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% else %}
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'blog:password_change' user.username %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button-primary">password change</button></div>
</form>
你能看到頁面的其餘部分嗎?只有這種形式沒有加載? –
@AlexanderTyapkov頁面的其餘部分正確加載,我想這是因爲其他部分是用HTML構建的。只有這種形式沒有加載。 – camila
你沒有向模板提供表單,你在視圖中看到過嗎? –