2014-09-19 82 views
0

的型号:如何呈现有条件

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(), 
    } 

该解决方案改变了选择进入的TextInput,这是非常好的一步。但是现在我看到父亲/母亲的身份不是姓名(在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 

(我希望你能看到[凯特晚]和凯特晚之间的差异(不[ ])

+0

澄清:您希望实例中已存在的字段不再可编辑? – 2014-09-20 07:39:12

+0

不完全。这很容易做到self.fields ['name']。widget.attrs ['readonly'] = True或self.fields ['name']。widget.attrs ['disable'] = True。我需要将ChoiceField转换为TextField,但是TextField包含的id不是选项的值 – 2014-09-20 08:38:27

+0

您的意思是'Option'的值是什么?我不确定我是否可以理解这个问题,但是如果您在模型上实现了__str__(或__unicode__)方法,这将非常有用。之后看看TextField中出现的内容。正如我所说,我不确定你以后的真实情况,这只是一个猜测。 – cezar 2014-09-20 08:51:45

回答

0

下一步天堂:

我从表单中删除的父亲和母亲,覆盖初始化并添加两个附加字段: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") 

(同为父亲)

但是,我的父亲和母亲还加回来上课元,原因无它,设置self.cleaned_data [“母亲”]什么都不做。

class Meta: 
    model = Person 
    fields = ('UNIQUE', 'name','email','father','mother') 
    widgets = { 
     'father': forms.HiddenInput(), 
     'mother': forms.HiddenInput(), 
    } 

它工作的很好,但会完美地删除hiddeninputs - 显示html源代码中的father_id不好。但现在,我不知道如何将数据发送到没有隐藏输入的模型