[英]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. 我想在HTML模板中创建一个下拉列表,该模板从Django数据库中提取数据。 Is there anyway I can code it in the
<option value...>
? 无论如何,我可以在
<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
. 问题是,我需要利用的
username
外地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.
在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.