WTForms和Django OneToOneFields

时间:2014-04-09 20:31:15

标签: python django wtforms

我有一个扩展auth User类的Django模型,但我找不到以单一形式从两个模型渲染数据的方法。

例如,让我们使用One2OneField扩展带有country字段的User类:

from django.contrib.auth.models import User
import pycountry
class Account(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    COUNTRY_CHOICES = [(country.alpha2, country.name) for country in pycountry.countries]
    country = models.CharField(max_length=2, choices=COUNTRY_CHOICES, default='US')

现在让我们创建一个包含两个模型元素的表单:

class AccountSettingsForm(Form):
    first_name = TextField(u'First name:', [validators.Length(min=2, max=35,message=u'First name should be between 2 and 35 characters.')])
    last_name = TextField(u'Last name:', [validators.Length(min=2, max=35,message=u'Last name should be between 2 and 35 characters.')])
    email = EmailField(u'E-mail address:', [validators.Email(message=u'Invalid e-mail address.')])
    COUNTRY_CHOICES = [(country.alpha2, country.name) for country in pycountry.countries]
    country = SelectField(u'Country', [valid_country,],choices=COUNTRY_CHOICES)

现在,在我的“帐户设置”页面上,我有这个:

@login_required
def update_settings(request):
    form = AccountSettingsForm(request.POST, obj=request.user)
    if request.method=='POST' and form.validate():
        #processing goes here
    context = {'form': form}
    return render(request, 'account/settings.html', context)

打开页面时,仅显示“用户”中的信息(如名字,姓氏,邮件地址等)。但是,不会从模型中检索“国家/地区”部分。

我需要做什么才能让两者同时显示?我没有看到如何将表单的“country”字段显式绑定到模型上的user.account.country字段。

2 个答案:

答案 0 :(得分:1)

你可以覆盖这样的__init__()方法来填充obj.account的数据(甚至是默认名称?我总是使用related_name选项)。

class AccountSettingsForm(Form):
    def __init__(self, formdata=None, obj=None, prefix='', data={}, meta=None, **kwargs):
        data['country'] = obj.account.country
        # etc
        super(AccountSettingsForm, self).__init__(formdata, obj, prefix, 
                                                  data, meta, **kwargs)

答案 1 :(得分:0)

似乎比我想象的要容易。

替换它:

form = AccountSettingsForm(request.POST, obj=request.user)

使用:

form = AccountSettingsForm(request.POST, obj=request.user, country=request.user.account.country)