How to get radio button value from FORM in view.py file

一个人想着一个人 提交于 2020-12-15 04:55:12

问题


I wanna get the radio button value in view.py file, I'm getting all the values except for radio button value

I tried to get data using POST and GET method but both didnt work for me //HTML code

<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 Code

if request.method == "POST":
    radoption = str(request.POST["radoption"])
    return redirect("/")

TypeError at /rating User() got an unexpected keyword argument 'radoption'


回答1:


Do something like this.

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>



回答2:


The whole thing is done backwards. Post your views, forms, and html and I'll show you the right way. Basically, you shouldn't be naming all 5 of those fields the same way, and the radio button should be one field with the selections given in form.py. Then you would call form.cleaned_data.get("radoption") to get the info in views.py ...



来源:https://stackoverflow.com/questions/57422465/how-to-get-radio-button-value-from-form-in-view-py-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!