P
P
PyChan2020-06-02 17:29:32
Django
PyChan, 2020-06-02 17:29:32

Why does a 404 error occur when using get_absolute_url?

In models.py:

class Items(models.Model):
    id = AutoField(primary_key=True)
    name = CharField(max_length=150)
    date = DateField(default=timezone.now())
    marks = ForeignKey(Marks, on_delete=models.DO_NOTHING, null=True)
    category = ForeignKey(Cats, on_delete=models.DO_NOTHING, null=True)
    price = DecimalField(max_digits=7, decimal_places=2)
    previous_price = DecimalField(max_digits=7, decimal_places=2, null=True)
    article_number = CharField(max_length=150)
    description = TextField(null=True)
    picture = TextField(null=True)
    video = TextField(null=True)
    objects = models.Manager()

    def get_absolute_url(self):
        return "/item/%i/" % self.id

in urls.py:
urlpatterns = [path('', views.index, name='index'), path('add_item/<int:id>', views.add_item, name='add_item'),
               path('register', views.add_user, name='register'), path('item/<int:id>', views.item, name='item')]


In views.py:
def item(request, id):
    context = {'cats_nav': Cats.objects.filter(location='nav'), 'objects': Items.objects.get(id=id)}
    return render(request, 'index.html', context)

When going to item/1, an error occurs. Why is that?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-06-02
@PyChan

Don't hardcode like that, use reverse, it's directly mentioned in the docs
Well, item/1 vs item/1/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question