我正在做一个Django项目,当我尝试访问127.0.0.1:8000/articles/create时,我的Ubuntu终端出现以下错误:
/home/(my name)/django_test/article/forms.py:4: RemovedInDjango18Warning: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is deprecated - form ArticleForm needs updating
class ArticleForm(forms.ModelForm):
另外,在访问我的本地主机站点时,我还会收到以下错误消息:
ValueError at /articles/create/
The view article.views.create didn't return an HttpResponse object. It returned None instead.
这是我的forms.py文件:
from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
这是我的views.py文件:
from django.shortcuts import render_to_response
from article.models import Article
from django.http import HttpResponse
from forms import ArticleForm
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
#import pdb; pdb.set_trace()
# Create your views here.
def articles(request):
language = 'en-us'
session_language = 'en-us'
if 'lang' in request.COOKIES:
language = request.COOKIES['lang']
if 'lang' in request.session:
session_language = request.session['lang']
return render_to_response('articles.html',
{'articles':
Article.objects.all(), 'language' : language,
'session_language' : session_language})
def article(request, article_id=1):
return render_to_response('article.html', {'article':
Article.objects.get(id=article_id) })
def language(request, language='en-us'):
response = HttpResponse("setting language to %s" %
language)
response.set_cookie('lang', language)
response.session['lang'] = language
return response
def create(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
我不确定如何解决此问题。我查看了Django文档,但找不到解决我问题的方法,因此将不胜感激。
最佳答案
对于您的表单,这是一个警告,而不是错误,告诉您在django 1.8中,您需要将表单更改为
from django import forms
from models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = '__all__' # Or a list of the fields that you want to include in your form
或在列表字段中添加
exclude
以排除在外直到1.8才需要
https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#selecting-the-fields-to-use
至于 View 的错误,您的返回内容位于
if
语句:if request.POST:
内,因此当它收到get请求时,不会返回任何内容。def create(request):
if request.POST:
form = ArticleForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/articles/all')
else:
form = ArticleForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('create_article.html', args)
只需确定
else
块的大小,以便将其应用于正确的if
语句。