简体   繁体   English

在Bootstrap表单中使用外键的Django下拉列表

[英]Django Dropdown with Foreign key in Bootstrap Form

I am developing my first Django Website and i want to use a Foreign Key drop down in a Bootstrap Form. 我正在开发我的第一个Django网站,我想在Bootstrap表单中使用外键下拉。 I am able to add the Foreign Key by manually typing in the foreign key number (eg "1") and the form will work. 我可以通过手动输入外键号(例如“1”)来添加外键,表单将起作用。 But i am not able to insert the right syntax for a linked drop down. 但我无法为链接下拉列表插入正确的语法。 Find below my current models.py / views.py and html 在下面找到我当前的models.py / views.py和html

I have the following Customer model; 我有以下客户模型;

class Customer(models.Model):
    customer_type = models.ForeignKey(CustomerType)
    customer_name = models.CharField(max_length=120, null=True, blank=True)

    def __unicode__(self):
        return smart_unicode(self.customer_name)

With the CustomerType 使用CustomerType

class CustomerType(models.Model):
    customer_type = models.CharField(max_length=120, null=True, blank=True)

    def __unicode__(self):
        return smart_unicode(self.customer_type)

See my views.py below; 请参阅下面的views.py;

def customeradd(request):      
    form = CustomerAddForm(request.POST or None)

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        messages.success(request, 'Customer added succesfully')
        return HttpResponseRedirect('/customeroverview/')

    return render_to_response("customer-add.html",
                              locals(),
                              context_instance=RequestContext(request))

and finally my html; 最后是我的HTML;

<div class="col-lg-12">
          <form class="form-horizontal" method="POST" action=''> {% csrf_token %}

            <div class="form-group">
              <label for="customer_name" class="col-sm-2 control-label">Customer Name</label>
              <div class="col-sm-10">
                <input id="customer_name"  name="customer_name" type="text" class="form-control" >
              </div>
            </div>

        <div class="form-group">
              <label for="customer_type" class="col-sm-2 control-label">Customer Type</label>
              <div class="col-sm-10">
        <select class="form-control" id="customer_type" name="customer_type"></select>
          </div>
            </div>

            <div class="form-group">
            <div class="col-sm-10"></div>
              <div class="col-sm-2">
                <button type='submit' class="btn btn-success btn-block">Add Customer</button>
              </div>
            </div>

          </form>
</div>

Any help is much appreciated. 任何帮助深表感谢。

First of all, I would just like to suggest using django-crispy-forms , you will not regret it and it pairs VERY nicely with bootstrap. 首先,我想建议使用django-crispy-forms ,你不会后悔,它与bootstrap配对非常好。 After I switched over, I don't understand how I used the built in django forms for so long. 我换了之后,我不明白我如何使用内置的django表格这么久。

That being said, here is a jsfiddle demonstrating how to use the bootstrap dropdown as an input-item. 话虽这么说,这里有一个jsfiddle演示如何使用bootstrap下拉列表作为输入项。

Dropdown Button w/.form-control 下拉按钮w / .form-control
 <div class="panel panel-default"> <div class="panel-body"> <div class="btn-group"> <button type="button" class="btn btn-default dropdown-toggle form-control" data-toggle="dropdown"> <span data-bind="label">Select One</span>&nbsp;<span class="caret"></span> </button> <ul class="dropdown-menu" role="menu"> {% for t in types %} <li><a href="#">{{ type }}</a></li> {% enfor %} </ul> </div> </div> </div> 

And then in your views make sure you pass in types = CustomerType.objects.all() 然后在您的视图中确保传入types = CustomerType.objects.all()

To add customer types in your drop down first you have to collect all customer types from table: 要在您的下拉列表中添加客户类型,您必须从表中收集所有客户类型:

def customeradd(request):      
    form = CustomerAddForm(request.POST or None)
    customer_types = CustomerType.objects.all()

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        messages.success(request, 'Customer added succesfully')
        return HttpResponseRedirect('/customeroverview/')

    return render_to_response("customer-add.html",
                              {'customer_types': customer_types},
                              context_instance=RequestContext(request))

(don't forget to include CustomerType from your models) (不要忘记在模型中包含CustomerType)

and then you have to include them to your element 然后你必须将它们包含在你的元素中

<div class="col-lg-12">
          <form class="form-horizontal" method="POST" action=''> {% csrf_token %}

            <div class="form-group">
              <label for="customer_name" class="col-sm-2 control-label">Customer Name</label>
              <div class="col-sm-10">
                <input id="customer_name"  name="customer_name" type="text" class="form-control" >
              </div>
            </div>

        <div class="form-group">
              <label for="customer_type" class="col-sm-2 control-label">Customer Type</label>
              <div class="col-sm-10">
        <select class="form-control" id="customer_type" name="customer_type"> {%for type in customer_types%}<option value="{{type}}">{{type}}</option>{%endfor%}</select>
          </div>
            </div>

            <div class="form-group">
            <div class="col-sm-10"></div>
              <div class="col-sm-2">
                <button type='submit' class="btn btn-success btn-block">Add Customer</button>
              </div>
            </div>

          </form>
</div>

I changed 我变了

<option value="{{type}}">{{type}}</option>

to

<option value="{{type.id}}">{{type}}</option>

Now it saves the Key but shows the ValueText 现在它保存了Key但显示了ValueText

Final result for html part html部分的最终结果

<div class="form-group">
    <label for="customer_type" class="col-sm-2 control-label">Customer Type</label>
     <div class="col-sm-10">
       <select class="form-control" id="customer_type" name="customer_type">
          {%for type in customer_types%}<option value="{{type.id}}">{{type}}</option>{%endfor%}
        </select>
     </div>
</div>

Final result for views.py views.py的最终结果

def customeradd(request):      
    form = CustomerAddForm(request.POST or None)
    customer_types = CustomerType.objects.all()

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        messages.success(request, 'Customer added succesfully')
        return HttpResponseRedirect('/customeroverview/')

    return render_to_response("customer-add.html",
                              {'customer_types': customer_types},
                              context_instance=RequestContext(request))

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

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