2016-12-01 74 views
3

指定我是新來的Django未知領域(S)(身體),寫在標題AM接收錯誤。我谷歌它,但我無法找到任何thing.actually我想做的只是一個添加「評論」到我的博客網站。我添加我的代碼如下。謝謝你 我的文件:django.core.exceptions.FieldError:徵詢意見

#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, '[email protected]', 
                 [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, '[email protected]', 
         [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 

回答

6

您需要'body'像下面以去除'body '場,結束白色的空間,你應該有:

class CommentForm(forms.ModelForm): 
    class Meta: 
     model = Comment 
     fields = ('name', 'email', 'body') 
+0

謝謝sir..its工作 –

1

同樣的錯誤也發生如果包含editable=False的模型字段包含在表單的字段中。刪除模型字段中的editable屬性可修復錯誤。

+0

成爲可能。但我的問題是在'身體'的話。我不應該留下空間。謝謝 –