Home > Mobile >  Having additional url under <slug:slug> django
Having additional url under <slug:slug> django

Time:06-02

I am trying to add another html webpage on top of a slug:slug url and it throws an error.. i have no idea what went wrong here.

Already tried everything i can think of and on the border of giving up, can someone here please help? :)

Error message :

TypeError at /movies/joker/new/
add_comment() got an unexpected keyword argument 'slug'
Request Method: GET
Request URL:    http://127.0.0.1:8000/movies/joker/new/
Django Version: 4.0.4
Exception Type: TypeError
Exception Value:    
add_comment() got an unexpected keyword argument 'slug'
Exception Location: C:\Users\zenmy\PycharmProjects\pythonProject\venv\lib\site-packages\django\contrib\auth\decorators.py, line 23, in _wrapped_view
Python Executable:  C:\Users\zenmy\PycharmProjects\pythonProject\venv\Scripts\python.exe
Python Version: 3.8.0
Python Path:    
['C:\\Users\\zenmy\\PycharmProjects\\pythonProject\\Django-IMDB',
 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip',
 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38\\DLLs',
 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38\\lib',
 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38',
 'C:\\Users\\zenmy\\PycharmProjects\\pythonProject\\venv',
 'C:\\Users\\zenmy\\PycharmProjects\\pythonProject\\venv\\lib\\site-packages']
Server time:    Thu, 02 Jun 2022 06:26:36  0000

urls.py

from django.urls import path
from .views import MovieList, MovieDetail, MovieCategory, MovieLanguage, MovieSearch, MovieYear
from . import views

app_name = 'movie'

urlpatterns = [
    path('', MovieList.as_view(), name='movie_list'),
    path('search/', MovieSearch.as_view(), name='movie_search'),
    path('category/<str:category>', MovieCategory.as_view(), name='movie_category'),
    path('language/<str:lang>', MovieLanguage.as_view(), name='movie_language'),
    path('year/<int:year>', MovieYear.as_view(), name='movie_year'),
    path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'),
    path('<slug:slug>/add-comment/', views.add_comment, name='add-comment'),
    ]

models.py

class Movie(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=1000)
    image = models.ImageField(upload_to='movies')
    banner = models.ImageField(upload_to='movies_banner', blank=True)
    category = models.CharField(choices=CATEGORY_CHOICES, max_length=10)
    language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10)
    status = models.CharField(choices=STATUS_CHOICES, max_length=2)
    cast = models.CharField(max_length=100)
    year_of_production = models.DateField()
    views_count = models.IntegerField(default=0)
    movie_trailer = models.URLField()
    created = models.DateTimeField(blank=True, default=timezone.now)
    slug = models.SlugField(blank=True, null=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Movie, self).save(*args, **kwargs)

    def __str__(self):
    return self.title

views .py

@login_required(login_url='/accounts/login')
def add_comment(request, pk):
    movie = Movie.objects.get(id=pk)
    form = CommentForm()
    context = {
        'form': form
    }

    return render(request, 'add_comment.html', context)

CodePudding user response:

According to url in your urls.py:

path('<slug:slug>/add-comment/', views.add_comment, name='add-comment')

You need to edit your view like this:

@login_required(login_url='/accounts/login')
def add_comment(request, slug):  # We edited here: pk -> slug
    movie = Movie.objects.get(slug=slug)  # And we edited here: pk -> slug, twice.
    form = CommentForm()
    context = {
        'form': form
    }

    return render(request, 'add_comment.html', context)

Now you need to validate your slug and check if movie object exists.

from django.http import Http404  # Don't forget this import!


@login_required(login_url='/accounts/login')
def add_comment(request, slug):
    try:
        movie = Movie.objects.get(slug=slug)
    except Movie.DoesNotExist:  # We catch exception and raise 404 error, it means that movie with that slug doesn't exist.
        raise Http404
    form = CommentForm()
    context = {
        'form': form
    }

    return render(request, 'add_comment.html', context)

P.S. It is not good idea to get your Movie by field, that is not required and not unique. E.g. you have two movies with the same titles and slugs(that are generated from titles). If you pass this slug to the url - you will get MultipleObjectsReturned exception.

  • Related