Python Django-扩展用户配置文件,对象不存在,如何创建空白记录?
我已根据以下内容创建了一个用户配置文件类,如果用户单击“我的帐户”页面,但他们没有记录,我会得到以下错误:Python Django-扩展用户配置文件,对象不存在,如何创建空白记录?,python,django,Python,Django,我已根据以下内容创建了一个用户配置文件类,如果用户单击“我的帐户”页面,但他们没有记录,我会得到以下错误: RelatedObjectDoesNotExist at /profile User has no userprofile. Exception Type: RelatedObjectDoesNotExist Exception Value: User has no userprofile. 这是错误线 profile_form = ProfileForm(instance=re
RelatedObjectDoesNotExist at /profile
User has no userprofile.
Exception Type: RelatedObjectDoesNotExist
Exception Value:
User has no userprofile.
这是错误线
profile_form = ProfileForm(instance=request.user.userprofile)
所以我想我需要试一下那个部分?但我不知道如何创建一个记录作为例外
谢谢
Models.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
})
您必须检查第一个用户是否存在
@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”错误中得到了相同的错误:“user没有userprofile”。用户确实存在,他们只是没有userprofile,user profile是一个扩展模型如果user存在,那么为该用户创建一个userprofile。我得到了check if request.user.userprofile的错误“user没有userprofile”。这对我来说没有意义,因为这是检查…
userprofile=userprofile(user=request.user)userprofile.save()
?像这样的。我不明白你们之间的关系。谢谢!此解决方案的代码:(post_save
+数据迁移)