我是Django的新手,我收到了标题中写的错误。我谷歌它,但我找不到任何东西。实际上我想做的只是添加“评论”到我的博客网站。我添加我的代码如下。谢谢你 我的档案:
#form.py
from django import forms
from django.db import models
from blog.models import Comment
class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False, widget=forms.Textarea)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False, widget=forms.Textarea)
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body ')
#models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date="publish")
author = models.ForeignKey(User, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES,
default="draft")
objects = models.Manager()
published = PublishedManager()
class Meta:
ordering = ('-publish', )
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return "Comment by {} on {}".format(self.name, self.post)
#viwes.py
from django.shortcuts import render, get_object_or_404
from .models import Post
from django.core.paginator import Paginator, EmptyPage,\
PageNotAnInteger
from django.views.generic import ListView
from django.core.mail import send_mail
from .forms import EmailPostForm, CommentForm
def post_list(request):
posts = Post.objects.all()
object_list = Post.objects.all()
paginator = Paginator(object_list, 3) # 3 posts in each page
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts': posts})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments = post.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
return render(request, 'blog/post/detail.html', {'post':
post,'comments':
comments,'comment_form': comment_form})
class PostListView(ListView):
queryset = Post.objects.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
form = EmailPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading "
{}"'.format(cd['name'], cd['email'],
post.title)
message = 'Read "{}" at {}\n\n{}\'s comments:
{}'.format(post.title, post_url,
cd['name'], cd['comments'])
send_mail(subject, message, 'admin@myblog.com',
[cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})
def post_share(request, post_id):
post = get_object_or_404(Post, id=post_id, status='published')
if request.method == 'POST':
form = EmailPostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
post_url = request.build_absolute_uri(post.get_absolute_url())
subject = '{} ({}) recommends you reading "
{}"'.format(cd['name'], cd['email'],
post.title)
message = 'Read "{}" at {}\n\n{}\'s comments:
{}'.format(post.title, post_url,
cd['name'], cd['comments'])
send_mail(subject, message, 'admin@myblog.com',
[cd['to']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form})
#EROR
Unhandled exception in thread started by <function check_errors.
<locals>.wrapper at 0x0435D198>
Traceback (most recent call last):
File "C:\Python3.5.2\lib\site-packages\django\utils\autoreload.py", line 226 , in wrapper
fn(*args, **kwargs)
File "C:\Python3.5.2\lib\site-
packages\django\core\management\commands\runserver.py", line 121, in inner_run
self.check(display_num_errors=True)
File "C:\Python3.5.2\lib\site-packages\django\core\management\base.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "C:\Python3.5.2\lib\site-packages\django\core\management\base.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Python3.5.2\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Python3.5.2\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config
return check_resolver(resolver)
File "C:\Python3.5.2\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "C:\Python3.5.2\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python3.5.2\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Python3.5.2\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Python3.5.2\lib\site-packages\django\urls\resolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Python3.5.2\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in
_call_with_frames_removed
File "C:\project\mysite\mysite\urls.py", line 21, in <module>
url(r'^blog/', include('blog.urls',namespace='blog', app_name='blog')),
File "C:\Python3.5.2\lib\site-packages\django\conf\urls\__init__.py", line 50,
in include
urlconf_module = import_module(urlconf_module)
File "C:\Python3.5.2\lib\importlib\__init__.py", line 126, in
import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in
_find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "C:\project\mysite\blog\urls.py", line 2, in <module>
from . import views
File "C:\project\mysite\blog\views.py", line 7, in <module>
from .forms import EmailPostForm, CommentForm
File "C:\project\mysite\blog\forms.py", line 16, in <module>
class CommentForm(forms.ModelForm):
File "C:\Python3.5.2\lib\site-packages\django\forms\models.py", line 257, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (body ) specified for Comment
答案 0 :(得分:12)
您需要删除'body '
字段末尾的空格,您应该'body'
,如下所示:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
答案 1 :(得分:4)
如果表单的字段中包含editable=False
的模型字段,也会出现相同的错误。删除模型字段上的editable
属性可修复错误。
答案 2 :(得分:0)
删除“ body”中的空格 它看起来像这样
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
答案 3 :(得分:0)
我浪费了很多时间,因为我不小心在模型的字段定义后面加上了一个逗号
答案 4 :(得分:0)
我刚刚遇到了这个问题的一个变体,其中表单中字段名称的拼写与模型中的拼写相同。我仍然收到错误。
我像这样声明了模型字段:
body = BooleanField(name="The comment's body text")
错误是在我想说name
的地方说了verbose_name
。
因此,模型中确实没有名为 body
的字段,就像错误消息声称的那样,而现在该字段被称为更长的时间。