在 <slug:slug> django 下有额外的 url

Having additional url under <slug:slug> django

我正在尝试在 slug:slug url 上添加另一个 html 网页,但出现错误。 我不知道这里出了什么问题。

我已经尝试了所有我能想到的并且在放弃的边缘,这里有人可以帮忙吗? :)

错误信息:

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

观看次数.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)

根据您 urls.py 中的 url:

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

您需要像这样编辑视图:

@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)

现在您需要验证您的 slug 并检查电影 object 是否存在。

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。按字段获取电影不是好主意,这不是必需的,也不是唯一的。例如。您有两部电影具有相同的标题和 slug(由标题生成)。如果您将此 slug 传递给 url - 您将得到 MultipleObjectsReturned 异常。