在CBV的post方法中,我坚持使用userprofileform进行初始化,并且实例从对super()的调用中收到None对象... 该模型非常标准:用户及其个人资料; uerprofile模型具有用户属性( onetoone )
models.py
[...]
class User(AbstractUser):
"""User model."""
username = None
email = models.EmailField(_('email address'), unique=True)
first_name = models.CharField(_('first name'), unique=False, max_length=100)
last_name = models.CharField(_('last name'), unique=False, max_length=100)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=15,null=True)
website = models.URLField(blank=True, null=True) upload_to=PathAndRename("avatars/"))
photo = models.ForeignKey(Photo, null=True, on_delete=models.PROTECT)
organization = models.CharField(_('organization'), null=True,unique=False, max_length=100)
city = models.CharField(_('city'), unique=False, max_length=100, null=True)
country = CountryField(blank_label=_('select country'), null=True)
subscribe_newsletter = models.BooleanField(default=False)
language = models.CharField(max_length=10,
choices=settings.LANGUAGES,
default=settings.LANGUAGE_CODE)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
def save(self, *args,**kwargs):
#import ipdb; ipdb.set_trace()
self.city=(self.city or '').lower()
self.organization=(self.organization or '').lower()
self.website=(self.website or '').lower()
super(UserProfile, self).save(*args,**kwargs)
self.user.save()
[...]
forms.py
[...]
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('first_name', 'last_name', 'phone', 'website','city','country','organization','subscribe_newsletter')
def __init__(self, *args, **kwargs):
user = kwargs.pop('user',None)
super(UserProfileForm, self).__init__(*args, **kwargs)
try:
self.instance.user=user
except:
pass
try:
self.fields['first_name'].initial = self.instance.user.first_name
self.fields['last_name'].initial = self.instance.user.last_name
except User.DoesNotExist:
pass
[...]
views.py
class ProfileView(LoginRequiredMixin, View):
def __init__(self,*args,**kwargs):
self.context={}
super().__init__()
def get(self,request):
profile_form = UserProfileForm(instance=request.user.profile, prefix='profile')
self.context['profile_form']=profile_form
return render(request,'account/profile.html', self.context)
def post(self,request):
#import ipdb; ipdb.set_trace()
if request.POST.get('action',)=='profile':
profile_form = UserProfileForm(request.POST, user=request.user, prefix='profile')
if profile_form.is_valid():
profile_form.save()
info={'title':_('PROFILE SAVED !'),'desc':_('your profile has been successfully updated')}
self.context['infos']=[info]
return render(request,'info.html', self.context)
else:
self.context['errors']=get_form_errors_list(profile_form.errors)
elif request.POST.get('action',)=='avatar':
pass
self.context['profile_form']=profile_form
return render(request,'account/profile.html', self.context)
[...]
当我影响UserProfileForm到profile_form时,视图的post方法中会发生错误。调试工具栏返回“ UserProfile没有用户” 。
UserProfileForm的 init 方法与视图的get方法一起使用(实例通过user.profile设置),但在发布时未给出实例(将user.profile作为数据丢弃是无意义的)包含在resquest.POST中)。