我是Django的新手,我正在尝试使用Django表单将数据插入到表中,但我遇到了这个错误:
NoReverseMatch at / vinesF / NewVid 未找到“NewVid”的反向。 'NewVid'不是有效的视图函数或模式名称。
这是我的观点:
def NewVid(request):
if request.POST:
form = AddVidForm(request.POST)
if form.is_valid():
primaryName = form.cleaned_data['primaryName']
Origin = form.cleaned_data['Origin']
PreferredAudience = form.cleaned_data['PreferredAudience']
Date = form.cleaned_data['Date']
Link = form.cleaned_data['Link']
VPath = form.cleaned_data['VPath']
AddPath = form.cleaned_data['AddPath']
FreshVid = video(primaryName=primaryName, Origin=Origin, PreferredAudience=PreferredAudience, Date=Date,Link=Link, VPath=VPath, AddPath=AddPath)
FreshVid.save()
return HttpResponse("New Video added")
else:
return render(request,'vine/Newvid.html', {form:'form'})
else:
form = AddVidForm()
return render(request,'vine/Newvid.html', {form:'form'})
HTML模板代码:
<form method="post" action="{% url 'NewVid' %}" >
{% csrf_token %} <!-- This line inserts a CSRF token. -->
<table>
{{ form.as_table }} <!-- This line displays lines of the form. -->
</table>
<p><input type="submit" value="Create" /></p>
</form>
{% endblock %}
网址交易:
app_name = 'vinesF'
urlpatterns = [
url(r'^NewVid$',views.NewVid, name='NewVid'),
]
任何帮助表示赞赏。
它可能是代码:
url(r'^NewVid$',views.NewVid, name='NewVid'),
改成:
url(r'^NewVid/$',views.NewVid, name='NewVid'),
并改变:
return render(request,'vine/Newvid.html', {form:'form'})
至:
return render(request,'vine/NewVid.html', {form:'form'})
我最终通过以下方式解决了这个问题:首先,我将我的url处理程序更改为直接从root用户拉到app目录:
urlpatterns = [
url(r'^vinesF/',include('vinesF.urls')),
url(r'^admin/', admin.site.urls),
url(r'^NewVid',vinesF.views.NewVid, name='NewVid'),
] 并在视图中进行更正,我错误地颠倒了解析:
else:
return render(request,'vine/Newvid.html', {'form':form})
else:
form= AddVidForm()
return render(request,'vine/Newvid.html', {'form':form})
在代码格式化中,我看到第二行没有缩进。但是,如果这是错误,它应该给你一个缩进错误。
def NewVid(request):
if request.POST:
form= AddVidForm(request.POST)
if form.is_valid():
primaryName= form.cleaned_data['primaryName']
Origin= form.cleaned_data['Origin']
PreferredAudience= form.cleaned_data['PreferredAudience']
Date= form.cleaned_data['Date']
Link= form.cleaned_data['Link']
VPath= form.cleaned_data['VPath']
AddPath= form.cleaned_data['AddPath']
FreshVid= video(primaryName=primaryName, Origin=Origin, PreferredAudience=PreferredAudience, Date=Date,Link=Link, VPath=VPath, AddPath=AddPath)
FreshVid.save()
return HttpResponse("New Video added")
else:
return render(request,'vine/Newvid.html', {form:'form'})
else:
form= AddVidForm()
return render(request,'vine/Newvid.html', {form:'form'})