How to fix NoReverseMatch error in Django for the getting and displaying user specific data in ListView

Viewed 50

Hey I have a video sharing webapp project with basic CRUD operations in it. Any user after successful login can post any number of videos and after login the user is redirected to home page of another app inside the django project.

Home page shows all the videos uploaded by different users. Now I want place all the videos uploaded by the user at an seprate endpoint. If user clicks on this endpoint link in the nav-bar then the user should be directed to this endpoint containing all the videos uploaded by him/her.

I am using builtin class based view ListView for this purpose and I have just one model of Video. But I am getting Noreversematch error after performing get_queryset() function and here is my error : Endpoint page showing error part of views.py

class UserUploads(LoginRequiredMixin, ListView):
model = Video
template_name = 'courses/user_uploads.html'
context_object_name = 'videos'


def get_queryset(self):
    user = get_object_or_404(User, username=self.kwargs.get('username'))
    return Video.objects.filter(uploader=user).order_by('-date_time')


def get_success_url(self):
    return reverse('courses:video-detail', kwargs={'pk': self.object.pk})

part of urls.py

from django.urls import path, include
from django.contrib import admin
from . import views
from .views import CreateVideo, DetailVideo, UpdateVideo, DeleteVideo
app_name = "courses"

urlpatterns = [
    path('', views.Index.as_view(), name = "home"),
    path('user-uploads/<str:username>', views.UserUploads.as_view(), name = "user-uploads"),
    path('create-video',  CreateVideo.as_view(), name='video-create'),
    path('<int:pk>/', DetailVideo.as_view(), name='video-detail'),
    path('<int:pk>/update-video', UpdateVideo.as_view(), name='video-update'),
    path('<int:pk>/delete-video', DeleteVideo.as_view(), name='video-delete'),
]

html document of home page nav-bar containg videos of all the different users

{% block content %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="create-video">Create Video</a>
            </li>
            
            <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="{% url 'courses:user-uploads' user.username %}">Your Videos</a>
            </li>
            
            </ul>
            <ul class="nav-item">
                <a class="nav-link active" aria-current="page" href="/logout">Log-Out</a>
            </ul>
            
        </div>
    </div>
</nav>
<div class="container">
    <div class="row justify-content-center">
        {% for object in object_list %}
        <div class="card col-md-3 col-sm-12 mr-md-2 mt-5 p-3 border-0">
            <a href="{% url 'courses:video-detail' object.pk %}"><img src="/media/{{ object.thumbnail }}" width="256" height="144"></a>
            <div class="card-body">
                <a class="link-text" href="{% url 'courses:video-detail' object.pk %}"><h5 class="text-center">{{ object.caption }}</h5></a>
                <p class="text-muted text-center m-0">{{ object.uploader }}</p>
                <p class="text-muted text-center">{{ object.date_time | date:"M d, Y" }}</p>
            </div>
        </div>
        {% endfor %}
    </div>
</div>

courses:user_uploads.html

{% extends "base.html" %}
{% block title %} Your Courses {% endblock %}
{% block content %}
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
        <a class="navbar-brand" href="#">Navbar</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav me-auto mb-2 mb-lg-0">
            <li class="nav-item">
                <a class="nav-link active" aria-current="page" href="create-video">Create Video</a>
            </li>
                        
            </ul>
            <ul class="nav-item">
                <a class="nav-link active" aria-current="page" href="/logout">Log-Out</a>
            </ul>
            
        </div>
    </div>
</nav>

    <h1>Your Uploads</h1>

    <div class="container">
        <div class="row justify-content-center">
            {% for video in videos %}
            <div class="card col-md-3 col-sm-12 mr-md-2 mt-5 p-3 border-0">
                <a href="{% url 'courses:video-detail' video.pk %}"><img src="/media/{{ video.thumbnail }}" width="256" height="144"></a>
                <div class="card-body">
                    <a class="link-text" href="{% url 'courses:video-detail' object.pk %}"><h5 class="text-center">{{ video.caption }}</h5></a>
                    <p class="text-muted text-center m-0">{{ video.uploader }}</p>
                    <p class="text-muted text-center">{{ video.date_time | date:"M d, Y" }}</p>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>

{% endblock %}

models.py

class Video(models.Model):
   uploader = models.ForeignKey(User, on_delete=models.CASCADE)
   caption = models.CharField(max_length=100)
   video_description = models.TextField()
   video_file = models.FileField(upload_to="courses/video_files", validators=[FileExtensionValidator(allowed_extensions=['mp4'])])
   thumbnail = models.FileField(upload_to="courses/thumbnails", validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg'])])
   date_time = models.DateTimeField(default=timezone.now)

   def __str__(self):
       return self.caption
1 Answers

The problem is in the following code because video.pk is an empty string.

<a href="{% url 'courses:video-detail' video.pk %}">

This can be determined because the error message says the reverse was performed with arguments ('',) indicating it was passed an empty string for a positional argument.

Does the Video model have a field specified for the primary key or does it use the automatic id field provided by Django? You may want to use that specific field or .id if it's using the auto id.

Related