模型表单额外字段

时间:2011-03-01 12:28:45

标签: python django forms django-models

所以我通过模型为表单添加了一个额外的字段,&使用这些选择:

A_CHOICES = (
    ('none', 'none'),
    # further conversion table

class MyForm(ModelForm):

extra_field_a = ChoiceField(choices=A_CHOICES)

如果此字段不是'none',那么我想将其值用于模型中的字段,但我不确定如何检索它,我在MyForm内尝试了:

def cleaned_extra(self):
    if(self.cleaned_data.get('extra_field_a') != 'none'):
        return self.extra_field_a
    else:
        return self.original_field

但我得到一个NameError,'未定义全局名称'?任何帮助非常感谢,

亚当

1 个答案:

答案 0 :(得分:1)

这就是你如何检索它。除了时髦的语法,NameError在哪里? self未定义?你把这个代码放在哪里。

您通常会将此类字段特定代码放在clean_FOO方法中。 http://docs.djangoproject.com/en/dev/ref/forms/validation/#form-and-field-validation

def clean_extra_field_a(self):
    data = self.cleaned_data.get('extra_field_a')
    if data != 'none':
        return data
    return None # remember to set this field as required=False

def save(self, *args, **kwargs):
    # override save to do something with your extra field.
    self.instance.myfield = self.cleaned_data.get('extra_field_a')
    super(MyForm).save(*args, **kwargs)

更新:在视图中保存没问题。

mymodel = myform.save(commit=False) 
# ModelForm's will return the object being created/edited on save()
# commit=False will prevent a database save

mymodel.myfield = myform.cleaned_data.get('extra_field_a')
mymodel.save()

# note if you have an m2m, there is an extra method to call on commit=False