我不需要用户部分只有配置文件。我目前得到的错误是
'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()
forms.py
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
})
答案 0 :(得分:2)
您需要按属性名称获取userprofile,而不是模型名称:
...
else:
profile_form = ProfileForm(instance=request.user.userprofile)
这可能会有所帮助,也可以在创建字段时设置related_name参数,因此属性名称将对应于该名称。
答案 1 :(得分:-1)
使用UserProfile类的primary_key然后它将起作用。不要在request.user
中直接使用UserProfile类profile_form = ProfileForm(instance=request.user.user_profile_primary_key)