![](/img/trans.png)
[英]Django extending user with userprofile (error: User has no profile.)
[英]Django - extend user profile error user has no attribute userprofile
我不需要用戶部分僅配置文件。 我當前得到的錯誤是
'User' object has no attribute 'UserProfile'
line 45: profile_form = ProfileForm(instance=request.user.UserProfile)
我了解的是因為用戶模型沒有UserProfile。 我不確定如何將UserProfile放入請求中,以便表單可以工作?
模型
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)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.UserProfile.save()
表格
from django import forms
from home.models import UserProfile
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('mpls_m_subscriptions',)
views.py
from django.shortcuts import get_object_or_404, render, render_to_response
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.http import HttpResponse
from home.forms import ProfileForm
@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('settings: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
})
您需要通過屬性名稱而不是模型名稱來獲取用戶配置文件:
...
else:
profile_form = ProfileForm(instance=request.user.userprofile)
這可能會有所幫助,在創建字段時,您還可以設置related_name參數,因此屬性名稱將與該名稱相對應。
使用UserProfile類的primary_key它將起作用。 不要在request.user中直接使用UserProfile類
profile_form = ProfileForm(instance=request.user.user_profile_primary_key)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.