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
Related
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'),
]
I'm fairly new at this. I'm trying to build a report page in iframe according to user requirement user can create report with src, width and height ...and i successfully done this...i am able to create the report now i want this created report name will be show in the dropdown menu and when the user click on report name then user can see the report and the name of the report will add on dynamically in the dropdown....
i'm waiting for response ..here i'm going to share the code what i have done ...
i would say one more thing i don't want to add these data (Src,width ,height,name of the report) in the data base ...is that possible to create report and get the same report when i will click on the report name.
index.html
<li class="dropdown">
Reports<span class="caret"></span>
<ul class="dropdown-menu">
<li class="dropdown-header">Reports</li>
<li>
<div class="buttons pull-right">
<i class="fa fa-plus"></i>
</div>
Report one
</li>
{% for item in report_item %}
<li>
{{item.name}}
</li>
{% endfor %}
</ul>
</li>
reportform.html
<form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal">
{% csrf_token %}
<div class="panel panel-default">
<div class="panel-heading">
<strong>Add Report</strong>
</div>
<div class="panel-body">
<table class="table table-hover report-body attr-table">
<tr>
<td>URL</td>
<td>
<input type="text" name="src">
</td>
</tr>
<tr>
<td>WIDTH</td>
<td>
<input type="number" name="width">
</td>
</tr>
<tr>
<td> HEIGHT</td>
<td>
<input type="number" name="height">
</td>
</tr>
<tr>
<td> NAME OF THE REPORT</td>
<td>
<input type="text" name="name">
</td>
</tr>
</table>
<input type="submit">
</div>
</div>
</form>
report_one.html
<iframe src = {{src}} width= {{width}} height= {{height}} frameborder="0" allowfullscreen allowtransparency ></iframe>
**view.py **
def reportone(request):
return render(request, 'report_one.html')
def reporttwo(request):
return render(request, 'report_two.html')
def reporttest(request):
return render(request, 'reportform.html')
def add(request):
if request.method == "POST":
report_item={}
src=request.POST['src']
width=request.POST['width']
height=request.POST['height']
name=request.POST['name']
report_item={'src':src, 'width':width, 'height':height, 'name':name}
return render(request, 'report_one.html', report_item)
else:
return render(request, 'report_one.html' , report_item)
urls.py
from django.contrib import admin
from django.urls import path
from extras.views import ObjectChangeLogView
from . import views
app_name = 'report'
urlpatterns = [
path('reportone', views.reportone, name='reportone'),
path('reporttwo', views.reporttwo, name='reporttwo'),
path('reporttest', views.reporttest, name='reporttest'),
path('add', views.add, name='add'),
]
Please try this:
models.py
from django.db import models
class Report(models.Model):
url = models.URLField(null=False,max_length=300)
width = models.IntegerField(default=300)
height = models.IntegerField(default=200)
name = models.CharField(max_length = 50)
forms.py
from .models import Report
from django.db import models
class ReportForm(forms.Form):
width = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'}))
height = forms.CharField(widget=forms.NumberInput(attrs={'class':' form-control'}))
url = forms.URLField(max_length=300)
name = forms.CharField(max_length = 50)
class Meta:
model = Report
fields = [ "url","width","height","name"]
views.py
from .forms import ReportForm
from .models import Report
def reporttest(request):
form = ReportForm()
return render(request, 'reportform.html',{'form':form})
def add(request):
report_item={}
if request.method == "POST":
obj= Report()
obj.url =request.POST['url']
obj.width=request.POST['width']
obj.height=request.POST['height']
obj.name=request.POST['name']
obj.save()
report_item={'src':request.POST['url'], 'width':request.POST['width'], 'height':request.POST['height'], 'name':request.POST['name']}
return render(request, 'report_one.html', report_item)
else:
return render(request, 'report_one.html' , report_item)
reportform.html
<form action = "add" method= "post" enctype="multipart/form-data" class="form form-horizontal">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Add Report</strong>
</div>
<div class="panel-body">
<table class="table table-hover report-body attr-table">
{% csrf_token %}
{% for field in form.visible_fields %}
<tr>
<td>{{field.label}}</td>
<td>{{field}}</td>
</tr>
{% endfor %}
</table>
<input type="submit" >
</div>
</div>
</form>
report_one.html
<iframe width="{{width}}" height="{{height}}" src="{{src}}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
please try this.After change model then migrate it.
simple url for checking :https://www.youtube.com/embed/F5mRW0jo-U4
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
I guess there is some error in updateorder function, but I cannot find it. When I am clicking on the update button in dashboard.html it gives an error saying that
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order\/(?P[^/]+)\/$']
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from accounts.models import *
from accounts.forms import OrderForm
# Create your views here.
def home(request):
customers = Customer.objects.all()
orders = Order.objects.all()
total_customers = customers.count()
total_orders = orders.count()
pending = orders.filter(status='Pending').count()
delivered = orders.filter(status='Delivered').count()
context = {'customers':customers, 'orders':orders, 'pending':pending, 'delivered':delivered, 'total_customers':total_customers,
'total_orders':total_orders}
return render(request, 'accounts/dashboard.html', context)
def products(request):
products = Product.objects.all()
return render(request, 'accounts/products.html', {'products':products})
def customer(request, pk):
customers = Customer.objects.get(id=pk)
orders = Order.objects.all()
orders_counts = orders.count()
context = {'customers':customers, 'orders':orders, 'orders_counts':orders_counts}
return render(request, 'accounts/customer.html', context)
def createorder(request):
form = OrderForm
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)
def updateorder(request, pk):
orders = Order.objects.get(id = pk)
form = OrderForm(instance = orders)
context = {'form':form}
return render(request, 'accounts/order_form.html', context)
> Blockquote
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>/', views.customer, name = 'customer'),
path('create_order/', views.createorder, name = 'create_order'),
path('update_order/<str:pk>/', views.updateorder, name = 'update_order')
]
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="">CREATE CUSTOMERS</a>
<table class = "table table-sm">
<tr>
<th>Customers</th>
<th>Phone</th>
</tr>
{% for i in customers %}
<tr>
<!-- <td>View</td> -->
<td>{{i.name}}</td>
<td>{{i.phone}}</td>
<td><a class="btn btn-info" href="{% url 'customer' i.id %}">View</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
<div class="col-md-7">
<h5>LAST 5 ORDERS</h5>
<hr>
<div class="card card-body">
<a class="btn btn-primary btn-sm btn-block" href="{% url 'create_order' %}">CREATE ORDERS</a>
<table class = "table table-sm">
<tr>
<th>Product</th>
<th>Date Ordered</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for i in orders %}
<tr>
<td>{{i.product}}</td>
<td>{{i.date_created}}</td>
<td>{{i.status}}</td>
<td><a class="btn btn-info" href="{% url 'update_order' Order.id %}">Update</a></td>
<td><a class="btn btn-danger" href="">Delete</a></td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{% endblock %}
forms.py
from django.forms import ModelForm
from accounts.models import Order
class OrderForm(ModelForm):
class Meta:
model = Order
fields = '__all__'
order_forms.html
{% extends 'accounts/main.html' %}
{% load static %}
{% block content %}
<form method="post">
{% csrf_token %}
{{form}}
<input type="submit" name="Submit">
</form>
{% endblock %}
{% for i in orders %}
...
{% url 'update_order' Order.id %}
it's i, not Order, so change to
{% url 'update_order' i.id %}
For django-1.x, you can not use such path(..)s, and in that case you need to write a regular expression, like:
url(r'^complete/(?P<todo_id>[0-9]+)$', views.completeTodo, name='complete'),
If you are using django-2.x, you probably want to use path(..), like you have.
I believe it may be to do with how you've set up your regex. What data type is the Order object from your models, I am assuming they're string since that's the type you have defined in your urls. If they're then do as you've done , else if its string then do what's below
For urls, instead of this:
url('update_order/<todo_id>', , views.updateorder, name = 'update_order'),
try this:
url(r'^update_order/(?P<todo_id>\d+)$', , views.updateorder, name = 'update_order'),
Or incase you want to use [path]
path('update_order/<int:todo_id>', views.updateorder, name = 'update_order'),
I am developing an app in Django.
I have contents of a database displayed on my template glossario.html ad I want to implement a search bar to query the database and display only the query results.
So I have set up the toolbar in glossario.html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="topnav">
<a id="pulsante_ricerca_avanzata" href="#Ricerca_avanzata">Ricerca avanzata</a>
<div id="blocco_ricerca_semplice" class="search-container">
<form method="GET" action="{% url 'glossario' %}">
<input type="text" placeholder="Ricerca terminologia..." name="q" value="{{request.GET.q}}">
<button id="cancel_search_button" type=""><i class="fa fa-trash"></i></button>
<button id="search_button" type="submit"><i class="fa fa-search"></i></button>
</form>
</div>
</div>
In views.py have prepared a function to show only the query results:
def vista_ricerca_semplice(request):
template = "glossario.html"
query = request.GET.get('q')
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query))
context = {'selected_entries':selected_entries}
return render(request, template, context)
Note: Lemma_it is the field of my model I want to search and glossary_entry is the name of my model
To tell the truth I am looking for a command to do the query on all the model fields without typing
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query) | Q(field2__icontains=query) | Q(field3__icontains=query) ...)
In app/urls.py I have mapped the url of the search results:
from django.urls import path
from . import views
from .views import vista_ricerca_semplice
urlpatterns=[
path('', views.home, name='home'),
path('glossario', views.glossario, name="glossario"),
path('glossario', views.vista_ricerca_semplice, name="vista_ricerca_semplice"),
]
But it simply does not work.
If for example I type "attempt1", the console returns
[19/Sep/2019 18:08:00] "GET /glossario?q=attempt1 HTTP/1.1" 200 126941
And it updates the page but there is no query. The view does not change.
What's the error here?
I have been working on a similar project like yours but mine is a school management system.
I have implemented a search bar and it is working perfectly.
in views.py
def search_student(request):
student_list = DataStudent.objects.all()
student_filter = StudentFilter(request.GET, queryset=student_list)
return render(request, 'accounts/Students/Search/student_list.html', {'filter': student_filter})
and in urls.py
from django.conf.urls import url, include
from . import views
urlpatterns=[
url(r'^search_student', views.search_student, name="search_student")
]
in student_list.html
{% extends 'base.html' %}
{% block body %}
<div class="container" style="margin-left: 200px;font-size: 20px; padding: 0px 10px;">
{% load crispy_forms_tags %}
<form method="get">
<nav class="container nav navbar-expand navbar" >
<div style="color:black; font-size:160%">
<ul class="navbar-nav mr-auto" >
<li class="nav-item">
{{ filter.form.name|as_crispy_field }}
</li>
<li class="nav-item">
{{ filter.form.Class|as_crispy_field }}
</li>
<li class="nav-item">
{{ filter.form.stream|as_crispy_field }}
</li>
<li style="margin-left:5%"> <button type="submit" style="margin-top:60%;" class="btn btn-primary">Search </button>
</li>
</ul>
</div>
</nav>
</form>
<ul>
<div class="container" style="margin-left:2px; font-size:15px; padding:3px">
<table class="table table-hover" border="2">
<thead class="table-success">
<tr>
<td>Reg Number</td>
<td>Photo</td>
<td>Name</td>
<td>Class</td>
<td>Stream</td>
<td>Admision No</td>
<td>Action</td>
</tr>
</thead>
<tbody>
{% for student in filter.qs %}
<tr>
<td>{{ student.admission_no}}</td>
<td>{% if student.Student_Photo %}<img src="{{ student.Student_Photo.url}}" width="50">{% endif %}</td>
<td>{{ student.name}}</td>
<td>{{ student.Class}}</td>
<td>{{ student.stream}}</td>
<td>{{ student.admission_no}}</td>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<td><a class="btn btn-primary a-btn-slide-text" href="{% url 'singlestudentdetails' pk=student.id %}"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
<span><strong>View</strong></span></a>
<a class="btn btn-danger a-btn-slide-text" href="{% url 'deletestudent' pk=student.id %}"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span> </a>
</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% endblock %}
I hope this helps you fellow dev, happy coding
SOLVED
As pointed by ,the problem was that I had two views functions pointing at the same path (template).
This cannot be. One template/path cannot be pointed by more than one view function.
So I eliminated all the code related to my previous view function vista_ricerca_semplice
I solved my problem by changing code in urls.py and views.py like this:
In views.py:
def glossario(request):
query = request.GET.get('q')
template = "glossario.html"
# query executed
if query:
query = request.GET.get('q')
selected_entries = glossary_entry.objects.filter(Q(Lemma_it__icontains=query))
return render(request, template, {'all_entries':selected_entries})
# no query
else:
all_entries = glossary_entry.objects.all
return render(request, template, {'all_entries':all_entries})
In Urls.py
urlpatterns=[
path('', views.home, name='home'),
path('glossario', views.glossario, name="glossario"),
]