首页 > 解决方案 > 浏览器不会呈现同时包含详细视图和列表视图的模板

问题描述

我正在建立一个问答网站作为我的第一个 django 实践项目(第一个项目的错误选择),但是我创建了一个问题模型(PoliticsPost)和一个答案模型(Answer),并使用外键和带有问题实例的答案实例使用正在回答的问题的 ID。该网站的逻辑是将问题显示在模板中(列表视图),每个问题都是指向其描述(详细视图)和与之关联的所有答案(列表视图)的链接。问题是,虽然我在模板中插入了问题上下文名称和答案上下文名称,但浏览器只呈现问题详细视图。

(对不起,如果这令人困惑,那是因为我首先感到困惑)

这是代码:

视图.py:

     class Home(ListView):
    model= PoliticsPost
    context_object_name = 'politicsposts'
    ordering = ['-date_posted']
    paginate_by = 5


def about(request):
    return render(request, 'lisk_templates/about_template.html')


@login_required
def interests(request):
    return render(request, 'lisk_templates/interests_template.html')


class Profile(LoginRequiredMixin,ListView):
    model = PoliticsPost
    context_object_name = 'politicsposts'
    paginate_by = 5
    ordering = ['-date_posted']


class Outerprofile(ListView):
    model = PoliticsPost
    context_object_name = 'politicsposts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return PoliticsPost.objects.filter(author=user).order_by('-date_posted')


#POLITICS-------------


class Politics_topic(ListView):
    model= PoliticsPost
    context_object_name = 'politicsposts'
    ordering = ['-date_posted']
    paginate_by = 5


class Politics_post_details(DetailView):
    model = PoliticsPost
    context_object_name = 'politicsposts'



class Questionpolitics(LoginRequiredMixin, CreateView):
    model = PoliticsPost
    fields =['question','description']
    success_url = reverse_lazy('Politics_topic')

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)


class Updatepolitics(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
    model = PoliticsPost
    fields = ['question','description']
    success_url = reverse_lazy('Politics_topic')

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False


class Deletepoliticspost(LoginRequiredMixin, UserPassesTestMixin, DeleteView):

    model = PoliticsPost
    success_url = reverse_lazy('Politics_topic')

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False



#ANSWER


class CreateAnswer(LoginRequiredMixin,CreateView):
    model = Answer
    fields = ['content']
    success_url = reverse_lazy('Lisk home')
    question_id = 'qid'
    pk_url_kwarg = 'aid'



    def form_valid(self, form):
        try:
            question = PoliticsPost.objects.get(pk=self.kwargs[self.question_id])
        except PoliticsPost.DoesNotExist:
            form.add_error(None, 'Invalid question')
            return self.form_invalid(form)
        form.instance.post = question
        form.instance.author = self.request.user
        return super().form_valid(form)

class Answers(ListView):
    model = Answer
    context_object_name = 'answers'
    ordering = ['-date_posted']

    def get_queryset(self):
        question_id = get_object_or_404(PoliticsPost, pk=self.kwargs.get('qid'))
        return Answer.objects.filter(post_id=question_id)

urls.py(不是根):

path('politicspost/<int:pk>/',views.Politics_post_details.as_view(template_name='lisk_templates/politics_post_details.html'),
             name='politics_post_details'),

urls.py(not root):     path('politicspost/<int:qid>',views.Answers.as_view(template_name='lisk_templates/politics_post_details.html'),name ='answerslist')

政治帖子模板.html:

{%extends "lisk_templates/base.html"%}
{% block title %}
    Post Details
{% endblock title %}

{%block body%}
    <h1 id="page_topic">Page topic</h1>
    <div class="feed">
        <div class="question">

            <h1>{{ politicsposts.question }}</h1>
            <p><img src="{{ politicsposts.author.profile.image.url }}" height="30" width="30">
                <br>
                By <a href="{% url 'Outerprofile' politicsposts.author.username %}">{{ politicsposts.author }}</a> | <span>{{ politicsposts.date_posted }}</span></p>
            <h4>{{ politicsposts.description }}</h4>

            <hr>
             <a href="{% url 'Answer' politicsposts.id %}" class="speciallink">Answer</a>
              {%  if politicsposts.author == user %}
                <a href="{% url 'updatepoliticspost' politicsposts.id %}" class="speciallink" style="fontsize:14px;">Edit</a>
                <a href="{% url 'deletepoliticspost' politicsposts.id %}" class="speciallink">Delete</a>
            {% endif %}
            <hr>
            <h2>Answers:</h2>
            <hr>
            {% for answer in answers %}
                {% if answer.post == politicsposts %}
                    {{ answer.author }}{{ answer.content }}
                {% endif %}
            {% endfor %}
            </div>
      </div>
{% endblock body %}

模型.py:

class PoliticsPost(models.Model):
    question = models.CharField(max_length=200)
    description = models.TextField(null = True , blank=True)
    date_posted =models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    #solution = models.TextField(null=True,blank=True)


    def __str__(self):
        return self.question

class Answer(models.Model):
    content = models.TextField(null=True,blank=True)
    post = models.ForeignKey(PoliticsPost, on_delete=models.CASCADE)
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    date_posted = models.DateTimeField(default=timezone.now)
    post_id = post.pk

我确定答案与问题相关联,因为当我查看管理页面时,我可以看到特定问题的所有答案。

提前致谢。

标签: pythondjangodjango-viewsdjango-templatesdjango-urls

解决方案


您有两个不同的 url 引用两个不同的视图,因此您不能期望在一个模板中看到来自两个视图的信息。

如果我正确理解您的设置,您需要get_context_data在您的Politics_post_details视图中进行覆盖,以便能够访问相关答案。

例如这样的事情:

def get_context_data(self, **kwargs):
   context = super().get_context_data(**kwargs)
   # now you can get any additional information you want from other models
   question_id = get_object_or_404(PoliticsPost, pk=self.kwargs.get('qid'))
   context['answer'] = Answer.objects.filter(post_id=question_id)
   return context

然后你应该能够{{answer}}在你的模板中使用。


推荐阅读