我想在view.py文件中获取单选按钮值,我正在获取除单选按钮值以外的所有值
我尝试使用POST和GET方法获取数据,但两者均对我不起作用 // HTML代码
<label class="col-12 col-sm-2">Rating</label>
<input type="radio" class="form-control radio-inline col-sm-1 mt-1" name="radoption" value=" 1">1
<input type="radio" class="form-control radio-inline col-sm-1 mt-1" name="radoption" value=" 2" checked>2
<input type="radio" class="form-control radio-inline col-sm-1 mt-1" name="radoption" value=" 3">3
<input type="radio" class="form-control radio-inline col-sm-1 mt-1" name="radoption" value=" 4">4
<input type="radio" class="form-control radio-inline col-sm-1 mt-1" name="radoption" value=" 5">5
// View.py代码
if request.method == "POST":
radoption = str(request.POST["radoption"])
return redirect("/")
/ p 答案 0 :(得分:0)
整个过程都是倒退的。发布您的视图,表单和html,我将向您展示正确的方法。基本上,您不应该以相同的方式命名所有5个字段,单选按钮应该是在form.py中提供选择的一个字段。然后,您将调用form.cleaned_data.get(“ radoption”)在views.py中获取信息...
答案 1 :(得分:0)
做这样的事情。
forms.py
from django import forms
NUMS= [
('one', 'one'),
('two', 'two'),
('three', 'three'),
('four', 'four'),
('five', 'fives'),
]
class CHOICES(forms.Form):
NUMS = forms.CharField(widget=forms.RadioSelect(choices=NUMS))
views.py
from .forms import CHOICES
def name_of_url_goes_here(request):
form = CHOICES(request.POST)
if form.is_valid():
selected = form.cleaned_data.get("NUMS")
print(selected)
return render(request, 'name_of_page.html', {'form':form})
html
<form class="form-inline" method='POST' action="" enctype='multipart/form-data'>{% csrf_token %}
{{form.NUMS}}
</form>