这是我的views.py
from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django import forms
def TestLayer(request):
users = User.objects.all()
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
user = form.cleaned_data['user']
rad1=form.cleaned_data['radio1']
rad2=form.cleaned_data['radio2']
test = Permission()
test.user = user
test.val = rad1 + rad2
test.save()
return render_to_response('testlayer.html',{'user':users})
else:
form = TestForm()
return render_to_response('testlayer.html', {'user':users})
这是我的forms.py
from django import forms
from django.forms.widgets import RadioSelect
class TestForm(forms.Form):
user = forms.CharField(max_length=100)
RADIO_CHOICES1 = [['1','Radio 1'],['2','Radio 2']]
RADIO_CHOICES2 = [['3','Radio 2'],['4','Radio 2']]
radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES1)
radio = forms.ChoiceField( widget=RadioSelect(), choices=RADIO_CHOICES2)
我的urls.py就是这个 URL(R '^测试/', 'test.views.TestLayer',名称= 'testlayer'),
当我点击提交按钮时,表单未处理或导致404错误。根据表格和模板,我的观点是否正确?我已经从表格中生成了模板。
答案 0 :(得分:1)
我注意到有关您的视图和表单代码的一些事情......
首先,你的TestForm类定义了两次“radio”,而不是你在视图中的表单清理数据集合中寻找的两个字段:radio1,radio2
其次,您没有将表单传递给视图中的模板。
第三,没有必要两次返回render_to_response,或者甚至没有需要创建测试表单的新实例的条件。相反,试试这个:
#views.py
from django.conf import settings
from django.shortcuts import render #assumes Django 1.3
#these imports seem to be missing...
from your_app.forms import TestForm
from your_app.models import Permission
def test_layer(request):
users = User.objects.all()
form = TestForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
cleaned_data = form.cleaned_data
user = cleaned_data.get('user')
radio1 = cleaned_data.get('radio1')
radio2 = cleaned_data.get('radio2')
test = Permission()
test.user = user
test.val = radio1 + radio2
test.save()
return render(request, 'testlayer.html', {'user':users, 'form' : form})
#forms.py
from django import forms
class TestForm(forms.Form):
user = forms.CharField(max_length=100)
RADIO_CHOICES1 = [['1','Radio 1'],['2','Radio 2']]
RADIO_CHOICES2 = [['3','Radio 2'],['4','Radio 2']]
radio1 = forms.ChoiceField( widget=forms.RadioSelect(), choices=RADIO_CHOICES1)
radio2 = forms.ChoiceField( widget=forms.RadioSelect(), choices=RADIO_CHOICES2)
此外,您的网址格式不以$结尾,您可以为模式添加前缀,以避免重复查看功能的路径:
#urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('test.views',
url(r'^tests/$','test_layer', name='testlayer'),
)
最后,您的视图函数名称是标题为:TestLayer。在Python中,函数名称,变量等的约定是低级的,下划线分隔单词,类是标题的。
希望能帮到你。