【问题标题】:edit user profile in django without typing password在 django 中编辑用户配置文件而不输入密码
【发布时间】:2015-07-06 03:40:05
【问题描述】:

这里我试图允许用户修改他们的用户配置文件。有一个名为 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 已经绑定到特定用户,我只允许用户在 UserProfile 模型上进行更改,而无需触及 django 的 auth User 模型。我想知道为什么在这种情况下仍然需要用户名和密码。是否可以允许在没有用户密码的情况下编辑用户配置文件?

这是从 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')

模板上的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 %}

【问题讨论】:

  • 请发布您的UserProfileForm
  • 可以发一下Python类UserProfileForm吗?我只看到UserForm
  • 嗨 Aebersold,我刚刚在此处添加了 UserProfileForm。
  • 您确定您的视图服务于正确的形式吗?并且您的 URL 正在访问正确的视图?你能展示你的观点和你的 urls.py 吗?
  • 同一页面上是否有主用户模型的表单?可能是你同时发送。无论如何,您在发布的某些 html 中使用了错误的模板标签。例如,&lt;label class="col-xs-2" for="{{ user_form.picture.id_for_label }}"&gt; 应该是 &lt;label class="col-xs-2" for="{{ profile_form.picture.id_for_label }}"&gt;

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


【解决方案1】:

您的 UserForm 类正在扩展 Model.Form 类,该类根据需要显示 Password 字段,因此存在问题。改用 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')

此表单按应有的方式处理密码。

【讨论】:

  • 我的表单扩展了 UserChangeForm 但我仍然有这个问题。我做错了什么?
猜你喜欢
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 2018-02-20
相关资源
最近更新 更多