简体   繁体   中英

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. I am able to add the Foreign Key by manually typing in the foreign key number (eg "1") and the form will work. 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

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

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;

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;

<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. After I switched over, I don't understand how I used the built in django forms for so long.

That being said, here is a jsfiddle demonstrating how to use the bootstrap dropdown as an input-item.

Dropdown Button 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()

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)

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

Final result for html part

<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

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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