简体   繁体   English

Django:如何从CreateView创建下拉列表

[英]Django: How to create a dropdown from CreateView

I have a form that you enter in new clients. 我有一张您要输入新客户的表格。 Within the client form you should be able to select the branch they are apart of. 在客户表单中,您应该能够选择它们分开的分支。 I have tried to add a select field within the template that lists all the branches as options but it returns nothing. 我试图在模板中添加一个选择字段,该字段将所有分支列为选项,但它什么也不返回。 What is the correct way of doing this. 正确的做法是什么?

models.py models.py

class Client(models.Model):
    branch = models.ForeignKey(Branch)

view.py view.py

class ClientCreate(CreateView):
   model = Client
   fields = [..., 'branch']

form.html form.html

<form role="form" method="post" action="."> {% csrf_token %}
  <div class="form-group">
    <label>Type</label>
    <div class="input-group">
      <select id="id_type" name="type">
        <option value selected="selected">Select</option>
        {% for i in client_create %}
        <option value="{{i.branch}}">{{i.branch}}</option>
        {% endfor %}
      </select>
    </div>
  </div>

First thing it's model not models: 首先是模型而不是模型:

class ClientCreate(CreateView):
    model = Client
    fields = [..., 'branch']

Second thing, try to use the generated ModelForm : 第二件事,尝试使用生成的ModelForm

<form role="form" method="post" action="."> 
    {% csrf_token %}
    ...
    {{ form.branch }}
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM