如何在我的表单中显示来自模型的选择框?
How I can show selectbox from models in my form?
如何在我的表单中显示来自模型的选择框。以下代码的输出不显示选择框的选项。
#models.py
class Reg(models.Model):
options = (
('one', 'option1'),
('two', 'option2'),
)
types = models.CharField(max_length=30, choices=options,null=True)
company = models.CharField(max_length=50,null=True)
#form.py
from django import forms
from .models import Reg
class Regform(forms.ModelForm):
class Meta:
model = Reg
fields = ['types','company']
types = forms.CharField(
widget=forms.Select(
attrs={'class': 'form-control'}
),
label="Type",
)
templatefie.html
{% load static %}
{% block main %}
<form method="post" class="post-form" autocomplete="off">
{% csrf_token %}
<div class="row col-md-4 m-auto">
<div>
{{people.as_p}}
<button type="submit" class="save btn btn-primary mt-5">apply</button>
</div>
</div>
</form>
{% endblock %}
标签和小部件可以单独定义。
Class RegForm(forms.ModelForm):
class Meta:
model = Reg
fields = ['types','company']
labels = {
'types': 'Types',
'company': 'Company'
}
widgets = {
'types': Select(attrs={'class':'form-control'})
}
创建一个创建“Reg”模型实例的视图函数,并将上下文传递给模板 context = {'form_obj':Regform()}
{% load static %}
{% block main %}
<form method="post" class="post-form" autocomplete="off">
{% csrf_token %}
<div class="row col-md-4 m-auto">
<div>
{{form_obj.types.label_tag}}
{{form_obj.types}}
<button type="submit" class="save btn btn-primary">apply</button>
</div>
</div>
</form>
{% endblock %}
如何在我的表单中显示来自模型的选择框。以下代码的输出不显示选择框的选项。
#models.py
class Reg(models.Model):
options = (
('one', 'option1'),
('two', 'option2'),
)
types = models.CharField(max_length=30, choices=options,null=True)
company = models.CharField(max_length=50,null=True)
#form.py
from django import forms
from .models import Reg
class Regform(forms.ModelForm):
class Meta:
model = Reg
fields = ['types','company']
types = forms.CharField(
widget=forms.Select(
attrs={'class': 'form-control'}
),
label="Type",
)
templatefie.html
{% load static %}
{% block main %}
<form method="post" class="post-form" autocomplete="off">
{% csrf_token %}
<div class="row col-md-4 m-auto">
<div>
{{people.as_p}}
<button type="submit" class="save btn btn-primary mt-5">apply</button>
</div>
</div>
</form>
{% endblock %}
标签和小部件可以单独定义。
Class RegForm(forms.ModelForm):
class Meta:
model = Reg
fields = ['types','company']
labels = {
'types': 'Types',
'company': 'Company'
}
widgets = {
'types': Select(attrs={'class':'form-control'})
}
创建一个创建“Reg”模型实例的视图函数,并将上下文传递给模板 context = {'form_obj':Regform()}
{% load static %}
{% block main %}
<form method="post" class="post-form" autocomplete="off">
{% csrf_token %}
<div class="row col-md-4 m-auto">
<div>
{{form_obj.types.label_tag}}
{{form_obj.types}}
<button type="submit" class="save btn btn-primary">apply</button>
</div>
</div>
</form>
{% endblock %}