NoReverseMatch Django Project - django

I want to create the products through the customer's profile, so that the customer's name is attached to the form when creating the product that is related to it. But when I try to enter the user profiles from the dashboard it throws this error
urls.py
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name="products"),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>', views.createOrder, name='create_order'),
path('update_order/<str:pk>', views.updateOrder, name='update_order'),
path('delete_order/<str:pk>', views.deleteOrder, name='delete_order'),
path('create_customer/', views.createCustomer, name='create_customer'),
]
views.py
Here I focus on the "create Order" function passing the customer's primary key and using "initial" to append the customer's name to the form
def home(request):
orders_value = Order.objects.all()
customer_value = Customer.objects.all()
total_orders_value = orders_value.count()
total_customers_value = customer_value.count()
pending_value = orders_value.filter(status='Pending').count()
delivered_value = orders_value.filter(status='Delivered').count()
context = {'orders_key': orders_value, 'customer_key': customer_value,
'total_orders_key':total_orders_value, 'pending_key': pending_value,
'delivered_key': delivered_value}
return render (request, 'accounts/dashboard.html', context)
def products(request):
products_value = Product.objects.all()
return render (request, 'accounts/products.html', {'products_key': products_value})
def customer(request, pk_test):
customer_value = Customer.objects.get(id=pk_test)
orders_value = customer_value.order_set.all()
orders_value_count = orders_value.count()
context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count}
return render (request, 'accounts/customer.html', context)
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form_value = OrderForm(initial={'customer':customer})
if request.method == 'POST':
form_value = OrderForm(request.POST)
if form_value.is_valid:
form_value.save()
return redirect('/')
context = {'form_key':form_value}
return render(request, 'accounts/order_form.html', context)
def updateOrder(request, pk):
order = Order.objects.get(id=pk)
form_value = OrderForm(instance=order)
if request.method == 'POST':
form_value = OrderForm(request.POST, instance=order)
if form_value.is_valid:
form_value.save()
return redirect('/')
context = {'form_key':form_value}
return render(request, 'accounts/order_form.html', context)
def deleteOrder(request, pk):
order = Order.objects.get(id=pk)
if request.method == 'POST':
order.delete()
return redirect('/')
context={'item':order}
return render (request, 'accounts/delete.html', context)
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer_key.email}}</p>
<p>Phone: {{customer_key.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Orders</h5>
<hr>
<h1 style="text-align: center;padding: 10px">{{orders_key_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="get">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Orderd</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders_key %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.data_created}}</td>
<td>{{order.status}}</td>
<td>{{order.product}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
dashboard.html
{% extends 'accounts/main.html' %}
{% block content %}
{% include 'accounts/status.html' %}
<br>
<div class="row">
<div class="col-md-5">
<h5>CUSTOMERS:</h5>
<hr>
<div class="card card-body">
<a class="btn btn-primary btn-sm btn-block" href="{% url 'create_customer' %}">Create Customer</a>
<table class="table table-sm">
<tr>
<th></th>
<th>Customer</th>
<th>Phone</th>
</tr>
{% for customer in customer_key %}
<tr>
<th><a class="btn btn-sm btn-info" href="{% url 'customer' customer.id %}">View</a></th>
<td>{{customer.name}}</td>
<td>{{customer.phone}}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
<div class="col-md-7">
<h5>LAST 5 ORDERS</h5>
<hr>
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Date Orderd</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for orders in orders_key %}
<tr>
<td>{{orders.product}}</td>
<td>{{orders.data_created}}</td>
<td>{{orders.status}}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'update_order' orders.id %}">Update</a></td>
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' orders.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
This is the error that throws me
NoReverseMatch at /customer/1/
Error during template rendering
Reverse for 'create_order' with arguments '('',)' not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)$']
Maybe i wrote some wrong in "customer.html" but i dont know where and i cant find the error... I need help, please

