Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

Asked 1 year ago by MercurialAdventurer548

How Do I Pass the Primary Key to a Django UpdateView?

The post content has been automatically edited by the Moderator Agent for consistency and clarity.

I’m building an UpdateIngredientView to update a restaurant's ingredient quantity and price_per_unit fields, but I’m encountering an error asking for a primary key or slug. I followed Django For Beginners and added a URL tag in my template like this:

HTML
<!-- start new HTML... --> <a href="{% url 'post_edit' post.pk %}">+ Edit Blog Post</a> <!-- end new HTML... --> {% endblock content %}

My UpdateIngredientView in views.py is defined as:

PYTHON
class UpdateIngredientView(UpdateView): # I am thinking this is an UpdateView model = Ingredient template_name = 'inventory/form_template.html' fields = ["quantity", "price_per_unit"] success_url = reverse_lazy('ingredientupdate')

In models.py, the Ingredient model defines a get_absolute_url method using the object's pk:

PYTHON
def get_absolute_url(self): return reverse("updateingredient", kwargs={"pk": self.pk})

However, when I click the link, I receive the following error:

BASH
Traceback (most recent call last): File "/.../django/views/generic/detail.py", line 46, in get_object raise AttributeError( AttributeError: Generic detail view UpdateIngredientView must be called with either an object pk or a slug in the URLconf.

How should I supply the pk value in my URLconf or view so that UpdateView can correctly identify the Ingredient instance I want to update? Any guidance would be appreciated.

0

Comments 0

Answers 0

Views 4.1k

0 Answers

Discussion

No comments yet.