4
我想爲Userena製作多個配置文件 - 每個用戶只能有一個配置文件類型。在進行其他討論之後,我使用了多個表格內容,但是當我這樣做時,我無法將數據保存到派生模型中。一切都以CommonProfile結尾,這不應該是可能的/允許的。示例代碼如下:django-userena中的多個用戶配置文件
在models.py
:
# models.py
# This is an example of how i've attempted to get
# multiple user profiles working with Userena
from django.contrib.auth.models import User
from django.db import models
from userena.models import UserenaLanguageBaseProfile
class CommonProfile(UserenaLanguageBaseProfile):
"""Common fields for 2 user profiles: Spam and Eggs"""
user = models.OneToOneField(User)
common_field = models.CharField(max_length=100)
@property
def is_spam(self):
"""Find out if this is a Spam user"""
try:
self.spamprofile
return True
except SpamProfile.DoesNotExist:
return False
def get_real_type(self):
"""return the real model"""
if self.is_spam:
return self.spamprofile
else:
return self.eggsprofile
class SpamProfile(CommonProfile):
spam_field = models.CharField(max_length=20)
class EggsField(CommonProfile):
eggs_field = models.SmallIntegerField()
在forms.py
# forms.py
# This is the form to sign up a Spam Type Person
from django import forms
from userena.forms import SignupFormTos
from . models import CommonProfile, SpamProfile
class SpamSignupForm(SignupFormTos):
"""signup a Spam Person"""
common_field = forms.CharField(label='what is your quest')
spam_field = forms.CharField(label='what kind of spam are you')
def clean(self):
cleaned_data = super(SpamSignupForm,self).clean()
#do stuf, same idea for clean_<field>
return cleaned_data
def save(self):
"""Save the SpamProfile"""
user = super(SpamSignupForm,self).save()
common_profile = user.get_profile()
spam_profile = SpamProfile(commonprofile_ptr=common_profile)
spam_profile.spam_field = self.cleaned_data['spam_field']
spam_profile.save()
return spam_profile
只是一個評論,SpamProfile,如CommonProfile和UserenaLanguageBaseProfile的直接繼承者,沒有一個objects.create_user,這意味着你需要添加的UserManager衍生經理的個人資料。或者我在你的解決方案中遺漏了一些隱含的東西? – yarbelk
是的,你需要一個經理。您可以看到userena如何在其managers.py文件中實現它 –