Reputation: 11
I cant get my head around this problem. Went to countless sites and question but can't find why it doesn't work. Everything is imported. The error I get after I run the server is: Reverse for 'random_book' with arguments '('',)' not found. 1 pattern(s) tried: ['book/(?P[-a-zA-Z0-9_]+)$'] It highlights this with red from template: {% url 'random_book' random_item.slug %} Models:
class Books(models.Model):
title=models.CharField(max_length=200)
author=models.CharField(max_length=150)
description=models.TextField()
cover=models.ImageField(upload_to='images/', blank=True)
slug=models.SlugField(max_length=100, blank=True, unique=True)
genre=models.ManyToManyField(Genres)
def save(self, *args, **kwargs):
self.slug= slugify(self.title)
super().save(*args, **kwargs)
def __str__(self):
return self.title
def get_absolute_url(self):
kwargs=self.slug
return reverse('random_book', kwargs=kwargs)
Views:
def random_book(request, slug):
cartile=Books.objects.all()
random_item=random.choice(cartile)
return render(request, 'carti/book.html', context={"random_item": random_item})
Urls:
path('book/<slug:slug>', views.random_book, name="random_book"),
Template:
<a href="{% url 'random_book' random_item.slug %}">{{ random_item.title }}</a>
Hope you guys can help me.
EDIT: If anybody ever comes across this, I've fixed the problem myself and here's how:
The problem is with the view. I try to get the random book in the page that displays the book instead of home page where the button is pressed. Basically on the home page if you press the button it takes you to another page where the randomize process starts, hence it doesn't have any slug data to pass. You need to add there the random.choice().
Then, to get that random data and display it with it's unique slug, you just need to use book=Books.objects.get(slug=slug) on that random_book view. For some reason I still don't understand, by fetching the slug, somehow you get the data associated with that slug.
Upvotes: 1
Views: 127
Reputation: 3390
This is a "reverse using kwargs" type of problem. I suspect your error originates here:
def get_absolute_url(self):
kwargs=self.slug
return reverse('random_book', kwargs=kwargs)
This is not how you use reverse
, see an example.
I would suspect that rewriting the code in this manner is going to fix the issue:
def get_absolute_url(self):
kwargs={'slug': self.slug}
return reverse('random_book', kwargs=kwargs)
Upvotes: 1