1

I am attempting to create a dropdown field which populates with values from a model (Customers) and display it to the user.

Below is what I am attempting - not exactly sure why, but the dropdown field is not populating with any of the info from the Customer Model, it is just empty.

Views.py

def add_order(request):
    if request.method == "POST":
        form = CreateOrderForm(request.POST)
        objectlist = Customers.objects.all()


        if form.is_valid():
            form.save()
            return redirect('add_manifest')#, kwargs={'reference_id': form.cleaned_data['reference']})
    #else:
    form = CreateOrderForm()
    objectlist = Customers.objects.all()
    context = {
        'form': form,
        'objectlist': objectlist,
    }

    return render(request, 'add_order.html', context)

Template (add_order.html)

<div class="container">
    <form method="POST">
      <br>
      <h2>Order Information</h2>
      <br>
 <div class="column_order">
 <select>
          {% for element in objectlist %}
            <option value="{{ element.c_name }}">
          {% endfor %}
        </select>
 </div>
</div>

Models.py

class Customers(models.Model):

    c_name = models.CharField(max_length=100)
    c_address = models.CharField(max_length=1000)
    c_country = models.CharField(max_length=50)

def _str_(self):
    return self.c_name

When I go to this url and render the template, the select box displays, but there are no values in it. Any thoughts?

1 Answer 1

1

You did not close the <option> tag and there is no option text. Try:

<option value="{{ element.c_name }}">{{ element.c_name }}</option>

It is also a good idea to set the value to {{ element.pk }} instead as there might be multiple customers with the same name since you don't enforce that column to be unique.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.