我有一些问题需要通过编辑 django-userena 的配置文件来解决。我想使用 EditProfileFormExtra(它是 userena EditProfileForm 的扩展)来编辑 Settings 模型的相关额外字段(选择字段),这些字段与 Accounts 应用程序存在 OneToOne 关系,字段:default_house_system。
保存是可以的,但是 default_house_system 的初始值不起作用,总是显示元组的第一个值。我想这样做而不在 Django-Userena 的原始文件中包含任何代码。
楷模:
class UserProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name='user',
related_name='user_profile')
settings = models.OneToOneField(Settings, unique=True, verbose_name="Ustawienia", blank=True, null=True)
is_virtual = models.BooleanField(default=False)
class Settings(models.Model):
points = models.IntegerField(default=0)
default_house_system = models.CharField(choices=HOUSE_SYSTEMS, max_length=24, default="Placidus")
用户表格:
class EditProfileForm(forms.ModelForm):
""" Base form used for fields that are always required """
first_name = forms.CharField(label=_(u'First name'),
max_length=30,
required=False)
last_name = forms.CharField(label=_(u'Last name'),
max_length=30,
required=False)
def __init__(self, *args, **kw):
super(EditProfileForm, self).__init__(*args, **kw)
# Put the first and last name at the top
new_order = self.fields.keyOrder[:-2]
new_order.insert(0, 'first_name')
new_order.insert(1, 'last_name')
self.fields.keyOrder = new_order
class Meta:
model = get_profile_model()
exclude = ['user']
def save(self, force_insert=False, force_update=False, commit=True):
profile = super(EditProfileForm, self).save(commit=commit)
# Save first and last name
user = profile.user
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
我替换了一个 urls 定义,放入 accounts/urls.py:
url(r'^(?P<username>[\.\w]+)/edit/$',
'userena.views.profile_edit',
{'edit_profile_form': EditProfileFormExtra},
name='userena_profile_edit'),
...这是 EditProfileFormExtra 的定义:
class EditProfileFormExtra(EditProfileForm):
default_house_system = forms.ChoiceField(choices=HOUSE_SYSTEMS)
def __init__(self, *args, **kw):
super(EditProfileFormExtra, self).__init__(*args, **kw)
new_order = self.fields.keyOrder[:-1]
new_order.insert(3, 'default_house_system')
self.fields.keyOrder = new_order
class Meta:
model = get_profile_model()
fields = ['mugshot', 'default_house_system']
def save(self, force_insert=False, force_update=False, commit=True):
profile = super(EditProfileFormExtra, self).save(commit=commit)
settings_profile = profile.settings
settings_profile.default_house_system = self.cleaned_data['default_house_system']
settings_profile.save()
profile.save()
return profile
现在重要的东西。如果我放:
'default_house_system':user.user_profile.settings.default_house_system
进入 userena/views.py/profile_edit 方法中的 dict (它是基于类的视图):
user_initial = {'first_name': user.first_name,
'last_name': user.last_name,
'default_house_system': user.user_profile.settings.default_house_system}
它工作正常!但我不想在 Django-Userena 的原始文件中包含任何代码。
除了将整个 profile_edit 方法从 userena/views.py 复制到我的应用程序帐户/views.py 之外,还有其他方法吗?
我将不胜感激任何提示或建议,谢谢。