【发布时间】: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
})
【问题讨论】: