使用模型生成django形式的选择字段

时间:2018-03-17 05:58:37

标签: django

我正在编写Django应用程序并手动构建表单。

<form method="post">
{% csrf_token %}

<input name="name" class="form-control">

<textarea name="description">

<select name="teaching_language">
    <option value="">Value 1</option>
</select>
</form>

我的models.py包含

class TeachingLanguage(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    modified = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

    class META:
        verbose_name_plural = 'teaching_languages'
        db_table = 'languages'

    def __str__(self):
        return self.title

class Course(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=250)
    teaching_language = models.ForeignKey(TeachingLanguage, on_delete=models.CASCADE)
    description = models.TextField(blank=True)

我必须在<option>

列表中填写TeachingLanguage

view.py文件包含

class NewCourse(CreateView):
    model = Course
    fields = ['name', 'teaching_language', 'description']

    def get_context_data(self, **kwargs):
        context = super(NewCourse, self).get_context_data(**kwargs)
        teaching_languages = TeachingLanguage.objects.all()
        context['teaching_languages'] = teaching_languages
        return context

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        form.save()

        return super().form_valid(form)

如何在teaching_languages字段中呈现select以生成下拉列表?

2 个答案:

答案 0 :(得分:1)

在模板中尝试此操作:

<form method="post">
{% csrf_token %}

<input name="name" class="form-control">

<textarea name="description">

{{ form.teaching_languages }}
</form>

这将只生成表单中的teaching_languages字段。 Click here了解更多详情。

此外,您现在应该删除get_context_data方法,因为form变量会自动传递给模板,并且表格会自动选取所有教学语言,因为它们在课程中设置为外键模型。

答案 1 :(得分:0)

如果您必须手动执行而不是让Django处理它,那么您可以简单地迭代您传递给上下文的教学语言:

<select name="teaching_language">
    {% for lang in teaching_languages %}
    <option value="{{ lang.pk }}">{{ lang }}</option>
    {% endfor %}
</select>