该模型:
class Human(models.Model):
UNIQUE = models.CharField(max_length=10)
name = models.CharField(max_length=30)
father = models.ForeignKey('Human', related_name = "fathers_children", null=True, blank=True)
mother = models.ForeignKey('Human', related_name = "mothers_children", null=True, blank=True)
def __unicode__(self):
return "%s" % name
class Person(Human):
email = models.EmailField()
现在,我正在尝试制作ModelForm:
class PersonForm(ModelForm):
class Meta:
model = Person
fields = ('UNIQUE','name','email')
直到此为止-完美的作品。
现在我想添加两个字段:父亲和母亲
如果“人”已经有父亲(和/或母亲),请显示姓名。如果不是,则显示输入字段(或两个字段),用户必须在其中输入UNIQUE。
更新
class PersonForm(ModelForm):
class Meta:
model = Person
fields = ('UNIQUE','name','email')
widgets = {
'father' :forms.TextInput(),
'mother' :forms.TextInput(),
}
此解决方案将Select更改为TextInput,这是一个很好的步骤。但是现在我看到父亲/母亲的ID而不是名字(在Select中可以看到)。
=====================预期=========================== ========一小段图形:
情况1:人没有父母
UNIQUE: [AAA]
name: [John Smith ]
email: [[email protected]]
father: [ ]
mother: [ ]
情况2:某人有父亲
UNIQUE: [BBB]
name: [Kate Late ]
email: [ ]
father: Mike Tyson
mother: [ ]
情况3:人有父母双亲
UNIQUE: [CCC ]
name: [Jude Amazing ]
email: [[email protected] ]
father: James Bond
mother: Alice Spring
情况4:“用户[AAA]”(情况1)用户类型为“母亲”:[BBB]
UNIQUE: [AAA ]
name: [John Smith ]
email: [[email protected]]
father: [ ]
mother: Kate Late
(我希望您能看到[Kate Late]和Kate Late(没有[])之间的区别
通往天堂的下一步:
我从表单中删除了父亲和母亲,覆盖了init并添加了两个附加字段:father_input和mother_input
class PersonForm(ModelForm):
def __init__(self, *args, **kwargs):
super(PersonForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance and instance.pk:
if instance.father is not None:
self.fields['father_input'].initial = self.instance.father
self.fields['father_input'].widget.attrs['disabled'] = True
if instance.mother is not None:
self.fields['mother_input'].initial = self.instance.mother
self.fields['mother_input'].widget.attrs['disabled'] = True
father_input = forms.CharField(required = False)
mother_input = forms.CharField(required = False)
class Meta:
model = Person
fields = ('UNIQUE','name','email')
因此,现在解决了1/2题-当定义了父/母时-它在不可编辑的字段中显示了父亲的名字。
现在是时候为输入的UNIQUE服务:
父亲/母亲输入字段可以包含任何文本-服务器现在不提供该文本。所以我必须添加
def clean_mother_input():
data = self.cleaned_data['mother_input']
if data == '':
return data # do nothing
try:
mother = Person.objects.get(UNIQUE=data)
logger.debug("found!")
self.cleaned_data['mother'] = mother
return data
except ObjectDoesNotExist:
raise forms.ValidationError("UNIQUE not found")
(父亲也一样)
但是我也将父级和母级添加回Class meta,因为如果没有它,设置self.cleaned_data ['mother']不会执行任何操作。
class Meta:
model = Person
fields = ('UNIQUE', 'name','email','father','mother')
widgets = {
'father': forms.HiddenInput(),
'mother': forms.HiddenInput(),
}
它运作良好,但删除隐藏输入将是完美的-在html来源中显示father_id不好。但是到目前为止,我还不知道如何在没有隐藏输入的情况下将数据发送到模型
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句