Amy*_*yth 2 python django modelform custom-fields
假设我的模型如下.
class Profile(models.Model):
user = models.OneToOneField(User)
middle_name = models.CharField(max_length=30, blank=True, null=True)
Run Code Online (Sandbox Code Playgroud)
我email在ModelForm中有一个自定义字段如下
class ProfileForm(ModelForm):
email = forms.CharField()
class Meta:
model = models.Profile
fields = ('email', 'middle_name')
Run Code Online (Sandbox Code Playgroud)
在am中设置上述模型的实例,以便在编辑模板的表单中预填充数据,如下所示.
def edit_profile(request):
profile = models.Profile.objects.get(user=request.user)
profileform = forms.ProfileForm(instance=profile)
return render_to_response('edit.html', { 'form' : 'profileform' }, context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
现在在表单中,我获得了为Profile模型下的所有字段预填充的所有值,但自定义字段为空,这是有意义的.
但有没有办法可以预先填充自定义字段的值?也许是这样的:
email = forms.CharField(value = models.Profile.user.email)
Run Code Online (Sandbox Code Playgroud)
我可以推荐别的吗?如果它与模型无关,我不是在模型中使用该email字段的忠实粉丝Profile.
相反,如何只有两个表单并将初始数据传递给您的自定义数据email?事情看起来像这样:
# this name may not fit your needs if you have more fields, but you get the idea
class UserEmailForm(forms.Form):
email = forms.CharField()
Run Code Online (Sandbox Code Playgroud)
profile = models.Profile.objects.get(user=request.user)
profileform = forms.ProfileForm(instance=profile)
user_emailform = forms.UserEmailForm(initial={'email': profile.user.email})
Run Code Online (Sandbox Code Playgroud)
然后,您将验证配置文件和用户电子邮件表单,但其他方面大致相同.
我假设你没有在Profile ModelForm和这个UserEmailForm之间共享逻辑.如果您需要配置文件实例数据,您可以随时传递它.
我更喜欢这种方法,因为它不那么神奇,如果你在一年内回顾你的代码,你就不会想知道为什么,在简短的扫描中,为什么它不是作为该模型上的字段存在的email一部分ModelForm.
| 归档时间: |
|
| 查看次数: |
1731 次 |
| 最近记录: |