我像这样写了forms.py
# -*- coding: utf-8 -*-
from django import forms
class InputForm(forms.Form):
name = forms.CharField(max_length=100)
select1 = forms.ChoiceField(widget=forms.RadioSelect,required=False)
select2 = forms.ChoiceField(widget=forms.RadioSelect,required=False)
以html
<div>
{{ f.select1 }}
<label for="select1" dataGoTo="7">select1</label>
{{ f.select2 }}
<label for="select2">select2</label>
</div>
在views.py
中def get_data(request):
if request.method == "POST":
form = InputForm(data=request.POST)
if form.is_valid():
name = form.cleaned_data['name']
我想获取选择了select1或select2的值。 我应该如何写在views.py中?
答案 0 :(得分:0)
您可以使用Ajax在Javascript中完成此操作。右键单击浏览器中的页面,然后选择“查看源代码”。找出您的表单是什么,然后选择元素的ID或类。然后在您的Javascript(jQuery)中执行以下操作:
"use strict";
$(document).ready(function() {
$('form#form_id').on('submit', function(){
// your option elements must have a 'value' attribute
var selectedValue = $('select#select_id').val();
$.ajax({
type:'POST',
url:'your/view/url',
data:{
'selected': selectedValue,
},
dataType: 'json',
success:function(data){
// error handling
if (data['status']==='ok') {
// display success message
} else {
console.log(data);
}
}, // success
}); //ajax
}); // on form submit
}); // document ready
然后在您的views.py:
from django.views.generic import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
class SomeAjaxView(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
if request.user.is_authenticated:
selected = request.POST.get('selected', None)
if selected:
# do something here
return JsonResponse({'status':'ok'})
else:
return JsonResponse({'status':'ko', 'error': 'Value missing'})
return JsonResponse({'status':'ko', 'error': 'Not authenticated'})
使用Ajax的好处是不会在提交时刷新整个页面。这是当今行业标准的做法。