【问题标题】:Django - extended User profile, object does not exist, how to create a blank record?Django - 扩展用户配置文件,对象不存在,如何创建空白记录?
【发布时间】:2016-12-08 13:44:45
【问题描述】:

我按照下面创建了一个用户配置文件类,如果用户点击我的帐户页面并且他们没有记录,我会收到以下错误:

RelatedObjectDoesNotExist at /profile
User has no userprofile.
Exception Type: RelatedObjectDoesNotExist
Exception Value:    
User has no userprofile.

这是错误行

profile_form = ProfileForm(instance=request.user.userprofile) 

所以我想我需要尝试一下那个部分?但我不确定如何创建记录作为例外?

谢谢

模型.py

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
# Create your models here.

class UserProfile(models.Model):
    mpls_m_subscriptions = models.CharField(max_length=50,verbose_name="MPLS Maintenance Subscription",choices=settings.SUBSCRIPTION_TYPE,blank=True,null=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)

views.py

@login_required
@transaction.atomic
def update_profile(request):
    if request.method == 'POST':
        profile_form = ProfileForm(request.POST, instance=request.user.userprofile)
        if profile_form.is_valid():
            profile_form.save()
            messages.success(request, ('Your profile was successfully updated!'))
            return redirect('home:profile')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        profile_form = ProfileForm(instance=request.user.userprofile)
    return render(request, 'home/profile.html', {
        'profile_form': profile_form
    })    

【问题讨论】:

    标签: python django


    【解决方案1】:

    我建议做以下两件事:

    1. 创建数据迁移,为所有现有用户创建空白用户配置文件Django Migrations Documentation
    2. 为用户创建一个 post_save 信号处理程序,以便在创建新用户时自动创建配置文件对象Django Signals

    【讨论】:

    【解决方案2】:

    您必须检查第一个用户是否存在

    @login_required
    @transaction.atomic
    def update_profile(request):
        if request.method == 'POST':
            if request.user.userprofile is None:
                user_profile = UserProfile(user=request.user)
                user_profile.save
            ...
    

    【讨论】:

    • 我在“if request.user.userprofile: # check user not none”处遇到了同样的错误:“用户没有用户配置文件。”
    • 用户确实存在,只是没有用户配置文件,用户配置文件是扩展模型
    • 如果用户存在,则为该用户创建用户配置文件
    • 我收到错误“用户没有用户配置文件”以检查 request.user.userprofile。这对我来说没有意义,因为那是支票......
    • userprofile = UserProfile(user=request.user) userprofile.save() ?像这样的东西。我不明白这种关系。
    猜你喜欢
    • 2010-12-26
    • 1970-01-01
    • 2012-04-30
    • 2012-07-22
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多