django评论和分享未显示在模板博客文章中

时间:2019-07-09 16:19:02

标签: django

我正在撰写博客文章,并通过示例书关注django 2,在该书中我遇到一个问题。我创建了一个注释和共享部分,该部分未显示在模板中

这是应用程序mysite / blogs / views.py文件:

ask turtles [
   set opinions n-values 3 [random-float 1]
  (foreach opinions [x ->
    let avg-network map mean ([opinions] of turtles)
    let pp position x opinions
    set opinions replace-item pp opinions random-normal (item pp avg-network) 0.1])
  ]
end

mysite / blog / urls.py:

    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():
                # Form fields passed validation
                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, 'abc@gmail.com',
                          [cd['to']])
                sent = True
        else:
            form = EmailPostForm()
        return render(request, 'blog/post/share.html', {'post': post,
                                                        'form': form,
                                                        'sent': sent,
                                                        'cd': cd
                                                        })


    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():
                # Created Comment object but don't save to database yet
                new_comment = comment_form.save(commit=False)
                # Assign the current post to the comment
                new_comment.post = post
                # Save the comment to the database
                new_comment.save()
        else:
            comment_form = CommentForm()

        # List of similar posts
        post_tags_ids = post.tags.values_list('id', flat=True)
        similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)

        similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4]
        return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments,
                                                         'comment_form': comment_form,
                                                         'similar_posts': similar_posts})

mysite / blog / models.py:

urlpatterns = [

    path('', views.post_list, name='post_list'),

    path('<int:year>/<int:month>/<int:day>/<slug:post>/',
         views.post_detail,
         name='post_detail'),

    path('<int:post_id>/share/',
         views.post_share, name='post_share'),

    path('tag/<slug:tag_slug>/',
         views.post_list, name='post_list_by_tag'),
]

mysite / blog / share.html:

    from django.db import models
    from django.utils import timezone 
    from django.contrib.auth.models import User 
    from django.urls import reverse
    from taggit.managers import TaggableManager


    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, 
                                   on_delete=models.CASCADE,
                                   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() # The default manager. 
        published = PublishedManager() # Our custom manager.
        tags = TaggableManager()

        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.month,
                                 self.publish.day,
                                 self.slug])


    class Comment(models.Model): 
        post = models.ForeignKey(Post,
                                 on_delete=models.CASCADE,
                                 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)

mysite / blog / forms.py:

    {% extends "blog/base.html" %}

    {% block title %}Share a post{% endblock %}

    {% block content %}
      {% if sent %}
        <h1>E-mail successfully sent</h1>
        <p>
          "{{ post.title }}" was successfully sent to {{ form.cleaned_data.to }}.
        </p>
      {% else %}
        <h1>Share "{{ post.title }}" by e-mail</h1>
        <form action="." method="post">
          {{ form.as_p }}
          {% csrf_token %}
          <input type="submit" value="Send e-mail">
        </form>
      {% endif %}
    {% endblock %}

mysite / blog / detail.html:

    from django import forms
    from .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')

0 个答案:

没有答案