我按照下面创建了一个用户配置文件类,如果用户单击我的帐户页面并且他们没有记录,我会收到以下错误:
RelatedObjectDoesNotExist at /profile
User has no userprofile.
Exception Type: RelatedObjectDoesNotExist
Exception Value:
User has no userprofile.
这是错误行
profile_form = ProfileForm(instance=request.user.userprofile)
所以我想我需要尝试一下那个部分?但我不确定如何创建一条记录作为异常(exception)?
谢谢
模型.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)
View .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
})
请您参考如下方法:
我建议做以下两件事:
- 创建数据迁移,为所有现有用户创建空白用户配置文件 Django Migrations Documentation
- 为用户创建一个 post_save 信号处理程序,以便在创建新用户时自动创建配置文件对象 Django Signals
