Django - 模板显示编辑的用户上下文信息,尽管ValidationError

时间:2017-08-02 17:47:36

标签: django django-forms django-templates django-views

您好我正在使用表单来编辑用户的个人资料。它在成功提交时正确更新字段,没有任何验证错误。我遇到的问题是,如果表单在提交时确实返回了验证错误并且我在表单上更改了名称,则模板将显示此新名称而不是旧名称。我假设这是因为它使用POST请求提供的用户上下文。在表单实际成功提交之前,有没有办法正确显示用户的旧名称?以下是我的代码。

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.forms import ModelForm

class UserProfileForm(UserCreationForm):
    first_name = forms.CharField(label="First Name", required=True)
    last_name = forms.CharField(label="Last Name", required=True)
    email = forms.EmailField(label="Email", required=True)

    class Meta:
        model = User
        fields = ("first_name", "last_name", "email", "username", "password1", "password2")

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email:
            if User.objects.filter(email=email).exists():
                raise forms.ValidationError('This email is already in use.')
        return email

    def save(self, commit=True):
        user = super(UserProfileForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user


class EditProfileForm(ModelForm):
    first_name = forms.CharField(label="First Name", required=True)
    last_name = forms.CharField(label="Last Name", required=True)
    email = forms.EmailField(label="Email", required=True)
    password1 = forms.CharField(label="New Password", widget=forms.PasswordInput)
    password2 = forms.CharField(label="Repeat New Password", widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ("first_name", "last_name", "email", "username", "password1", "password2")

    def clean_email(self):
        email = self.cleaned_data.get('email')
        if email:
            if User.objects.filter(email=email).exists():
                raise forms.ValidationError('This email is already in use.')
        return email

    def save(self, commit=True):
        user = super(EditProfileForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

views.py

def register(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            form.save()
            new_user = authenticate(username=form.cleaned_data['username'],
                                password=form.cleaned_data['password1'])
            login(request, new_user)
            return redirect('/overview')
    else:
        if request.user.is_authenticated():
            return redirect('/overview')
        else:
            form = UserProfileForm()

    return render(request, "/register.html", {'form': form})

@login_required
def edit_profile(request):
    if request.method == 'POST':
        print request.POST
        form = EditProfileForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            return redirect('/profile')
    else:
        form = EditProfileForm()

    return render(request, '/edit_profile.html', {'form': form})

navbar.html

<li class="">
    <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
      <img src="/ui/assets/images/user.png" alt="">{{ user.first_name }} {{ user.last_name }}
      <span class=" fa fa-angle-down"></span>
    </a>
    <ul class="dropdown-menu dropdown-usermenu pull-right">
      <li><a href="/profile/"> Profile</a></li>
      <li><a href="/logout/"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li>
    </ul>
</li>

1 个答案:

答案 0 :(得分:0)

从db中获取用户的单独实例以与表单一起使用。这样,在验证表单时,不会修改request.user

user = User.objects.get(id=request.user.id)
form = EditProfileForm(request.POST, instance=user)