Django用户个人资料未更新

时间:2019-03-04 17:43:13

标签: django django-users

我正在建立一个网站,用户可以在其中查看其个人资料并更新详细信息(例如电子邮件,密码等)/删除帐户。但是用户根本不承认更新表格。我正在使用标准的内置用户模型。

forms.py:

class UserDetailsForm(forms.ModelForm):
    password = forms.CharField(widget = forms.PasswordInput())
class Meta:
    model = User
    fields = ('first_name','last_name','email','password','is_active')

views.py:

@login_required
def edit_profile(request):
    user = User.objects.get(username=request.user)
    form = UserDetailsForm(request.POST or None,
                       initial={'first_name':user.first_name,
                                'last_name':user.last_name,
                                'email':user.email,
                                'password':user.password,
                                'is_active':user.is_active,})
    if request.method == 'POST':
        if form.is_valid():
            user.save()
            messages.info(request, 'This is a debug message')
            return HttpResponseRedirect(reverse('account'))

    context = {"form": form}

return render(request, "iFood/user-account.html", context)    

user-profile.html:

...
<form method="POST" action="{% url 'account' %}" class="" enctype="multipart/form-data">
{% csrf_token %}
        {{form.as_p}}
        <input type="submit" name="" value="Edit and Save">
            {% if messages %}
            <ul class="messages">
                {% for message in messages %}
                <li class="{{ message.tags }}">
                    {{ message }}
                </li>
                {% endfor %}
            </ul>
            {% endif %}

1 个答案:

答案 0 :(得分:1)

首先,您不能像这样更改密码。您应该使用用户输入的密码,并使用user_obj.set_password()进行设置:

Django docs: Change password

对于您的表单:

您用user.save()做错了。用户对象没有任何可保存的。您应该使用form.save()保存表单。

request.user也是实际的用户对象,而不是用户名。

forms.py:

class UserDetailsForm(forms.ModelForm):
    password = forms.CharField(widget = forms.PasswordInput())
    class Meta:
        model = User
        fields = ('first_name','last_name','email'','is_active')

views.py:

@login_required
def edit_profile(request):
    user = request.user
    form = UserDetailsForm(request.POST or None, instance=user)
    if request.method == 'POST':
        if form.is_valid():
            # Save the changes but password
            form.save()

            # Change password
            new_password = form.cleaned_data.get('password')
            if new_password:
                user.set_password(new_pass)
            messages.info(request, 'This is a debug message')
            return HttpResponseRedirect(reverse('account'))

    context = {"form": form}

    return render(request, "iFood/user-account.html", context)