Django:form.py中的表单不以HTML格式显示

时间:2017-02-17 03:16:20

标签: python html django forms

我一直在尝试使用我在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>

1 个答案:

答案 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请求相关的部分。在那里,您必须创建表单并使用上下文呈现页面。您应该为上下文提供表单。

在您的情况下,您可以创建表单并在此之后直接重定向到配置文件页面。这就是你看到空表单页面的原因。