-3

我是 Django 的初学者,我正在创建 Django 表单以获取输入和处理。我创建了名为“艺术家”的应用程序,并将文件编码如下。我的错误在这张图片中 这是我在服务器文件夹中的 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")]

-> 视图.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')

-> 模型.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']

-> 艺术家/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 表单。提前致谢

4

1 回答 1

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})
于 2017-07-02T17:01:14.097 回答