简体   繁体   English

无需输入密码即可在Django中编辑用户个人资料

[英]edit user profile in django without typing password

here I am trying to allow users to make modifications to their user profile. 在这里,我试图允许用户对其用户配置文件进行修改。 There's a model called UserProfile that holds a one to one relationship to django user itself. 有一个名为UserProfile的模型,它与django用户本身保持一对一的关系。 Below is the code in views.py 以下是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})

However, once the submit button is clicked from the template, I got an error saying that a password is needed. 但是,一旦从模板中单击了提交按钮,我就会收到一条错误消息,提示需要密码。

[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

from the code, I thought that the UserProfile is already bound to a specific user already, and I am only allowing users to make changes on the UserProfile model without touching django's auth User model. 从代码中,我认为UserProfile已经已经绑定到特定用户,并且我只允许用户在UserProfile模型上进行更改,而无需触摸django的auth User模型。 I wonder why the username and password is still needed in this case. 我想知道为什么在这种情况下仍然需要用户名和密码。 Would it be possible to allow editing on user profile without users' password? 是否可以在没有用户密码的情况下允许在用户个人资料上进行编辑?

Here is the UserProfile extended from the User model 这是从User模型扩展的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')

And the UserProfileForm on the template is here: 模板上的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 %}

Your UserForm class is extending Model.Form class which displays the Password field as required, hence the problem. 您的UserForm类扩展了Model.Form类,该类根据需要显示“密码”字段,因此出现了问题。 Use instead the UserChangeForm: 改用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')

This form handles password as it should. 此表单将按原样处理密码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM