我试图为 Userena 制作多个配置文件 - 每个用户只能使用一个配置文件类型 。 根据其他讨论, 我使用多张表格, 但这样做时, 我无法将数据保存到衍生模型中 。 所有结果都是通用的 profile, 这不应该是不可能/ 不允许的 。 示例代码如下 :
在 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