我想创建两个字段:单选按钮和下拉列表 单选按钮将填充给定的选项,下拉菜单将从数据库中提取。 停留在显示广播和获取值上
我应该使用modelform还是form?我希望将单选按钮的选择与下拉值一起按下时将数据存储在DB中,并希望使用该值来显示案例类型。
型号class Selections(models.Model):
roletype = models.CharField(max_length=8, default=None)
LOCATIONS = (('DC1','DC1'), ('DC2', 'DC2'), ('DC3', 'DC3'))
location = models.CharField(max_length=4, choices=LOCATIONS)
def __str__(self):
return self.roletype
表格
from django import forms
from .models import Selections
class SelectionsForm(forms.ModelForm):
ROLES = (('1','Type1'),('2','Type2'),('3', 'Type3'))
roletype = forms.ChoiceField(choices=ROLES, widget=forms.RadioSelect)
class Meta:
model = Selections
fields = ['roletype','location']
VIEWs.py
## VIEW: Populate dropdown to select Data center
def get_role_dc_data(request, *args, **kwargs):
location = Selections.objects.get(id=0) # List of objects
roletype = Selections.objects.get(id=1) # List of objects
context = { 'location': location, 'roletype': roletype }
return render(request, 'selections/view.html', context)
view.html
<form method="post" action=/viewselections/> {% csrf_token %}
<table class="table">
<tr>
<th>
{% for radio_input in context.roletype %}
<input type="radio" name="choice" id="{{ radio_input.id }}" value="{{ radio_input.id }}">
{% endfor %}
</th>
<th>
<div class="fieldWrapper" align="center" id="mainselection">
<select name="location">
<option selected="selected">Select an the site</option>
{% for instance in context.location %}
<option >{{ instance.location }}</option>
{% endfor %}
</select>
</div>
</th>
</tr>
</table>
</form>
无法获取该值。不确定这是否正确 同样,一旦用户选择了选项,如何显示返回数据并存储在DB中。