简体   繁体   中英

Django ImportError: cannot import name Comment

I am new to Django, currently following a book, Django by Example Antonio Mele. It is a Blog project. When attemtpting to extend an blog posts app to add comments. Am receiving imprt error. Am unable to import a models created in the project have included models, views, forms and traceback below

forms.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)

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
from .forms import EmailPostForm, CommentForm

# Create your models here.
class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager, self).get_queryset().filter(status='published')



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)

views.py

from django.shortcuts import render , get_object_or_404
from blog.models import Post, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from django.core.mail import send_mail
from blog.forms import CommentForm, EmailPostForm

class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 3
    template_name = 'list.html'


# Create your views here.


def post_list(request):
    posts = Post.objects.all()
    object_list = Post.published.all()
    paginator = Paginator(object_list,3)
    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, 'list.html', {'posts': posts,
                                         'page':page})



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)
    #list of active comments for this post
    comments = post.comments.filter(active=True)

    if request.method == 'POST':
        # A comment was posted
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            #create comment object but don't save to DB
            new_comment = comment_form.save(commit=False)
            # assitgn comment to post
            new_comment.post = post
            # save the comment to the DB
            new_comment.save()

    else:
        comment_form =CommentForm()

    args = {}
    args.update(csrf(request))
    args['post'] = post 
    args['comment_form']= comment_form
    args['comments'] = comments 



    return render(request, 'detail.html', args )




def post_share(request,post_id):
    # retrieve post by id
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False

    if request.method == 'POST':
        # form was submitted
        form = EmailPostForm(request.POST)
        if form.is_valid():
            # Forms fields passed validation#
            cd = form.cleaned_data


        post_url = request.build_absolute_uri(post.get_absolute_url())
        subject = '{} recommends you read "{}"'.format(cd['name'],post.title)
        message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title,post_url,cd['name'],cd['comments'])

        send_mail(subject,message,'eugenesleator17@gmail.com',[cd['to']])




        sent=True
    else:

        form = EmailPostForm()

    return render(request, 'share.html',{'post':post,
                                        'form': form,
                                        'sent': sent})

        return "Comment by {} on {}".format(self.name, self.post)

Traceback

(MySiteVirtualEnv) root@kali:~/MySite/MySiteVirtualEnv/mysite# python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/root/MySite/MySiteVirtualEnv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/root/MySite/MySiteVirtualEnv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 327, in execute
    django.setup()
  File "/root/MySite/MySiteVirtualEnv/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/root/MySite/MySiteVirtualEnv/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/root/MySite/MySiteVirtualEnv/local/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/root/MySite/MySiteVirtualEnv/mysite/blog/models.py", line 5, in <module>
    from .forms import EmailPostForm, CommentForm
  File "/root/MySite/MySiteVirtualEnv/mysite/blog/forms.py", line 3, in <module>
    from blog.models import Comment
ImportError: cannot import name Comment

You are trying to do a circular (cyclic) import. Remove the following line from your models.py :

from .forms import EmailPostForm, CommentForm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM