我是Django的初学者,我正在创建Django表单以获取输入和处理。我创建了一个名为“艺术家”的应用程序,我将文件编码如下。 我的错误是in this picture 这是我在服务器文件夹中的urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^artists/', include('artists.urls')),
]
这些是'艺术家'应用中的文件 - > urls.py< -
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^artists/', views.artistcreate, name="artistcreate")]
- > views.py< -
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from datetime import datetime
from artists.models import *
def artistcreate(request):
if request.method=="GET":
form=ArtistForm()
return render(request,'artists/create.html',{'form':form})
elif request.method=="POST":
form=ArtistForm(request.POST)
form.save()
return HttpResponseRedirect('/artists')
- > models.py< -
from django.db import models
from django.forms import ModelForm
class Artist(models.Model):
name=models.CharField(max_length=50)
year_formed=models.PositiveIntegerField()
class ArtistForm(ModelForm):
class Meta:
model=Artist
fields=['name','year_formed']
- > artists / create.html< - 这个html文件在我的模板文件夹中
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Test</title>
</head>
<body>
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Save</button>
</form>
</body>
</html>
我需要帮助来创建一个django表单,它接收输入并且能够处理。提前谢谢
答案 0 :(得分:1)
在保存表单之前,您需要致电form.is_valid()
。调用is_valid()
方法时,将运行表单上的验证,并返回布尔值,无论form
是否有效。
您可能需要对视图进行一些更改,
def artistcreate(request):
if request.method=="POST":
form = ArtistForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/artists')
else:
form = ArtistForm()
return render(request,'artists/create.html',{'form':form})