来自不同子页面上的管理面板的帖子

Posts from admin panel on different subpages

我想将 post 列表从主页添加到另一个子页面。 (主页到名为 "programowanie" 的子页面)

例如: 我有一个网站 wwww.example.com。在这个网站上,我有一个从管理面板生成的 post 列表(我可以使用管理面板添加、删除 posts)。 问题是,当我尝试将带有 post 列表的起始页面的模板复制到其他子页面(称为:www.example.com/programowanie)时,它不起作用(我从主页面看到一个模板页面但没有 post 列表) 我认为问题出在 templates/blog/post/list.html in loop {% for post in posts %}
如果我解决了这个问题,我想在管理面板中添加不同的重叠以仅在 "programowanie" 子页面中发布 posts。

这是我的文件: blog/views.py

from django.shortcuts import render, get_object_or_404, HttpResponse
from .models import Post, Posta, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
from taggit.models import Tag
from django.db.models import Count


def post_share(request, post_id):
    # Pobranie posta na podstawie jego identyfikatora.
    post = get_object_or_404(Post, id=post_id, status='published')
    sent = False

if request.method == 'POST':
    # Formularz został wysłany.
    form = EmailPostForm(request.POST)
    if form.is_valid():
        # Weryfikacja pól formularza zakończyła się powodzeniem…
        cd = form.cleaned_data
        post_url = request.build_absolute_uri(
                                      post.get_absolute_url())
        subject = '{} ({}) zachęca do przeczytania "{}"'.format(cd['nick'], cd['email'], post.title)
        message = 'Przeczytaj post "{}" na stronie {}\n\n Komentarz dodany przez {}: {}'.format(post.title, post_url, cd['nick'], cd['komentarz'])
        send_mail(subject, message, 'admin@myblog.com', [cd['adresat']])
        sent = True

else:
    form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
                                                'form': form,
                                                'sent': sent})

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

def post_list(request, tag_slug=None):
    object_list = Post.published.all()
    tag = None

if tag_slug:
    tag = get_object_or_404(Tag, slug=tag_slug)
    object_list = object_list.filter(tags__in=[tag])
    paginator = Paginator(object_list, 3) # Trzy posty na każdej stronie.
    page = request.GET.get('page')
try:
    posts = paginator.page(page)
except PageNotAnInteger:
    # Jeżeli zmienna page nie jest liczbą całkowitą,
    # wówczas pobierana jest pierwsza strona wyników.
    posts = paginator.page(1)
except EmptyPage:
    # Jeżeli zmienna page ma wartość większą niż numer ostatniej strony
    # wyników, wtedy pobierana jest ostatnia strona wyników.
    posts = paginator.page(paginator.num_pages)
return render(request,
              'blog/post/list.html',
              {'page': page,
              'posts': posts,
               'tag': tag})

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()

  # Lista podobnych postów.
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})


def programowanie(request):
        return render(request, 'blog/post/base.html')

blog/models.py

# -*- coding: utf-8 -*-
from taggit.managers import TaggableManager
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
                     self).get_queryset()\
                     .filter(status='published')

class Post(models.Model):
    STATUS_CHOICES = (
        ('draft', 'Roboczy'),
        ('published', 'Opublikowany'),
    )
    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() # Menedżer domyślny.
    published = PublishedManager() # Menedżer niestandardowy.
    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.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()
    komentarz = 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 'Komentarz dodany przez {} dla posta {}'.format(self.name, 
self.post)

blog/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
# Widoki posta.
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
#url(r'^$', views.PostListView.as_view(), name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
    r'(?P<post>[-\w]+)/$',
    views.post_detail,
    name='post_detail'),
url(r'^(?P<post_id>\d+)/share/$', views.post_share,
    name='post_share'),
url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list,
    name='post_list_by_tag'),
]

urls.py

