型号:
class Subject(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True,null=True)
形式:
class SearchTypeForm(forms.Form):
subject = forms.ModelChoiceField(queryset = Subject.objects.all())
查看:
...
context['search_type_form'] = SearchTypeForm()
...
模板:
{{search_type_form.subject}}
在实际模板中,搜索类型表单呈现为:
<select id="id_subject" name="subject">
<option selected="selected" value="">---------</option>
<option value="1">subject 1</option>
<option value="2">subject 2</option>
...
</select>
在值字段(上面的下拉列表中)是相应主题的ID,如何将其更改为其他字段,就像我们想要使其成为主题模型的 slug字段
答案 0 :(得分:1)
这取决于模型的__unicode__
方法。让它返回slug
:
class Subject(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.slug
答案 1 :(得分:1)
您可以通过指定“to_field_name”关键字参数来覆盖它,如下所示:
from django import forms
from some.models import Something
class SomeForm(forms.Form):
something = forms.ModelChoiceField(queryset=Something.objects.all(),
to_field_name="slug")