【问题标题】:Django - Updating UserProfile Always Returning Not_Valid()Django - 更新用户配置文件总是返回 Not_Valid()
【发布时间】:2013-11-10 22:51:53
【问题描述】:

我目前正在做一个 Django 项目。这是我对 Python / Django 的第一次介绍,所以我目前正在学习。希望大家帮忙!

我目前正在尝试通过模型、视图和模板更新我在 UserProfile 模型中设置的一些自定义字段。现在看来,无论我对视图做什么,返回的表单总是返回无效。我已经盯着这个看了很长一段时间,所以这可能没有帮助。代码如下:

models.py

 class UserProfile(models.Model):
    #inherit the base User model
    user = models.OneToOneField(User)

    #custom fields to be in the User model
    phoneNumber = models.IntegerField(null=True)
    about = models.TextField(null=True)
    gitHubLink = models.URLField(null=True)
    linkedInLink = models.URLField(null=True)
    gravitarLink = models.URLField(null=True)
    facebookLink = models.URLField(null=True)
    rating = models.PositiveSmallIntegerField(default=0)

    def __unicode__(self):
        return u'Profile of user: %s' % self.user.username

User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

views.py

@login_required
def edit_profile(request):
    profile = request.user.get_profile()

    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            userprofile = form.save(commit=False)
            userprofile.user = request.user
            userprofile.save()
            messages.success(request, "Account Updated!")
            return render_to_response('profile/edit.html', {"form": form}, context_instance=RequestContext(request))
        else:
            form = UserProfileForm()
            messages.error(request, "There are form errors.")
            return render_to_response('profile/edit.html', {"form": form}, context_instance=RequestContext(request))
    else:
        form = UserProfileForm(instance=profile)
        return render_to_response('profile/edit.html', {"form": form}, context_instance=RequestContext(request))

forms.py

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('phoneNumber', 'about', 'gitHubLink', 'linkedInLink', 'gravitarLink', 'facebookLink')

    def save(self, commit=True):
        userprofile = super(UserProfileForm, self).save(commit=False)
        userprofile.phoneNumber = self.cleaned_data['phoneNumber']

        if commit:
            userprofile.save()
        return userprofile

edit.html(模板)

<form action="/profile/edit/" method="post" class="form-signin">
    {% csrf_token %}
    <div class="form-group">{{ form.phoneNumber|add_class:"form-control"|attr:"placeholder:Phone Number" }} </div>
    <div class="form-group">{{ form.gitHubLink|add_class:"form-control"|attr:"placeholder:GitHub Account URL" }} </div>
    <div class="form-group">{{ form.facebookLink|add_class:"form-control"|attr:"placeholder:Facebook Account URL" }} </div>
    <div class="form-group">{{ form.linkedInLink|add_class:"form-control"|attr:"placeholder:LinkedIn Account URL" }} </div>
    <div class="form-group">{{ form.about|add_class:"form-control"|attr:"placeholder:About Yourself. Interests, Hobbies, etc.." }} </div>
    <button class="btn btn-lg btn-success btn-block" type="submit">Save Changes</button>
</form>

感谢您花时间阅读本文。非常感谢任何帮助/指针!

【问题讨论】:

    标签: django django-models django-forms django-views django-users


    【解决方案1】:

    您的模板不包含您的 gravitarLink 字段。因为模型字段没有用blank=True 声明,所以这个字段是必需的,所以你的表单永远不会有效。

    请注意,通常认为最好不要将null=True 与字符字段一起使用,其中URLField 是其中的一个子集。相反,如果您希望它们是可选的,请设置blank=True 并将null 保留为其默认值False,以便空字符串为空值。 blank=True 是可选的; null 只是控制哪些数据库表示是有效的。

    此外,最好在出现错误时将绑定的form 对象传回模板,而不是创建一个新的空对象。这不仅包括您之前提交的值,因此用户不必重新输入有效值,而且它可以显示每个字段的错误。关于“在视图中使用表单”的 Django 文档演示了通常的模式。

    【讨论】:

    • 就是这样!非常感谢你。我必须将字段上的依赖项删除到blank=True 而不是null=True。正如你所说,我会考虑传递一个绑定的 form 对象。
    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2016-11-20
    • 2019-11-16
    • 2013-03-15
    • 1970-01-01
    相关资源
    最近更新 更多