2 回答
TA贡献1155条经验 获得超0个赞
request.POST.get您可以通过使用所有提交的数据所在位置来获取选择框值。
views.py
def myview(request):
if request.method == "POST":
selected_option = request.POST.get('select')
Znat.objects.create(name_znat=selected_option)
return redirect("/")
{% csrf_token %}
每当您使用表单时也应该有。除非您的视图已明确标记为csrf_exempt
.
<form method = "POST" action = "{% url 'create_group_handler'%}">
{% csrf_token %}
<select name = "select"> <! - Add an identifier here instead of using 'name' ->
<option value = "value1"> Value 1 </ option>
<option value = "value2" selected> Value 2 </ option>
<option value = "value3"> Value 3 </ option>
</ select>
</ form>
TA贡献1854条经验 获得超8个赞
使用 ModelForm,最大限度地利用 Django 的内置功能。祝你好运!
models.py:
class Znat (models.Model):
CHOICES = (
('value1', 'Value 1'),
('value2', 'Value 2'),
('value3', 'Value 3'),
)
name_znat = models.CharField ('Name znat', max_length = 200, choices=CHOICES)
forms.py:
class CreateZnatForm(ModelForm):
class Meta:
model = Znat
fields = ('name_znat')
widgets = {
'name_znat': forms.Select(attrs={'class': 'form-control'}),
}
views.py:
class ZnatCreate(CreateView):
model = Znat
fields = ['name_znat']
urls.py:
urlpatterns = [
path('znat/', ZnatCreate.as_view(), name='create_group_handler'),
]
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报