from django.conf.urls import include, url
from django.contrib import admin
from blog import views

 urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^about/', views.about, name="about"),
    url(r'^programowanie/', views.programowanie, name="programowanie"),
    url(r'^algorytmy/', views.algorytmy, name="algorytmy"),
    url(r'^kontakt/', views.kontakt, name="kontakt"),
    url(r'', include('blog.urls',
                           namespace='blog',
                           app_name='blog')),
]

blog/templates/base.html

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
{% include "navbar.html" with page=posts %}
<title>{% block title %}{% endblock %}</title>
<link href="{% static "admin/css/blog.css" %}" rel="stylesheet">
</head>
  <body>
  <div id="content">
    {% block content %}
    {% endblock %}
  </div>
  <div id="sidebar">
    <h2>Mój blog</h2>
      <p>To jest mój blog.</p>
  </div>
</body>
</html>

blog/templates/post/list.html

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


{% block title %}Mój blog{% endblock %}

{% block content %}
  <h1>Mój blog</h1>
  {% if tag %}
    <h2>Posty oznaczone tagiem "{{ tag.name }}"</h2>
  {% endif %}
  {% for post in posts %}
    <h2>
      <a href="{{ post.get_absolute_url }}">
        {{ post.title }}
      </a>
    </h2>
    <p class="tags">
      Tagi:
      {% for tag in post.tags.all %}
        <a href="{% url "blog:post_list_by_tag" tag.slug %}">
          {{ tag.name }}
        </a>
        {% if not forloop.last %}, {% endif %}
      {% endfor %}
    </p>
    <p class="date">
      Opublikowany {{ post.publish }} przez {{ post.author }}
    </p>
    {{ post.body|truncatewords_html:30|linebreaks }}
  {% endfor %}

  {% include "pagination.html" with page=posts %}
{% endblock %}

blog/templates/post/detail.html

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

{% block title %}{{ post.title }}{% endblock %}

{% block content %}
  <h1>{{ post.title }}</h1>
  <p class="date">
     Opublikowany {{ post.publish }} przez {{ post.author }}
  </p>
   {{ post.body|linebreaks }}
  <p>
    <a href="{% url "blog:post_share" post.id %}">
      Udostępnij posta
    </a>
  </p>
 <h2>Podobne posty</h2>
  {% for post in similar_posts %}
    <p>
      <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
    </p>
  {% empty %}
    Nie ma podobnych postów.
  {% endfor %}
{% with comments.count as total_comments %}
    <h2>
      {{ total_comments }} komentarz{{ total_comments|pluralize:"y" }}
    </h2>
  {% endwith %}

  {% for comment in comments %}
    <div class="comment">
      <p class="info">
        Komentarz {{ forloop.counter }} dodany przez {{ comment.name }}
          {{ comment.created }}
      </p>
      {{ comment.komentarz|linebreaks }}
    </div>
  {% empty %}
    <p>Nie ma jeszcze żadnych komentarzy.</p>
  {% endfor %}

  {% if new_comment %}
    <h2>Twój komentarz został dodany.</h2>
  {% else %}
    <h2>Dodaj nowy komentarz</h2>
    <form action="." method="post">
      {{ comment_form.as_p }}
      {% csrf_token %}
      <p><input type="submit" value="Dodaj komentarz"></p>
    </form>
  {% endif %}
{% endblock %}

感谢您的帮助!! (我在想这第三天)

你的问题出在视图上。

Django 模板必须由视图呈现,您可以从视图中获取要在模板中呈现的数据。您要使用哪个 url 以及您在视图中使用哪个模板都没有关系。这意味着你可以有不同的 urls 指向同一个模板(www.example.com/blog/ 或 www.example.com/programming/)并且两者都渲染相同的模板。

如果我没看错,你只需要改变这个:

url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),

为此:

url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.post_list, name='programowanie'),

您可以参考 Django 官方网站以获得更多相关信息:https://docs.djangoproject.com/en/2.0/intro/tutorial03/

感谢您的帮助:)

我解决了这个问题。 urls.py 文件中有问题。