inside your template customer.html
change this(why ? because inside your context = {'customer_key':customer_value, 'orders_key': orders_value, 'orders_key_count': orders_value_count} that refers to this template there is no key called 'customer' and you tried to access again his id that is not correct)
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
to (if you look your context you have a customer_key that is from your Customer model to get his id you can just use customer_key.pk)
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer_key.pk %}">Place Order</a>
there is some mistake inside your urls.py(pk is an integer so instead of str(string) you should use int(integer))
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name="products"),
path('customer/<int:pk_test>/', views.customer, name="customer"),
path('create_order/<int:pk>', views.createOrder, name='create_order'),
path('update_order/<int:pk>', views.updateOrder, name='update_order'),
path('delete_order/<int:pk>', views.deleteOrder, name='delete_order'),
path('create_customer/', views.createCustomer, name='create_customer'),
]

Related

Why am I getting a No Reverse Match error?

I'm trying to add delete functionality to my Django project, and I seem to be stuck in a loop whenever I try to access my health_hub_history page.
I keep getting the below error, which I know is to do with my urls.py setup, but I have commented it out- so I really don't know why I'm still getting the error!
Error message:
NoReverseMatch at /MyHealth/history
Reverse for 'delete_entry' not found. 'delete_entry' is not a valid view function or pattern name.
Views.py:
from django.shortcuts import render, get_object_or_404, redirect
from django.views import View, generic
from .models import HealthStats
from .forms import StatUpdateForm
def home(request):
return render(request, 'home.html')
def health_hub(request):
latest = HealthStats.objects.filter(user=request.user).latest('date')
context = {
"user": latest.user,
"weight": latest.weight,
"date": latest.date,
"run_distance": latest.run_distance,
"run_time": latest.run_time,
}
return render(request, 'health_hub.html', context)
def health_history(request):
serialized_stats = []
for stats in HealthStats.objects.filter(user=request.user):
serialized_stats.append({
"user": stats.user,
"weight": stats.weight,
"date": stats.date,
"run_distance": stats.run_distance,
"run_time": stats.run_time,
})
context = {
"stats": serialized_stats
}
return render(request, 'health_hub_history.html', context)
class UpdateHealth(View):
def get(self, request, *args, **kwargs):
stats = HealthStats
update_form = StatUpdateForm
context = {
'stats': stats,
'update_form': update_form,
'user': stats.user,
'weight': stats.weight,
'date': stats.date,
}
return render(request, 'health_hub_update.html', context)
def post(self, request, *args, **kwargs):
stats = HealthStats
update_form = StatUpdateForm(data=request.POST)
context = {
'stats': stats,
'update_form': update_form,
'user': stats.user,
'weight': stats.weight,
'date': stats.date,
'run time': stats.run_time,
'run distance': stats.run_distance
}
if update_form.is_valid():
update_form.save()
return render(request, 'health_hub_update.html', context)
# def delete_entry(request, entry_id):
# entry = get_object_or_404(HealthStats, id=entry_id)
# entry.delete()
# return redirect("health_hub_history")
urls.py:
from django.urls import path
from django.contrib.staticfiles.storage import staticfiles_storage
from django.views.generic.base import RedirectView
from . import views
app_name = 'HealthHub'
urlpatterns = [
path('', views.home, name='home'),
path('MyHealth/', views.health_hub, name='health_hub'),
path('MyHealth/update', views.UpdateHealth.as_view(), name='health_hub_update'),
path('MyHealth/history', views.health_history, name='health_hub_history'),
path('favicon.ico', RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))),
# path('MyHealth/delete_entry/<id>', views.delete_entry, name='delete_entry'),
]
health_hub.html (button from which the error occurs):
<a href="{% url 'HealthHub:health_hub_history' %}"><button class="btn btn-primary btn-lg">View my Health
History</button></a>
health_hub_history.html:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 text-center">
<h1>My Health History</h1>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<table class="table table-striped table-hover table-bordered">
<tr>
<td>User:</td>
<td>Weight (lbs):</td>
<td>Date:</td>
<td>Run Distance (km):</td>
<td>Run Time (HH:MM:SS):</td>
<td>Action</td>
</tr>
{% for stat in stats %}
<tr>
<td>{{ stat.user }}</td>
<td>{{ stat.weight }} </td>
<td>{{ stat.date }}</td>
<td>{{ stat.run_distance }}</td>
<td>{{ stat.run_time }}</td>
<!-- Button trigger modal -->
<td>
<button type="button" class="btn btn-danger" data-bs-toggle="modal"
data-bs-target="#staticBackdrop">
Delete
</button>
</td>
<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false"
tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Are you sure you want to delete
this entry?</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">
If you just need to amend something, try the edit button.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Cancel</button>
<!-- <a href="{% url 'delete_entry' entry_id %}"><button class="btn btn-danger">I'm -->
sure</button></a>
</div>
</div>
</div>
</div>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock content %}
I don't understand how it can all be commented out, but it's still trying to access the 'delete_entry' view?
Django does not ignore HTML comments, you need to use a special tag :
{% comment "Optional note" %}
<a href="{% url 'delete_entry' entry_id %}"><button class="btn btn-danger">
{% endcomment %}
https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#comment

