2017-01-23 76 views
1

我想要做的是當用戶想要編輯時,他/她應該能夠以文本字段格式查看PlotID而不是下拉格式,因爲目前Plot_ID字段顯示爲下拉菜單不是文本框。將模型表單下拉字段轉換爲文本字段

我想要做的是,當用戶想要編輯時,他/她應該能夠看到文本字段格式的PlotID而不是下拉格式,因爲現在Plot_ID字段顯示爲下拉而不是文本字段。

我model.py:

class Farm(models.Model): 
    farmID = models.CharField('farmID',primary_key=True, max_length=20) 
    fieldsize = models.FloatField('Field Size (hactre)') 

class Plot(models.Model): 
    farm = models.ForeignKey(Farm,verbose_name='FarmID') 
    plotID = models.CharField('PlotID',max_length=50) 

class PlotManagement(models.Model): 
    farm = models.ForeignKey(Farm,verbose_name='FieldID') 
    plotID = models.ForeignKey(Plot,verbose_name='PlotID') 

我form.py

class PlotManagementForm(forms.ModelForm): 

    class Meta: 
     model=PlotManagement 
     exclude=('enteredpersonel',) 
    def __init__(self, *args, **kwargs): 
     super(PlotManagementForm, self).__init__(*args, **kwargs) 
     self.fields['farm'].widget.attrs['class'] = 'form-control' 
     self.fields['plotID'].widget.attrs['class'] = 'form-control' 

我template.html: {{plotmanagementform.farm.errors}} 農民: {{ plotmanagementform.farm}}

<div class="form-group"> 
{{ plotmanagementform.plotID.errors }} 
<label for="plotID" class="col-md-4 control-label">Plot ID:</label> 
<div class="col-md-4 selectContainer"> 
{{ plotmanagementform.plotID }} 
</div> 
</div> 
+0

你爲什麼要這樣做?它會很難讓你的用戶真正知道某個特定情節實例的id是什麼 – Sayse

+1

也許你正在尋找select2而不知道它?以防萬一,以防萬一。 https://select2.github.io/examples.html – makaveli

+0

我想要做的是與select2相比完全不同;我想要的是有一個用戶可以輸入他們的字段沒有下拉的文本字段 –

回答

0

您可以將PlotId場的控件更換一個TextInput這樣的:

self.fields['plotID'].widget = TextInput()

你將不得不從django.forms.widgets進口TextInput。或者在這裏可能更適合NumberInput()

但正如評論中所述,這樣做並不是一個好主意。將主鍵或外鍵ID編輯是不好的,因爲如果你犯了一個錯誤,你的數據庫和關係可能很容易失去同步。