在django中编辑用户配置文件而无需输入密码

时间:2015-04-27 15:30:08

标签: python django django-forms django-authentication django-users

这里我试图允许用户修改他们的用户配置文件。有一个名为UserProfile的模型,它与django用户本身保持一对一的关系。以下是views.py

中的代码
@login_required
def edit_profile(request):  
    if request.method == 'POST':
        profile = UserProfile.objects.get(user=request.user)
        profile_form = UserProfileForm(data=request.POST, instance=profile)

        if profile_form.is_valid():

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']
            profile.save()

            return HttpResponseRedirect("/me/login/")

        else:
            print user_form.errors, profile_form.errors
    else:
        user = request.user
        profile = UserProfile.objects.get(user=user)
        profile_form = UserProfileForm(initial={'website':profile.website,'address':profile.address, 'picture':profile.picture})

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

但是,一旦从模板中单击提交按钮,我就会收到一条错误消息,说明需要输入密码。

[27/Apr/2015 14:25:07] "GET /me/edit_profile2/ HTTP/1.1" 200 5080
<ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>password<ul class="errorlist"><li>This field is required.</li></ul></li></ul> 
[27/Apr/2015 14:25:16] "POST /me/edit_profile/ HTTP/1.1" 200 6384

从代码中,我认为UserProfile已经绑定到特定用户,我只允许用户在不触及django的auth用户模型的情况下对UserProfile模型进行更改。我想知道为什么在这种情况下仍然需要用户名和密码。是否可以在没有用户密码的情况下编辑用户配置文件?

以下是从用户模型

扩展的UserProfile
class UserProfile(models.Model):
    # link user profile to the user models
    user = models.OneToOneField(User)

    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to='avatar', blank=True)
    address = models.TextField(blank=True)

    @property
    def stats(self):
        """get statistics for this profile"""
        from tumboon.models import Donation
        return Donation.statistics.for_user(self)

    @property
    def amount_donated(self):
        __doc__ = """get the total amount donated """
        return self.stats['total_amount_donated']

    # Override the __unicode__ to return something meaningful
    def __unicode__(self):
        return self.user.username

class UserForm(forms.ModelForm):
    """Form for User Registration"""

    class Meta:
        model = User
        fields = ('username', 'email', 'password', 'first_name', 'last_name')
        widgets = {
            'username' : forms.TextInput(attrs = {'placeholder': 'Username'}),
            'email'    : forms.TextInput(attrs = {'placeholder': 'Email'}),
            'password'    : forms.TextInput(attrs = {'placeholder': 'Password'}),            
        }

class UserProfileForm(forms.ModelForm):
    """Form for UserProfile"""
    class Meta:
        model = UserProfile
        fields = ('website', 'picture', 'address')

模板上的UserProfileForm在这里:

{% if user.is_authenticated %}
        <form id="user_profile" class="form-horizontal" method="POST" enctype="multipart/form-data" action="/me/edit_profile/"> 
            {% csrf_token %}
            <h3>User Info</h3>
            <hr />
            <div class="form-group">
                <label class="col-xs-2" for="{{ user_form.picture.id_for_label }}">Picture: </label>
                <div class="col-xs-10">
                    {{profile_form.picture|add_class:"form-control"}}
                </div>
            </div>
            <div class="form-group">
                <label class="col-xs-2" for="{{ user_form.website.id_for_label }}">Website: </label>
                <div class="col-xs-10">
                    {{profile_form.website|add_class:"form-control"}}
                </div>
            </div>
            <div class="form-group">
                <label class="col-xs-2" for="{{ user_form.address.id_for_label }}">Address: </label>
                <div class="col-xs-10">
                    {{profile_form.address|add_class:"form-control"}}</li>
                </div>
            </div>
            <input class="btn btn-default" type="submit" name="save_button" value="Save Profile">
        </form>
    {% endif %}

1 个答案:

答案 0 :(得分:0)

您的UserForm类扩展了Model.Form类,该类根据需要显示“密码”字段,因此出现了问题。改用UserChangeForm:

from django.contrib.auth.forms import UserChangeForm

class UserForm(UserChangeForm):
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'is_super_admin')

此表单将按原样处理密码。