找不到关键字参数为“{post\u id':'}”的“logcreate”的/post/1/log/Reverse处的NoReverseMatch

2024-10-04 03:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有很多帖子的帖子模型。我还有一个日志模型,它在Post模型中有一个外键字段。基本上,日志模型在Post模型中存储Post的日志条目(基本上是Post评论)。一切都很顺利。我一直在用CBV作为我的post模型,我用CBV列出我的日志条目。然后,我添加了一个链接,使用以下锚定标记将我重定向到Log CreateView:

<a class="btn" href="{% url 'log-create' post_id=logs.post_id %}">Add Entry</a>

当错误开始发生的时候。当我将log.post\u id更改为1时,页面将正确加载。这使我相信log.post\u id不会返回任何值。我的另一个想法是,因为这个锚定标记在LogListView上,所以有多个日志条目,所以它不知道要使用哪个post\u id。但是我在这个视图中使用了get\u queryset函数来确保只返回与单个post相关的日志。在我看来log.post\u id应该有用

我的模型是:

class Post(models.Model):
    title = models.CharField(max_length=100, blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    overview = models.TextField(blank=True)

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.id})

    def __str__(self):
        return self.title

class Log(models.Model):
    post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
    log_entry = models.TextField(max_length=500, blank=True)
    log_author = models.ForeignKey(User, on_delete=models.CASCADE)
    date_posted = models.DateTimeField(default=timezone.now)

我的观点:

from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView, CreateView
from .models import Post, Log
from django.http import HttpResponseRedirect
from django.contrib.auth.mixins import LoginRequiredMixin

class LogListView(ListView):
    model = Log
    template_name = 'blog/log_entries.html'
    context_object_name = 'logs'
    ordering = ['-date_posted']

    def get_queryset(self):
        self.post = get_object_or_404(Post, log=self.kwargs['pk'])
        return Log.objects.filter(post=self.post)

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(LogListView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all images related to post
        context['post'] = Post.objects.all()
        return context

class LogCreateView(LoginRequiredMixin, CreateView):
    model = Log
    fields = [
            'log_entry'
            ]

    def form_valid(self, form):
        form.instance.log_author = self.request.user
        post = Post.objects.get(pk=self.kwargs['post_id'])
        return super().form_valid(form)

我的URL.py


from django.urls import path, include
from . import views 
from .views import LogListView, LogCreateView

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/log/', LogListView.as_view(), name='log-list'),
    path('post/<int:post_id>/log/new/', LogCreateView.as_view(), name='log-create'),
]

最后,我的模板:

{% extends "blog/base.html"%}
{% block body_class %} home-section {% endblock %}
{% block content %}
  <div class="container">
    <h2>Log Entries</h2>
      {% for log in logs %}
      <div class="row">
        <article class="content-section">
            <div class="article-metadata log-metadata">
              <a class="mr-2" href="{% url 'profile' user=log.log_author %}">{{ log.log_author }}</a>
              <small class="text-muted">{{ log.date_posted|date:"d F Y" }}</small>
              {% if request.user.is_authenticated and request.user == log.log_author %}
                <a href="#"><ion-icon name="trash"></ion-icon></a>
              {% endif %}
            </div>
            <p class="">{{ log.log_entry }}</p>
        </article>
        </div>
      {% endfor %}
      <a class="btn" href="{% url 'log-create' post_id=logs.post_id %}">Add Entry</a>

  </div>
{% endblock content %}

我认为我正确地向url传递了一个参数。当我把post\u id=1时,这一点就很明显了。但是我不确定我是否正确地调用了它。在这个问题上有任何帮助都会很好,谢谢

更新:我将LogListView中的context\u object\u name编辑为logs,以减少for循环的混乱。实际上,我试图在所有日志条目的底部获得一个锚定标记,以重定向到addentry页面


Tags: namefrom模型importselflogidget
1条回答
网友
1楼 · 发布于 2024-10-04 03:25:06

我建议使用第一个元素,仅当存在可用对象时呈现链接:

  </article>
  </div>
  {% if forloop.first %}<a class="btn" href="{% url 'log-create' post_id=log.post.id %}">Add Entry</a>{% endif %}
{% endfor %}

log.post.id表示日志对象的post对象(外键)的get id

相关问题 更多 >