Django Handling Multiple Forms

I'm currently working on To-Do App using Django.
I got stucked in handling two different forms in single html file and each form has separate function in views. I have two models Todo and Task.
The task items should be placed under to-do item. In short To-Do is a Category and the task's are its sub-category. The data is not getting saved and displayed in the Web.
I have two forms in main.html one is for to-do item and other one is for task item. Each have two different function in views.py which are home and add_todo function respectively.
In form-2 which is for task item built using bootstrap Modal. The form action provided to add_todo function in views.py.
models.py
class Todo(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
title = models.CharField(max_length=200)
user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Task(models.Model):
heading = models.CharField(max_length=100)
todo = models.ForeignKey(Todo, on_delete=models.CASCADE, related_name='tasks')
date_created = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.heading
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, Http404, HttpResponseNotFound, JsonResponse, HttpResponseRedirect
from .models import Todo, Task
from .forms import *
from django.utils import timezone
from django.contrib.auth.forms import UserCreationForm
from django.views.decorators.csrf import csrf_protect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.views.generic import View
from django.contrib.auth.models import User
from django.core.paginator import Paginator
def register(request):
form = userRegisterForm()
if request.method == 'POST':
form = userRegisterForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
return redirect('login')
else:
form = userRegisterForm()
context = {'form': form}
return render(request, 'todo/register.html', context)
def logoutUser(request):
logout(request)
return redirect('login')
#login_required(login_url='login')
def home(request):
todo_form = TodoForm()
task_form = TaskForm()
current = timezone.now()
todo_items_upcoming = Todo.objects.filter(user_id=request.user, completed=False).order_by('-date_created')
todo_items_completed = Todo.objects.filter(user_id=request.user, completed=True).order_by('-date_created')
pagi1 = Paginator(todo_items_upcoming, 4)
pagi2 = Paginator(todo_items_completed, 4)
page_num = request.GET.get('upcoming', 1)
page_num2 = request.GET.get('completed', 1)
page_obj = pagi1.get_page(page_num)
page_obj2 = pagi2.get_page(page_num2)
if request.method == "POST":
todo_form1 = TodoForm(request.POST)
if todo_form1.is_valid():
data = todo_form1.cleaned_data.get('title')
obj = Todo.objects.create(date_created=current, title=data, user_id=request.user)
return redirect('/')
context = {'todo_form': todo_form, 'page_obj': page_obj, 'page_obj2': page_obj2,
'pagi1': pagi1, 'pagi2': pagi2, 'page_num2': int(page_num2), 'page_num': int(page_num), 'task_form':task_form}
return render(request, 'todo/main.html', context)
#login_required(login_url='login')
def update_todo(request, pk):
try:
obj = Todo.objects.get(id=pk, user_id=request.user)
upform = TodoForm(instance=obj)
if request.method == 'POST':
upform = TodoForm(request.POST, instance=obj)
if upform.is_valid():
upform.save()
return redirect('/')
except Exception as err:
try:
obj = Task.objects.get(id=pk, user=request.user)
upform = TaskForm(instance=obj)
if request.method == 'POST':
upform = TaskForm(request.POST, instance=obj)
if upform.is_valid():
upform.save()
return redirect('/')
except Exception as err:
raise Http404(err)
context = {'upform': upform}
return render(request, 'todo/update_task.html', context)
#login_required(login_url='login')
def add_todo(request, pk):
try:
obj = Todo.objects.get(id=pk, user_id=request.user)
except Exception as e:
raise Http404(e)
if request.method == 'POST':
t_form = TaskForm(request.POST)
if t_form.is_valid():
data = t_form.cleaned_data.get('heading')
Task.objects.create(user=request.user, heading=data, todo=obj, date_created=timezone.now())
return redirect('/')
else:
t_form = TaskForm()
context = {'t_form':t_form}
return render(request, 'todo/main.html', context)
#login_required(login_url='login')
def delete_todo(request, pk):
try:
obj = Todo.objects.get(id=pk, user_id=request.user)
except Exception as err:
try:
obj = Task.objects.get(id=pk, user=request.user)
except Exception as err:
raise Http404(err)
obj.delete()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
#login_required(login_url='login')
def completed_todo(request, pk):
try:
obj = Todo.objects.get(id=pk, user_id=request.user)
except Exception as err:
try:
obj = Task.objects.get(id=pk, user=request.user)
except Exception as err:
raise Http404(err)
obj.completed = True
obj.save()
# return redirect('/')
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
main.html
{% extends 'todo/index.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="center-column">
<h5 class="card-title">Create your List</h5>
#form-1
<form action="" method="POST">
{% csrf_token %}
<div class="input-group-append">
{{ todo_form.title }}
<button type="submit" class="form-control btn btn-primary mb-3 mr-sm-2" id="addItem">
Add Items
</button>
</div>
</form>
</div>
<div class="row">
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h4 class="card-title">Upcoming Items</h4>
<hr/>
<ul class="list-group" id="upcomingItems">
{% for i in page_obj %}
<li class="list-group-item list-group-item-primary mb-1" id="upcomingItem">
{{ i.title }}
<div class="float-right">
<button type="submit" class="btn btn-sm btn-danger ml-1 mt-1 mr-1 mb-1">
❌
</button>
</div>
<div class="float-right">
<button type="submit" class="btn btn-sm btn-success ml-1 mt-1 mr-1 mb-1" id="update_btn">
Update
</button>
</div>
<div class="float-right">
<button type="submit" class="btn btn-sm btn-dark ml-1 mt-1 mr-1 mb-1" id="completed_btn">
Completed
</button>
</div>
<div class="float-right">
<!-- Button trigger modal -->
<button type="button" class="btn btn-sm btn-primary ml-1 mt-1 mr-1 mb-1" data-toggle="modal" data-target="#staticBackdrop">
Add
</button>
<!-- Modal -->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Add New Task</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#form-2
<form action="{% url 'home' %}" method="POST">
{% csrf_token %}
<div class="card">
{{ task_form.heading }}
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit">Submit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% for j in i.tasks.all %}
{% if i.tasks.all %}
<div class="card mt-4">
<ul class="list-group">
<li class="list-group-item list-group-item-danger" id="upcomingItem">
{{ j.heading }}
<div class="float-right">
<button type="submit" class="btn btn-sm btn-danger ml-1 mt-1 mr-1 mb-1">
❌
</button>
</div>
<div class="float-right">
<button type="submit" class="btn btn-sm btn-dark ml-1 mt-1 mr-1 mb-1" id="completed_btn">
Completed
</button>
</div>
</li>
</ul>
</div>
{% endif %}
{% endfor %}
</li>
{% endfor %}
</ul>
<hr/>
<ul class="pagination justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item {% if page_obj.page_number == page_num %} active {% endif %}">
<a class="page-link" href="?upcoming={{ page_obj.previous_page_number }}&completed={{ page_num2 }}">&laquo</a>
</li>
{% endif %}
{% for i in pagi1.page_range %}
<li class="page-item {% if i == page_num %} active {% endif %}">
<a class="page-link" href="?upcoming={{ i }}&completed={{ page_num2 }}">{{ i }}</a>
</li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item {% if page_obj.page_number == page_num %} active {% endif %}">
<a class="page-link" href="?upcoming={{ page_obj.next_page_number }}&completed={{ page_num2 }}">&raquo</a>
</li>
{% endif %}
</ul>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="card">
<div class="card-body">
<h4 class="card-title">Completed Items</h4>
<hr/>
<ul class="list-group">
{% for i in page_obj2 %}
{% if not i.tasks.all %}
<li class="list-group-item list-group-item-primary mb-1" id="upcomingItem">
{{ i.title }}
<div class="float-right">
<button type="submit" class="btn btn-sm btn-danger mt-1 mb-1">
❌
</button>
</div>
</li>
{% else %}
{% for j in i.tasks.all %}
<li class="list-group-item list-group-item-primary mb-1" id="upcomingItem">
{{ i.title }}
<div class="float-right">
<button type="submit" class="btn btn-sm btn-danger mt-1 mb-1">
❌
</button>
</div>
<div class="card mt-4">
<ul class="list-group">
<li class="list-group-item list-group-item-danger">
{{ j.heading }}
<div class="float-right">
<button type="submit" class="btn btn-sm btn-danger">
❌
</button>
</div>
</li>
</ul>
</div>
</li>
{% endfor %}
{% endif %}
{% endfor %}
</ul>
<hr/>
<ul class="pagination justify-content-center">
{% if page_obj2.has_previous %}
<li class="page-item {% if page_obj2.page_number == page_num %} active {% endif %}">
<a class="page-link" href="?completed={{ page_obj2.previous_page_number }}&upcoming={{ page_num }}">&laquo</a>
</li>
{% endif %}
{% for i in pagi2.page_range %}
<li class="page-item {% if i == page_num2 %} active {% endif %}">
<a class="page-link" href="?completed={{ i }}&upcoming={{ page_num }}">{{ i }}</a>
</li>
{% endfor %}
{% if page_obj2.has_next %}
<li class="page-item {% if page_obj2.page_number == page_num %} active {% endif %}">
<a class="page-link" href="?completed={{ page_obj2.next_page_number }}&upcoming={{ page_num }}">&raquo</a>
</li>
{% endif %}
</ul>
</div>
</div>
</div>
</div>
{% endblock %}
forms.py
class TodoForm(forms.ModelForm):
class Meta:
model = Todo
fields = ['title', 'completed']
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ['heading', 'todo', 'completed']
class userRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email','password1','password2']
urls.py
urlpatterns = [
path('', views.home, name='home'),
path('update_todo/<int:pk>/', views.update_todo, name='update_todo'),
path('completed/<int:pk>/', views.completed_todo, name="completed_todo"),
path('delete_todo/<int:pk>/', views.delete_todo, name='delete_todo'),
path('add_todo/<int:pk>/', views.add_todo, name='addTodo'),
path('register/', views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='todo/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='todo/logout.html'), name='logout'),
]
When I click Add button and type something and click enter, the data was not saved in the DB so that I'm unable to see the tasks data.
Image-1
Task form Popup modal using bootstrap for adding task items under a todo.
Image-2
Whenever I add task items for other todo items, those task items are getting dtored to 1t todo items not to their corresponding todo items. I have added two task items on Maths Todo items but those Maths-1 and Maths-2 was created under 1st todo items.
Simple way is
action = "{%url 'link_name' %}"
You can specify the function path name in the form Action.
The changes I have made are in add_todo function and bootstrap modal form.
views.py ad_todo function
def add_todo(request, pk):
obj = Todo.objects.get(id=pk, user_id=request.user)
if request.method == 'POST':
if request.POST.get('heading'):
data = Task()
data.heading = request.POST.get('heading')
data.todo = obj
data.user = request.user
data.save()
return redirect('/')
In main.html file - form-2 which is a bootstrap Modal form for adding task items.
<div class="float-right">
<!-- Button trigger modal -->
<button type="button" class="btn btn-sm btn-primary ml-1 mt-1 mr-1 mb-1">
<a href="{% url 'addTodo' i.id %}" data-toggle="modal" data-target="#staticBackdrop">
Add
</a>
</button>
<!--Modal -->
<div class="modal fade" id="staticBackdrop" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Add New Task</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{% url 'addTodo' i.id %}" method="POST">
{% csrf_token %}
<div class="card">
{{ task_form.heading }}
</div>
<div class="modal-footer">
<button class="btn btn-success" type="submit">Submit</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>

I am using django for a project and i got this error

I am doing a project in Django and i got this error.How is this occurs?
NoReverseMatch at /
Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$']
urls.py
from django.urls import path
from accounts import views
urlpatterns = [
path('',views.home, name="home"),
path('product/',views.products, name="product"),
path('customer/<str:pkid>/',views.customer, name="customer"),
path('create_order/<str:pk>/',views.createOrder, name="create_order"),
path('update_order/<str:pk>/',views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/',views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
customer = Customer.objects.get(id=pk)
form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
form = OrderForm(request.POST)
if form.is_valid:
form.save()
return redirect('/')
context = {'form':form}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" name="Submit">
</form>
{% endblock %}
customer.html`
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row" style="margin: auto;">
<div class="col-md">
<div class="card card-body">
<h5>Customer:{{customer.name}}</h5>
<hr>
Update Customer
Place Order
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Orders</h5>
<hr>
<h1 style="text-align:center;padding:10px">{{total_orders}}</h1>
</div>
</div>
</div>
<br>
<div class="row" style="margin: auto;">
<div class="col">
<div class="card card-body">
<form method="get">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row" style="margin: auto;">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product.name}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-sm btn-warning" href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Remove</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.
In your HTML write action=" {%url 'create_order' order.id%}"

Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P<pk>[^/]+)/$']

I'm getting this error when I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
but there is no such error when path is..
path('create_order', views.createOrder, name="create_order"),
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order , fields=('product','status'), extra=9)
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(), instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('printing post', request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'formset': formset}
#return redirect('accounts/order_form.html', context)
return render(request, 'accounts/order_form.html', context)
i also have tried redirect, that's not working the problem is with urls.py.
customer.html
{% extends 'accounts/main.html' %}
{% block content %}
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<h5>Customer:</h5>
<hr>
<a class="btn btn-outline-info btn-sm btn-block" href="">Update Customer</a>
<a class="btn btn-outline-info btn-sm btn-block" href="{% url 'create_order' customer.id %}">Place Order</a>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Contact Information</h5>
<hr>
<p>Email: {{customer.email}}</p>
<p>Phone: {{customer.phone}}</p>
</div>
</div>
<div class="col-md">
<div class="card card-body">
<h5>Total Order</h5>
<hr>
<h1 style="text-align: center;padding: 10px;">{{order_count}}</h1>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col">
<div class="card card-body">
<form method="POST">
<button class="btn btn-primary" type="submit">Search</button>
</form>
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-md">
<div class="card card-body">
<table class="table table-sm">
<tr>
<th>Product</th>
<th>Category</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.product}}</td>
<td>{{order.product.category}}</td>
<td>{{order.date_created}}</td>
<td>{{order.status}}</td>
<td><a class="btn btn-outline-info btn-md " href="{% url 'update_order' order.id %}">Update</a></td>
<td><a class="btn btn-outline-danger btn-md " href="{% url 'delete_order' order.id %}">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
models.py
class Customer(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
phone = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.name
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{formset.managment_form}} <!-- to remove the managmentForm data missing or has been tempered wiith , error -->
{% for form in formset %}
{{formset}} <!--in context of views.py -->
<hr>
{% endfor %}
<input class="btn btn-outline-success btn-md" type="submit" name="submit">
</form>
</div>
</div>
</div>
{% endblock %}
I have added the templates , and thanks to all but I think the only problem is with urls.py , because if I use
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
instead of
path('create_order', views.createOrder, name="create_order"),
then I get error, otherwise there is no such error for the above path.
I finally got the error.
So, error was here
the href which we have used id {% url 'create_order' customer.id %}
and this is in customer.html ,so the customer.id will get value provided by the views.customer
but if you see in your view.customer,
context = {'customers':customers,'orders': orders,'orders_count': orders_count}
because we followed a tutorial video, that guy did some changes which we didn't because it isn't shown in the video.
the changes he did was that
he changed 'customers' to 'customer' and now context of customer.html is good
because now it knows what the hell is customer.id
i know where the problem is
in the dashboard.html you should delete the line includes {% url 'create_order' %}
I don't know what is the problem but just replaced the file urls.py from GitHub with the same context and it's not showing that error.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('products/', views.products, name='products'),
path('customer/<str:pk_test>/', views.customer, name="customer"),
path('create_order/<str:pk>/', views.createOrder, name="create_order"),
path('update_order/<str:pk>/', views.updateOrder, name="update_order"),
path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"),
]
views.py
from django.forms import inlineformset_factory
def createOrder(request, pk):
OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status'), extra=10 )
customer = Customer.objects.get(id=pk)
formset = OrderFormSet(queryset=Order.objects.none(),instance=customer)
#form = OrderForm(initial={'customer':customer})
if request.method == 'POST':
#print('Printing POST:', request.POST)
#form = OrderForm(request.POST)
formset = OrderFormSet(request.POST, instance=customer)
if formset.is_valid():
formset.save()
return redirect('/')
context = {'form':formset}
return render(request, 'accounts/order_form.html', context)
order_form.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<div class="row">
<div class="col-md-6">
<div class="card card-body">
<form action="" method="POST">
{% csrf_token %}
{{ form.management_form }}
{% for field in form %}
{{field}}
<hr>
{% endfor %}
<input type="submit" name="Submit">
</form>
</div>
</div>
</div>
{% endblock %}
Again I don't know why it was showing this error and where was the problem but just relapced it with the same code from GitHub and it worked.if someone know how it worked, that will be really helpful in near future.
in dashboard you should remove the line with create order
cause there is use of create_order url without id so there's an error

Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$']

I am a beginner in Django and now i am developing a blogging application. At the article editing section i got stucked and I dont know why its showing this error. Searched a lot and cant find an answer
NoReverseMatch at /articles/edit/2/
Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['articles/edit/(?P<pk>[0-9]+)/$']
edit_articles section in
views.py
#login_required(login_url="/accounts/login/")
def edit_articles(request, pk):
article = get_object_or_404(Article, id=pk)
if request.method == 'POST':
form = forms.CreateArticle(request.POST, instance=article)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.save()
return redirect('articles:myarticles')
else:
form = forms.CreateArticle(instance=article)
return render(request, 'articles/article_edit.html', {'form': form})
article_edit.html
{% extends 'base_layout.html' %}
{% block content %}
<div class="create-article">
<form class="site-form" action="{% url 'articles:edit' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="jumbotron">
<div class="heading col-md-12 text-center">
<h1 class="b-heading">Edit Article</h1>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ form.title }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form.slug }}
</div>
</div>
<div class="col-md-6">
<div class="form-group">
{{ form.thumb }}
</div>
</div>
<div class="col-md-12">
<div class="form-group">
{{ form.body }}
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Update</button>
</div>
</form>
</div>
{% endblock %}
urls.py
from django.urls import path
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name='list'),
path('create/', views.article_create, name='create'),
path('edit/<int:pk>/', views.edit_articles, name='edit'),
path('myarticles/',views.my_articles, name='myarticles'),
path('<slug>/', views.article_detail, name='details'),
]
my_articles.html
That button in 4th is triggering the edit function with primary key and redirects to edit page
<tbody>
{% if articles %}
{% for article in articles %}
<tr class="table-active">
<th scope="row">1</th>
<td>{{ article.title }}</td>
<td>{{ article.date }}</td>
<td><button type="button" class="btn btn-info">Edit</button></td>
{% endfor %}
</tr>
{% else %}
<tr>
<td colspan=4 class="text-center text-danger">Oops!! You dont have any articles.</td>
</tr>
{% endif %}
In your template article_edit.html - post url is expecting a pk, you need to pass a pk just like you are doing it for template my_articles.html
<div class="create-article"><form class="site-form" action="{% url 'articles:edit' pk=form.instance.pk %}" method="post" enctype="multipart/form-data">{% csrf_token %}...
This way django knows which article you are editing