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.
Asked 1 year ago by MercurialAdventurer548
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:
PYTHONclass 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:
PYTHONdef get_absolute_url(self): return reverse("updateingredient", kwargs={"pk": self.pk})
However, when I click the link, I receive the following error:
BASHTraceback (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.
Comments 0
•Answers 0
•Views 4.1k
No comments yet.