2014-09-19 98 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不好。但現在,我不知道如何將數據發送到沒有隱藏輸入的模型