django.core.exceptions.FieldError:为Comment指定的未知字段(正文)

前端之家收集整理的这篇文章主要介绍了django.core.exceptions.FieldError:为Comment指定的未知字段(正文)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是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,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'],post.title)
            message = 'Read "{}" at {}\n\n{}\'s comments: 
                                {}'.format(post.title,[cd['to']])
            sent = True
    else:
        form = EmailPostForm()
    return render(request,'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",in 
    import_module
        return _bootstrap._gcd_import(name[level:],level)
          File "<frozen importlib._bootstrap>",in _gcd_import
          File "<frozen importlib._bootstrap>",in _find_and_load
          File "<frozen importlib._bootstrap>",in 
    _find_and_load_unlocked
          File "<frozen importlib._bootstrap>",in _load_unlocked
          File "<frozen importlib._bootstrap_external>",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

解决方法

您需要删除“body”字段末尾的空白区域,您应该在其中有“body”,如下所示:
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name','body')
原文链接:https://www.f2er.com/python/186671.html

猜你在找的Python相关文章