Home > Net >  django get an unexpected keyword argument 'slug'
django get an unexpected keyword argument 'slug'

Time:10-12

I get error but I can't understand how to fix it: (MainPage.get() got an unexpected keyword argument 'slug')

This is my model:

class Book(models.Model):
   title = models.CharField(max_length=256)
   price = models.IntegerField()
   category = models.ForeignKey('Category', on_delete=models.PROTECT)
   created_date = models.DateField(auto_now_add=True)
   description = models.TextField(blank=True, null=True)
   count = models.IntegerField(default=0)
   author = models.ForeignKey('Author', on_delete=models.PROTECT)

class Category(models.Model):
   name = models.CharField(max_length=256)
   slug = models.SlugField(blank=True, unique=True, allow_unicode=True)
   created_date = models.DateField(auto_now_add=True)

This is my view:

class MainPage(View):
   def get(self, request):
       books = models.Book.objects.all()
       return render(request, 'core/index.html', {'books': books})

class CategoryPage(View):
   def get(self, request):
       categories = models.Category.objects.all()
       return render(request, 'core/category.html', {'categories': categories})

This is my urls:

urlpatterns = [
path('', views.MainPage.as_view(), name='MainPage'),
path('category/', views.CategoryPage.as_view(), name='Category'),
path('category/<slug:slug>/', views.MainPage.as_view(), name='BookList')]

CodePudding user response:

When you use 'category/<slug:slug>/', django passes slug to your view.

So, either use **kwargs in your view, or declare slug as param in your view:

class MainPage(View):
   def get(self, request, *args, **kwargs):
       # get slug from kwargs and use it as you want
       books = models.Book.objects.all()
       return render(request, 'core/index.html', {'books': books})

Or:

class MainPage(View):
   def get(self, request, slug):
       # Use slug as you want
       books = models.Book.objects.all()
       return render(request, 'core/index.html', {'books': books})

  • Related