NoReverseMatch at /post/1/log/ Reverse for 'log-create' with keyword arguments '{'post_id': ''}' not found

Viewed 117

I have a Post model with a whole bunch of posts. I also have a log model which has a foreign key field to the Post model. Essentially the Log model stores log entries for the Posts in the Post model (basically Post comments). Everything was going great. I have been using CBV for my post models and I used a CBV to List my log entries. I then added a link to redirect me to the Log CreateView using the following anchor tag:

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

When the NoReverse errors started occuring. When I change the log.post_id to 1, the page loads correctly. This leads me to believe that the log.post_id is not returning any value. Another thought that I had was that because this anchor tag was on the LogListView there were multiple log entries so it didn't know which post_id to use. But I used the get_queryset function on this view to make sure that only logs related to a single post are returned. In my mind the log.post_id should work.

My models are:

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)

My Views:

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)

My urls.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'),
]

And Lastly, my template:

{% 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 %}

I think I am correctly passing a parameter to the url. this is evident from when I make post_id=1. But I am not sure I am calling it correctly. Any help on this issue would be great thanks.

UPDATED: I edited my context_object_name in my LogListView to logs to make the for loop less confusing. Essentially I am trying to get one anchor tag at the bottom of all the log entries to redirect to the Add entry page.

1 Answers

I suggest an approach that renders a link only if there are objects available, using the first element:

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

This log.post.id means get id of post object (foreign key) of log object.

Related