My restaurant page has a menu add page where I add a menu item to the list of menu items. Now when I made this page my tutor told me that it would be wise to utilize this code but we created menu items utilizing the admin page. Fast forward a few months where I am on my own and I am trying to click the hyperlink and it will not load. I am getting a no reverse error message because django says that form_tempalte.html cannot find an objects primary key. I say okay, well than all I need to do is create an instance of the class and Django will produce a primary key automatically and my code will work because there will be a primary key and I can at the very least see the menu add page.
What did I try and what am I expecting?
However when I try to create an instance of the menu add like so
class MenuAdditionView(CreateView):
model = MenuItem
template_name = "inventory/form_template.html"
form_class = MenuAdditionForm
# fields = ["name", "description", "price"]
mongo_db_energy_drink = MenuAdditionView()
I get this error message.
Error Message:
ImportError: attempted relative import with no known parent package
(project_env) andrewstribling@Andrews-MBP djangodelights %
So I asked Chat GPT and it explained to me that creating objects outside of view functions does not work in Django. (Darn) It says that I need to create an instance of it within a Django view function, which is then linked to a specific url pattern.
example given:
# views.py
from django.views.generic.edit import CreateView
from .forms import MenuAdditionForm
from .models import MenuItem
class MenuAdditionView(CreateView):
model = MenuItem
form_class = MenuAdditionForm
template_name = "inventory/form_template.html"
success_url = "/menu/" # or use reverse_lazy here
chat gpt urls.py file
# urls.py
from django.urls import path
from . import views
urlpatterns = [
# Other URL patterns...
path('menu/add/', views.MenuAdditionView.as_view(), name="menuadd"),
# Other URL patterns...
]
my urls.py file
# 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.
]
But the error persists it reads:
Traceback:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/menu/add/
Django Version: 4.2.6
Python Version: 3.11.5
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'inventory.apps.InventoryConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /Users/andrewstribling/dev/djangodelights/inventory/templates/inventory/form_template.html, error at line 8
Reverse for 'ingredientupdate' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ingredient/update/(?P<pk>[0-9]+)\\Z']
1 : {% extends "inventory/base.html" %}
2 : {% block content %}
3 : <form method="POST">
4 : {% csrf_token %}
5 : {{ form.as_p }}
6 : <input type="submit" value="Submit"/>
7 : </form>
8 : {% url 'ingredientupdate' pk=object.pk%}
9 : {% endblock %}
10 :
Traceback (most recent call last):
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/core/handlers/base.py", line 220, in _get_response
response = response.render()
^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/response.py", line 114, in render
self.content = self.rendered_content
^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/response.py", line 92, in rendered_content
return template.render(context, self._request)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 175, in render
return self._render(context)
^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/loader_tags.py", line 157, in render
return compiled_parent._render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 167, in _render
return self.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/loader_tags.py", line 63, in render
result = block.nodelist.render(context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 1005, in render
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 1005, in <listcomp>
return SafeString("".join([node.render_annotated(context) for node in self]))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/template/base.py", line 966, in render_annotated
return self.render(context)
^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/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/dev/djangodelights/project_env/lib/python3.11/site-packages/django/urls/base.py", line 88, in reverse
return resolver._reverse_with_prefix(view, prefix, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/andrewstribling/dev/djangodelights/project_env/lib/python3.11/site-packages/django/urls/resolvers.py", line 828, in _reverse_with_prefix
raise NoReverseMatch(msg)
^^^^^^^^^^^^^^^^^^^^^^^^^
Exception Type: NoReverseMatch at /menu/add/
Exception Value: Reverse for 'ingredientupdate' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['ingredient/update/(?P<pk>[0-9]+)\\Z']
My question is, how do I create an instance so that a primary key can be created and I can move on with my project? I want to create menu object but it seems that this code is creating an ingredient object. How can I get a menu object created?