简体   繁体   中英

Drop down menu from Django database

I'd like to create a drop down list in an HTML template that draws data from a Django database. Is there anyway I can code it in the <option value...> ?

The examples below work perfectly fine with the databases you create on your own. The problem is, that I need to make use of the username field from django.contrib.auth.models import User .

For example - you have a cars list in Template context. You can do something like this, if I understand you correctly:

<form>
<select name="cars">
  {% for car in cars%}
     <option value={{ car.name }}>{{ car.name }}</option>
  {% endfor %}
</select>
<input type="submit" value="Submit">
</form>

Describe your model and your form as well. It's pretty simple in Django. If you have a form and the form is passed to the template, you can render the form as follows:

{{ form.as_p }}

Model example:

from django.db import models

# Your model choices
class SampleCategory(models.Model):
    title = models.CharField(max_length=255)

# Your sample model that uses the model with choices
class SampleModel(models.Model):
   category = models.ForeignKey(SampleCategory)

Form example:

from django import forms

from yourapp.models import SampleModel

class SampleModelForm(forms.ModelForm):
    class Meta:
        model = SampleModel

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