2017-03-14 51 views
0

我有一個模型,其中場從另一個模型作爲參考外鍵:渲染洋場在Django形式

class DummyModel(models.Model): 
    name = models.CharField(max_length=100) 
    description = models.CharField(max_length=150)   
    image_type = models.ForeignKey(ImageTypeModel) # Foreign key 

    class Meta: 
     db_table = "dummy" 

父模型也很簡單:

class ImageTypeModel(models.Model): 
    name = models.CharField(max_length=100) 
    dims = models.IntegerField() 

    class Meta: 
     db_table = "imagetypes" 

現在,我嘗試爲了在此表格中創建記錄併爲此目的我正在使用django-crispy-forms。所以,我有:

class DummyForm(ModelForm): 
    class Meta: 
     model = DummyModel 
     fields = ['name', 'description', 'image_type'] 

    def __init__(self, *args, **kwargs): 
     super(DummyForm, self).__init__(*args, **kwargs) 
     self.helper = FormHelper(self) 
     self.helper.form_class = 'form-horizontal' 
     self.helper.label_class = 'col-sm-2' 
     self.helper.field_class = 'col-sm-10' 
     #self.helper.form_tag = False 
     self.helper.layout = Layout(
      Field('name'), 
      Field('description'), 
      Field('image_type')) 

image_type場呈現爲這是完美的一個下拉列表,但而不是圖像類型的名稱,條目都被標記ImageTypeModel。有沒有一種機制,使我可以顯示相應的名稱從ImageTypeModel記錄,但當表單被保存時,它保存主鍵而不是名稱。

+1

你有沒有實現的'ImageTypeModel'模型裏面的'__unicode__'方法(對於Python 2)或'__str__'(蟒蛇3)? –

+0

hmmmmmm ...不。好吧,我不知道我必須這樣做! – Luca

+0

這個伎倆!你想寫它作爲答案,以便我可以接受它> – Luca

回答

2

您應該在模型中實現__unicode__(python 2)或__str__(python 3)方法。

像這樣:

class ImageTypeModel(models.Model): 
    name = models.CharField(max_length=100) 
    dims = models.IntegerField() 

    class Meta: 
     db_table = "imagetypes" 

    # For Python 2 
    def __unicode__(self): 
     return self.name 

    # For Python 3 
    def __str__(self): 
     return self.name