2017-02-17 30 views
0

我一直在嘗試使用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> 
+0

你能看到頁面的其餘部分嗎?只有這種形式沒有加載? –

+0

@AlexanderTyapkov頁面的其餘部分正確加載,我想這是因爲其他部分是用HTML構建的。只有這種形式沒有加載。 – camila

+0

你沒有向模板提供表單,你在視圖中看到過嗎? –

回答

0

下面是一個例子如何change_password視圖可以實現

from django.contrib import messages 
from django.contrib.auth import update_session_auth_hash 
from django.contrib.auth.forms import PasswordChangeForm 
from django.shortcuts import render, redirect 

def change_password(request): 
    if request.method == 'POST': 
     form = PasswordChangeForm(request.user, request.POST) 
     if form.is_valid(): 
      user = form.save() 
      update_session_auth_hash(request, user) # Important! 
      messages.success(request, 'Your password was successfully updated!') 
      return redirect('accounts:change_password') 
     else: 
      messages.error(request, 'Please correct the error below.') 
    else: 
     form = PasswordChangeForm(request.user) 
    return render(request, 'accounts/change_password.html', { 
     'form': form 
    }) 

看一看到GET請求相關的部分。您必須創建表單並使用上下文呈現頁面。您應該爲上下文提供表單。

在你的情況下,你創建表單並直接重定向到配置文件頁面。這就是爲什麼你看到空的表單頁面。

+0

這個password_change表單應該在配置文件url中。我試圖在一個HTML中加載兩個表單。是不可能的? – camila

+0

@camila這是可能的,但你沒有提供給模板的形式..看看我提供的代碼的最後一行。在那裏,我給了change_password.html一個表單 –