UpdateView requires pk, where can I pull that value?

Now that I have finished Django for Beginers i want to try and complete my first project that does NOT involve a step by step instruction on how to finish things.

I have a class UpdateIngredientView, its intended functionality is to target a resturants ingredient amount and than decrement or increment the inventory amount. Updating the price per unit would be vital as well. When I click on the hyperlink to that template_name I get the following error message. It is asking for a primary key or a slug. I would think the primary key would involve the values that I am updating.

So the first thing that I did was check Django For Beginners and it said that I should create a template and inside that template their is a url tag and inside that url tag there is a post.pk.

From that I guessed that the pk I need to supply is in the template. After reading the documentation it says I need to target the self.object which is being updated. I have targeted fields of ["quantity, “price_per_unit”] in my views.py so where do I post the object? How do I find the primary key value that I need?

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

models.py

from django.db import models
from django.urls import reverse 

# Create your models here.

class Ingredient(models.Model):
    name = models.CharField(max_length = 20)
    quantity = models.FloatField()
    unit = models.CharField()
    price_per_unit = models.FloatField()
# keep in mind that django automatically creates a primarky key column which can be referenced as 
# id or .pk Ingredient.id or Ingreident.pk
# keep in mind that if you do use updateview you do not want to provide update view access to fields that you do not want edited in the column. 
# this could result in users messing up things that they should not be allowed to touch.
    class Meta:
        ordering = ['name']

    def __str__(self): # without the def_str__ method it will not label ingredient by name
        return " " + self.name
    
    def get_absolute_url(self):
        return reverse("updateingredient", kwargs={"pk": self.pk})
    
    

class MenuItem(models.Model):
    name = models.CharField(max_length = 20)
    description = models.CharField(max_length = 200)
    price = models.FloatField()
    # I have set a primary key in hopes of having some way to identfy what has been ordered?
    # id = models.AutoField(primary_key=True) 
    
    def requirements(self): # made for purchases sake and menu.html sake
        requirements = RecipeRequirement.objects.filter(recipe=self)
        return requirements
        # this function will will grab all of the objects in the receipe requirements table
        # and than it will filter what it grabs by the recipe being used and only grab what 
        # ingredients the recipe calls for. 
        # .filter will leave things as a list.  
        # ingredients is a method on the object. 
        # ingredient 

    def __str__(self):
        return self.name

        # go to the Receipe Requirements table.grab all of the recipe requiement data attributes. through .objects method. 
        # using.filter we tell python to only give me the objects when they equal this recipe. 
        # recipe is an attribute in the RecipeRequirement table line 44 see below.
        # when that recipe field is equal to self grab the items that were used in making the recipe. 
        # self is an instance of an object. and that was 
        # when this item is equal to the one listed in the recipe grab this value. 


        # we need to access the ingredient cost and add it up. price per unit by the amount used and add it up.
        

        #find me all of the recipe items you need to make this receipe. 
        #self is an instnace of the object. 
        #django djaffe cake as a menu item with descriptiona nd price. we pass that object in and say give me the recipe requirement
        # is this object. 



class RecipeRequirement(models.Model):
    # a recipe_id will populate with django here
    ingredient = models.ForeignKey(Ingredient,on_delete=models.CASCADE) # the ForeignKey will automatically reference the primary key that Django makes for us.
    recipe = models.ForeignKey(MenuItem,on_delete=models.CASCADE) # the table did not have a concept of which ingredients were tied to what recipe. this line of code associates ingredients with reciepes.
    quantity = models.FloatField()

    def __str__(self):
        return self.recipe.name + " " + self.ingredient.name # you can access values outside of the class to name things. this line of code details the recipe name and ingredient

class Purchases(models.Model):
    # a purchase_id_field will populate with django here
    menu_order = models.ForeignKey(MenuItem,on_delete=models.CASCADE) # this will let us see what menu items were ordered. # without the str method its an object method that you can use for calculations for purchases
    timestamp = models.DateTimeField()

# menu order points to a row on the menu item table 
# menu item is a table with a primary key called id. 
# python will grab the menu item as an object and all of its data.
# menu order is a column in purchases that will have the menu item id in it. 
# django djaffa cake has one id number. and if coffee has an id of two. it will find things by id number. 
# each recipe has an id number of its own. on line 33 of models.py 
# its saying follow those id numbers.


    class Meta:
        verbose_name = "Purchase"


# ask myself what does this table need information for
# what questions am I trying to answer for my boss or for my project?
# when inside of virtual enviornment just run python 
# python manage.py 

views.py

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 field attribute and reverse_lazy are used with updateview. upon successful completion of the viewd django
    # will route the user to the url with the name pattern of ingredientupdate
    success_url = reverse_lazy('ingredientupdate') 
    # fields = we need to input the fields of the columns that the provided model has.

Link to my Github: GitHub - strikeouts27/djangodelights

Error Message:

Traceback (most recent call last):
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/views/generic/base.py", line 104, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/views/generic/base.py", line 143, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/views/generic/edit.py", line 203, in get
    self.object = self.get_object()
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/views/generic/detail.py", line 46, in get_object
    raise AttributeError(

Exception Type: AttributeError at /ingredient/update/
Exception Value: Generic detail view UpdateIngredientView must be called with either an object pk or a slug in the URLconf.

Your url at https://github.com/strikeouts27/djangodelights/blob/main/djangodelights/urls.py#L20 should contain a <int:pk> in path, like what you have at https://github.com/strikeouts27/djangodelights/blob/main/djangodelights/urls.py#L23

So whenever I am doing an update view I need to have the int:pk value tagged at the end because it tells it go grab the primary key?
It seems I have another error, but a new error when I implement the int:pk.

According to the error message it says that the reverse for ‘ingredientupdate’ without arguments is not found. it claims it tried ingredient/update. So that is saying it tried the view with updateingredient and that attempt failed. Where I alter what it looks for is in success_url = reverse_lazy in views.py. So I look at views.py

Here is the line of code that I am talking about changing.

    path('ingredient/update/<int:pk>', views.UpdateIngredientView.as_view(success_url = "/ingredients/"), name='ingredientupdate'),

It was working without int:pk and now that I have added int:pk it does not work so maybe the difference is I have not given it a value needed to work? That or the url may be off?

traceback error message:

Traceback (most recent call last):
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/andrewstribling/Desktop/Programming/projects/django/code/django/djangodelights/inventory/views.py", line 61, in home
    return render(request,'inventory/home.html')
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/shortcuts.py", line 24, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/loader_tags.py", line 157, in render
    return compiled_parent._render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 167, in _render
    return self.nodelist.render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 1005, in render
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 1005, in <listcomp>
    return SafeString("".join([node.render_annotated(context) for node in self]))
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/base.py", line 966, in render_annotated
    return self.render(context)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/template/defaulttags.py", line 471, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/urls/base.py", line 88, in reverse
    return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
  File "/Users/andrewstribling/Library/Python/3.9/lib/python/site-packages/django/urls/resolvers.py", line 828, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'ingredientupdate' with no arguments not found. 1 pattern(s) tried: ['ingredient/update/(?P<pk>[0-9]+)\\Z']

urls.py

# urls.py 
from django.contrib import admin
from django.urls import path, include
# from inventory.views import finance, home, IngredientsView, MenuView, PurchaseView
from inventory import views # with every view imported you need to specify views.viewname as seen in this file in the code below
from django.views.generic.base import TemplateView
from django.http import HttpResponse

urlpatterns = [
    
    path('', views.home, name='default'), # users don't need to see the rocket page anyway. they need to see the home page.
    path('admin/', admin.site.urls),
    path('finance/', views.finance, name='finance'),
    path('home/', views.home, name='home'), #I am attempting to connect the home_view function with the views function.
    path('ingredients/', views.IngredientsView.as_view(), name='ingredients'),
    path('menu/', views.MenuView.as_view(), name='menu'),
    path('purchases/', views.PurchaseView.as_view(), name='purchases'), 
    path('menu/add/',views.MenuAdditionView.as_view(success_url = "/menu/"), name="menuadd"),
    path('ingredients/add/', views.IngredientAdditionView.as_view(success_url = "/ingredients/"), name='ingredientadd'), # if class based view it requires an as_view
    path('ingredient/update/<int:pk>', views.UpdateIngredientView.as_view(success_url = "/ingredients/"), name='ingredientupdate'),
    path('recipe/add/', views.RecipeRequirementAdditionView.as_view(success_url = "/menu/"), name='recipeadd'),
    path('purchases/add/', views.PurchaseAdditionView.as_view(success_url = "/purchases/"), name = 'purchaseadd'),
    path('update/inventory/<int:pk>/', views.IngredientsListUpdateView.as_view(), name='updateinventory'), # update view so the view had to be edited.
    # cannot have conflicting path names or matching names
    # finance is not a classed based view therefore i do not need an as_view
    # error message views.finance() type error means I a. calling the fucntion wrong or I am not supposed to be calling it.
    # It needs to know what it is updating. 
    ]

views.py

from django.shortcuts import render
from django.urls import path, reverse_lazy
from .models import Ingredient, MenuItem, Purchases, RecipeRequirement
from django.views.generic import ListView
# import one at the time write the view for it hook it up in urls.py check if it works than move on to the next one. 
from .forms import MenuAdditionForm, IngredientAdditionForm, UpdateIngredientForm, RecipeAdditionForm # link the views and forms togather on this line
# errors can come from importing on the wrong django.views
from django.views.generic.edit import CreateView, UpdateView
from django.http import HttpResponse

# Create your views here.

def finance(request):
    purchased_items = Purchases.objects.all() # this grabs every row in the purchases table

    total_revenue = 0 
    for item in purchased_items:
        total_revenue = total_revenue + item.menu_order.price #this uses the price of each item to calculate the revenue
    
    print(str(total_revenue))
    total_cost= ingredient_cost_calculate()
    print(str(total_cost) + " this is the total cost calculation")

    total_profit= total_revenue - total_cost
    print(str(total_profit) + "total profit calculation amount")

    return render(request,'inventory/finance.html', {"total_revenue": total_revenue, "total_cost":total_cost, "total_profit": total_profit})    
    # i want the price of the item and the cost of each item.
    # what holds this information? my ingredient model. 
    # it holds the price per unit and the unit.
def ingredient_cost_calculate(): 
    # classes do not store information objects do. 
    # i need the cost per ingredient multiplied by quantity used.
    # I need to than for loop over all of the ingredients in a recipe and than apply the cost per ingredient function or 
    # the same mathematical operation. 
    # classes do not have the data, the objects do.
    # when the customer purchases something an entry is made in the purchases table. 
    # Purchases.objects.all() grabs all of the Purchases data and puts it in a list.
    purchases_objects = Purchases.objects.all() 
    # I need to find all of the ingredients per order. How do I get one order to find the ingredients on. 
    # I need to use a for loop to access each purchase. 
    menu_order_cost = 0 
    for purchase in purchases_objects:
        menu_item_object = purchase.menu_order 
        # recipe requirements is a list of data
        recipe_requirements = RecipeRequirement.objects.filter(recipe=menu_item_object)
        # we iterate over that list with a for loop and access the iteration variable quantity fields. 
        
        for requirement in recipe_requirements: 
            cost_per_ingredient = requirement.quantity * requirement.ingredient.price_per_unit
            menu_order_cost = menu_order_cost + cost_per_ingredient
    return menu_order_cost

    

    # the purchases are listed by names they do hold the ingredient data for each indvidual order. 



def home(request):
    return render(request,'inventory/home.html')

class MenuView(ListView):
    # when we specify the model being used for the template its almost as if we import or give access
    # to the html template the class data for us to use for loops and django code on. 
    model = MenuItem
    template_name = 'inventory/menu.html'

class PurchaseView(ListView):
    model = Purchases
    template_name = 'inventory/purchases.html'

class IngredientsView(ListView):
    model = Ingredient
    template_name = "inventory/ingredients.html"

class IngredientsListUpdateView(ListView):
    model = Ingredient
    template_name = "inventory/ingredients_update.html"
    
    
class MenuAdditionView(CreateView):
    model = MenuItem
    template_name = "inventory/form_template.html"
    form_class = MenuAdditionForm
    # fields = ["name", "description", "price"]

class IngredientAdditionView(CreateView):
    model = Ingredient
    template_name = 'inventory/form_template.html'
    form_class = IngredientAdditionForm

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 field attribute and reverse_lazy are used with updateview. upon successful completion of the viewd django
    # will route the user to the url with the name pattern of ingredientupdate
    success_url = reverse_lazy('ingredientupdate') 
    # fields = we need to input the fields of the columns that the provided model has.

class RecipeRequirementAdditionView(CreateView):
    model = RecipeRequirement
    template_name = 'inventory/form_template.html'
    fields = ["ingredient", "recipe", "quantity"]

class PurchaseAdditionView(CreateView):
    model = Purchases
    template_name = 'inventory/form_template.html'
    fields = ["menu_order", "timestamp"]

# update view will require a <pk> or slug where I specify what I need to update.
# check out the codecademy section.
# https://www.codecademy.com/paths/build-python-web-apps-with-django/tracks/views-in-django/modules/django-writing-more-views/lessons/django-views/exercises/using-primary-keys-in-urls


# create a view based on the forms made.
# create a path to urls.py

form_template.html

{% extends "inventory/base.html" %}
 
{% block content %}
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Submit"/>
</form>
{% endblock %}

According to my models.py I am targeting ingredients_update.html.

We actually need to see the template that you are trying to render here to address this error.

Exception Type: NoReverseMatch at /
Exception Value: Reverse for 'ingredientupdate' with no arguments not found. 1 pattern(s) tried: ['ingredient/update/(?P<pk>[0-9]+)\\Z']

base.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="topnav"> <!-- the green text is talking about paths the white is what is on the page-->
    <a href="{% url 'home' %}">Home</a>
    <a href="{% url 'ingredients' %}">Ingredients</a> <!-- name= connection-->
    <a href="{% url 'menu' %}">Menu</a>
    <a href="{% url 'finance' %}">Finance</a>
    <a href="{% url 'purchases' %}">Purchases</a>
    <a href="{% url 'menuadd' %}">Add Menu</a> <!--utilize name in urls.py -->
    <a href="{% url 'ingredientadd' %}">Add Ingredient</a>
    <a href="{% url 'recipeadd' %}">Add Receipe</a>
    <a href="{% url 'purchaseadd' %}">Add Purchase</a>
    <a href="{% url 'ingredientupdate'%}">Ingredient Update</a> <!-- I need a reverse-->
  </div>

  {% block content %}
  {% endblock %}
</body>
</html>

The template that my model is targeting has been edited onto the prior post.
So the error message is saying my reverse is not working.

You have:

However, that url is defined as:

You need to supply the value that will be used in that portion of the url.

Go back and look at work you’ve done before for urls with parameters, and look at how they’re referenced within the templates.

I will go look at the django tutorial polls app and my current project ASAP. thank you Ken!

Okay so looking at my past work in the templates there is a url tag that grabs the primary key of the thing it wants to update. I want to update the Ingredient model. So it stands to reason that I want to target the Ingredient models primary key.

Looking at my past work a url tag is utilized. First the a href= is established, than we reference which url we want to have the button target, followed by the model that we want to target and than put down a .pk to grab that value. I would think that would supply it the primary key it needs!

However I have base.html extending a hyperlink on its own. I don’t want a second url link made. I need the url link that the base.html is creating to be able to do the same thing the url tag did.

In my template I placed Ingredient.pk which I believe is telling Django to grab the Ingredients models primary key.

No Reverse Match Error:

form_template.html

<p><a href="{% url 'ingredientupdate' Ingredient.pk %}">Update_Ingredient_Button</p>

GitHub link for project:

I want to be able to go in and update each of the ingredient names quantitys and price per unit.

Im still stuck. Am I supposed to be using url tags?

I’m sorry, I’m not following you at this point.

Your original post concerned the url tag in a template. I don’t understand how your most recent two posts relate to the original topic, or what the question is that you’re trying to ask now.

I am recieveing the no reverse match error. This error is saying that i have not supplied the information necessary to get the view and url to work properly to display the page. I am trying to supply that value which in this case is an int:pk that my url has. I was told earlier that I needed to supply this value.

My end goal is to be able to select the ingredients updateview page and have that page load. On that page there will be a different ingredients. I want admins to be able to update the ingredient quantity and price per unit. But I cannot do that if the page will not load.

You told me to go back and look at how I handeled urls with parameters. It seems that my templates had a url tag that had a primary key value passed in. I passed in Ingredients.pk but that did not work.

Ok, so please post the code that you tried, along with your corrected template.

{% extends "inventory/base.html" %}
{% block content %}
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Submit"/>
</form>
{% url 'ingredientupdate' Ingredient.pk %}
{% endblock %}

I passed in ingredient.pk but that did not fix the issue.

What about the view that renders that template?

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 field attribute and reverse_lazy are used with updateview. upon successful completion of the viewd django
    # will route the user to the url with the name pattern of ingredientupdate
    success_url = reverse_lazy('ingredientupdate') 
    # fields = we need to input the fields of the columns that the provided model has.

Good.

You’re using the default get_context_data method which means the object being updated is added to the context for the template under two names, object and the lowercase version of the model name - which in this case is ingredient. However, in your template, you’re trying to access it as Ingredient, which isn’t the same thing.

Now, you’ve also got a similar issue with your success_url attribute. Two things there:

  • You’re trying to reverse the same url, which means your reverse_lazy call also needs to include a parameter.
  • You can’t use a dynamically defined function for the success_url attribute. You need to override the get_success_url method instead.

I want to ask questions so that I can better understand going forward.

I have a url which has a name = ‘ingredientupdate’ which means that it is referenced throught my program as ingredientupdate and when referenced it knows to use that url pathway.

I have an updateingredient view that has updateview subclassed. Its mission is to update the ingredients on the web page. It also tells django to load the template that is assigned to it which is inventory/form_template.html.

When I click on the hyperlink Django tries to load the page but it gave an error saying IN eeded to provide an object pk or slug in my url.

Question 1: why does it need a pk or a slug to begin with?

I was told to add int:pk to my url. I did so because the error message told me to. When I did so, django raised an error saying that I needed to supply an int:pk parameter. I can only guess that because it is an updateview it needs to have some more information about what to update.

I was told by you that my template logic was wrong. Based on the error message, I need to supply an int or a pk. I input Ingredients.pk but this was wrong.

It seems that the template has a get_context_data method which updates the context. The context is a dictionary that holds information about variables. It seems that because get_context_data method access context and has by template be named in it under two different entries.

object and the lowercase version of my model name ingredient.

So I need to put in ingredient.pk when I do so I get attribute error.

Question 2: it seems I need to re research context and understand get_context_data better I will research that ASAP.

my success_url attribute has issues as well. Reverse is a url finder that helps django find which url to use. By reversing the same url my reverse_lazy needs to have a parameter.->

Question 3: why does reverse_lazy need a paraemter.

Continuning on

You can’t use a dynamically defined function for the success_url attribute. You need to override the get_success_url method instead.

I will look that method up and if I have questions will reach out.

That is not accurate.

You have a url named ingredientupdate - that is correct. However, referencing the name itself doesn’t do anything. The reverse (and reverse_lazy) functions look up that name in the defined urls structure to find the last url defined with that name.

This is not accurate. Your view is named UpdateIngredientView and it subclasses UpdateView. Case is significant in Python.

The Django-terminology here is that the view renders the template, not merely load it.

What hyperlink? On which page? The page being rendered by UpdateIngredientView or a different view?

Cannot answer without clarification to the previous item.

Yes, an UpdateView updates an instance of an object. The view needs to know which instance to update.

Correct, you’ve got ingredients capitalized, which as I pointed out in my previous response, is incorrect.

Diagnosing any further issues related to it requires the current code and template be posted, along with the current error. This statement doesn’t make it clear if you’re encountering the same error or a different one somewhere else.

reverse_lazy itself doesn’t need a parameter. Using reverse_lazy on a url that requires a parameter means you need to supply the parameter to generate the url.

Thank you for your corrections.

I am referring to the far right hyperlink on the image here. I believe this is using the ‘ingredientupdate’ url.

base.html

  <a href="{% url 'ingredientupdate'%}">Ingredient Update</a> <!-- I need a reverse-->

views.py

 path('ingredient/update/', views.UpdateIngredientView.as_view(success_url = "/ingredients/"), name='ingredientupdate'),

Okay I am working on the success_url attribute part of the problem and it says I need to include a parameter for reverse_lazy. Per the documentation reverse_lazy is used when I want to use a url reverse find before my url conf is loaded.

Question: Why is loading my url conf a factor? Does it update values as it does so and make the search fail? What exactly does the url conf do that makes it where reverse would not work on its own?

Per what you said if I have a reverse_lazy call on a url that requires a parameter, than I need to figure out what that parameter is and palce it somewhere. Would I be placing that in the template page as well? What is a good question to ask myself to figure out what parameter I need to pass in?

You say that really I shouldn’t be using functions at all. That I need to override the get_success_url method instead. I am assuming that I would be putting the get success_url in my view function.

I have some serious Youtube and Django Documentation reading to do.

The url definition you supplied here:

Doesn’t logically make any sense.

An UpdateView (or subclass thereof) exists to update an instance of an object. You need to specify for the view which instance is going to be updated. In 99.999% of the cases, this is done by supplying the pk of the instance as a parameter in the url.

It’s a “sequence of events” issue. If you’ve got code that is trying to reverse a url before the urls are loaded, it’s going to fail. The reverse_lazy method allows Django to defer the retrieval of the url until such time as it is available.

In all cases here, for this discussion, you can consider reverse and reverse_lazy to perform identical functions. There’s no difference of any importance between the two that you need to worry about at this point in time.

Which instance of Ingredient am I trying to update?

I’ve never said that. That’s a mischaracterization of something - without context, I’m not sure what.

Yes, the url you’re trying to reverse needs to be reversed in a get_success_url method, not as being assigned to the success_url attribute of the class.

No, you override get_success_url in Class-Based Views (CBV). You would call reverse directly in a function-based view.