I am looking to create a very simple form with several drop down fields allowing users to query a database of restaurants I have created (I would like to use the fields 'food', 'city' and 'average rating'). Whilst I have found an approach to do this using separate html pages (Django form to query database (models)) I would like to implement this on one page (restaurants.html).
I am using Python 3.1.0, Django 2.0.1 and Bootstrap 4.0.
Appreciate all your help.
My models.pyis as follows:
from django.db import models
import numpy as np
# Create your models here.
class Restaurant(models.Model):
name = models.CharField(max_length=100, null=False)
desc = models.CharField(max_length=100)
web = models.CharField(max_length=100)
phone = models.CharField(max_length=40)
address = models.CharField(max_length=100)
post_code = models.CharField(max_length=20)
picture = models.ImageField(upload_to='images/restaurants', null=True)
map = models.ImageField(upload_to='images/restaurants', null=True)
FOOD = ((1,'English'),
(2,'French'),
(3,'American'),
(4,'Indian'),
(5, 'Undefined'))
food = models.IntegerField(choices=FOOD, default=5)
CITY = ((1,'London'),
(2,'Paris'))
city = models.IntegerField(choices=CITY, default=1)
STARS = ((1,'One'),
(2,'Two'),
(3,'Three'),
(4,'Four'),)
CB_rating = models.IntegerField(choices=STARS, default=4)
def average_rating(self):
all_ratings = map(lambda x: x.rating, self.review_set.all())
return np.mean(all_ratings)
def __str__(self):
return self.name
views.py:
from django.shortcuts import get_object_or_404, render
from .models import Review, Restaurant
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .forms import ReviewForm
import datetime
def review_list(request):
latest_review_list = Review.objects.order_by('-pub_date')[:9]
context = {'latest_review_list':latest_review_list}
return render(request, 'review_list.html', context)
def review_detail(request, review_id):
review = get_object_or_404(Review, pk=review_id)
return render(request, 'review_detail.html', {'review': review})
def restaurant_list(request):
restaurant_list = Restaurant.objects.order_by('-name')
context = {'restaurant_list':restaurant_list}
return render(request, 'restaurants.html', context)
def restaurant_detail(request, restaurant_id):
restaurant = get_object_or_404(Restaurant, pk=restaurant_id)
return render(request, 'restaurant_detail.html', 'restaurant':restaurant})
def user_review_list(request, username=None):
if not username:
username = request.user.username
latest_review_list = Review.objects.filter(user_name=username).order_by('-pub_date')
context = {'latest_review_list':latest_review_list, 'username':username}
return render(request, 'user_review_list.html', context)
restaurants.html:
{% extends 'base.html' %}
{% load staticfiles %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<h3>Search Criteria</h3>
<hr>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<form method="get" action="/search/">
Search Restaurants:<input type="text" name="q" id="id_q" value="{{ query }}"/>
<input type="submit" value="Search" />
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-offset-4" style="text-align: center">
<h3>Search Results</h3>
<hr>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div>
{% if restaurant_list %}
<div class="container">
<div class="table-responsive">
<table class="table table-bordered table-hover" style="text-align: center;">
<caption class="text-center">A list of restaurants based on your search criteria above.</caption>
<thead>
<th class="col-xs-2">Name</th>
<th class="col-xs-6">Description</th>
<th class="col-xs-1" style="text-align: center">Food Type</th>
</thead>
<tbody>
{% for restaurant in restaurant_list %}
<tr>
<td style="text-align: left;"><strong>{{ restaurant.name }}</strong></td>
<td style="text-align: left;">{{ restaurant.desc }}</td>
<td style="text-align: center;">{{ restaurant.food }}</td>
{% endfor %}
</tr>
</tbody>
</table>
</div>
</div>
{% else %}
<h3>No restaurants match your search criteria.</h3>
{% endif %}
</div>
</div>
</div>
{% endblock %}
Related
I am using Class Based Views in django... Then my model is:
models.py
class Survey(Base):
description = models.CharField('Description', max_length=50, unique=True)
item1 = models.CharField('Item1', max_length=50)
item2 = models.CharField('Item2', max_length=50)
...
class Meta:
verbose_name = 'Survey'
def __str__(self):
return self.description
Now I am reading database data for fill in select and works fine.
How I get this select item for fill table fields?
info.html
<div class="col-12">
<div class="card card-chart">
<div class="card-header ">
<div class="row">
<div class="col-sm-4 text-left">
<h2 class="card-title">Informations</h2>
<option selected>choose a option</option>
{% for s in survey %}
<option>{{s.description}}</option>
{% endfor %}
</select>
</div>
<!-- of course, in this moment variable [s] not exist -->
<div class="col-sm-8 text-right">
<table class="table">
<tbody>
<tr>
<td>item 1</td>
<td>item 2</td>
</tr>
<tr>
<!-- want fill this fields with select item above-->
<td>{{s.item1}}</td>
<td>{{s.item2}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
views.py
from django.views.generic import TemplateView
from .models import Survey
class IndexView(TemplateView):
template_name = 'index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['survey'] = Survey.objects.all()
return context
You should add value attribute to the options that you create in HTML.
If you want to use the value somewhere else you can follow the procedure below:
You get the Select element by giving a specific id to it and retrieve its value.
You can get the element by using var el = document.getElementById("#id_of_select").
By using el.value you can get the selected value for select.
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.
My models are as shown below.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
def __str__(self):
return ".`. {}_____{}".format(self.size_id,
self.prod_id)
This is the form I used to add and edit the model.
forms.py
from django import forms
from user.models import SizeProductMapping
class SizeProductMapForm(forms.ModelForm):
class Meta:
model = SizeProductMapping
fields = ['size_id', 'prod_id']
Here is the view I created to add ,update and delete the record.
views.py
def sizeProductMap(request):
form = SizeProductMapForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect("/admin1/sizeProductMap/")
else:
sizeProductMap_show = SizeProductMapping.objects.all()
# start paginator logic
paginator = Paginator(sizeProductMap_show, 3)
page = request.GET.get('page')
try:
sizeProductMap_show = paginator.page(page)
except PageNotAnInteger:
sizeProductMap_show = paginator.page(1)
except EmptyPage:
sizeProductMap_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show, 'form': form})
def sizeProductMap_delete(request, id):
sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
sizeProductMap_delete.delete()
return redirect('/admin1/productSizeMap')
def sizeProductMap_edit(request, id):
instance = SizeProductMapping.objects.get(size_p_map_id=id)
form = SizeProductMapForm(instance=instance)
if request.method == 'POST':
form = SizeProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/sizeProductMap')
return render(request, 'admin1/sizeProductMap.html', {'form': form})
This is my urls.
urls.py
from django.urls import path
from admin1 import views
urlpatterns = [
path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]
This is the Html page where I want to display the form according to the page request.
sizeProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
<center>Size Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{% if sizeProductMap_show %}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Size Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-size-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.size_id.label_tag}}
</th>
<td>{{form.size_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Size Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Size Product Mapping Id</th>
<th>Product ID</th>
<th>Size ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in sizeProductMap_show %}
<tr>
<td>{{x.size_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.size_id}}</td>
<td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-size-product-map-delete' x.size_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if sizeProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in sizeProductMap_show.paginator.page_range %}
{% if sizeProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if sizeProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
And if it is possible to reduce the number of line of code please also help. Thanks in advance.
I've found out the answer. There was a really a silly mistake by me.
In the sizeProductMap.html there is a mistake let me point out that:
sizeProductMap.html
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing.
I have to check {% if instance %} according to my views.py.
I am a newbie, and I am working on a website. On this website I have created admin panel to manage different products and attributes .
I have a page named size.html and and I am supposed to change it name and make it productAtributes.html and on this single page I want to do all add, update, delete operations for different Product attributes.
My code is as:
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class Color(models.Model):
color_id = models.AutoField("Color ID", primary_key=True, auto_created=True)
prod_color = models.CharField("Product Color", max_length=50, null=False)
def __str__(self):
return "{color_id}-->{prod_color}".format(color_id=self.color_id,
prod_color=self.prod_color)
class PaperChoice(models.Model):
paper_id = models.AutoField("Paper Choice ID", primary_key=True, auto_created=True)
paper_choices_name = models.CharField("Paper Choices", max_length=50, null=False)
def __str__(self):
return "{}-->{}".format(self.paper_id,
self.paper_choices_name)
views.py
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect
from user.models import *
def size(request):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
else:
size_show = Size.objects.all()
# start paginator logic
paginator = Paginator(size_show, 3)
page = request.GET.get('page')
try:
size_show = paginator.page(page)
except PageNotAnInteger:
size_show = paginator.page(1)
except EmptyPage:
size_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/size.html', {'size_show': size_show})
def size_edit(request, id):
size_edit = Size.objects.filter(size_id=id)
return render(request, 'admin1/size.html', {'size_edit': size_edit})
def size_edit_update(request, id):
if request.method == 'POST':
size_store = request.POST['prod_size']
size_update = Size(size_id=id, prod_size=size_store)
size_update.save()
return redirect('/admin1/productSize')
def size_delete(request, id):
size_deletee = Size.objects.filter(size_id=id)
size_deletee.delete()
return redirect('/admin1/productSize')
As I created add, update, delete functionality for Size I am going to do it same with color and Papaer choice.
size.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size{% endblock %}
{% block main %}
<h1>
<center>Size</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Product Size</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-product-size'%}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
<br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<br>
{% if size_show %}
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Product Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Product Id</th>
<th>Product Size</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in size_show %}
<tr>
<td>{{x.size_id}}</td>
<td>{{x.prod_size}}</td>
<td><a href="/admin1/size_edit/{{x.size_id}} "
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="/admin1/size_delete/{{x.size_id}}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if size_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in size_show.paginator.page_range %}
{% if size_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if size_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{size_show.has_next_page_number}}"> Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if size_edit %}
{% for x in size_edit %}
<form action="/admin1/size_data_update/{{x.size_id}}" method="POST">
{% csrf_token %}
<label>Size Name:</label>
<input type="text" name="prod_size" value="{{x.prod_size}}" class="form-control w-50"><br>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
</form>
{% endfor %}
{% endif %}
</div>
</div>
</div>
{% endblock %}
For performing oertions of views.py I have created size.html .Nut there around 10 to 12 product attributes ,and for that attributes I don't want to create seprate html pages.
I want to do all the operations for all the attributes in single html page. Is it possible?
Means according to the atrribut type request the page data should change dynamically, I do not have to create seprate template pages for each attribute.
You need to make the form in your views, not the Templates, I'm not sure if this is best practise but it's the only way I see you can do this, (using Class-Based Views would simplify this process a lot) but if you want to stick to functions, this is what you do.
Let's take an input line:
<label>Product Size:</label>
<input type="text" name="prod_size" class="form-control w-50"><br>
Let's use Django's tags and turn it into this:
<label>{{form.display_name}}:</label>
<input type="text" name="{{form.name}}" class="form-control w-50">
The class will probably be the same but you could extend the same functionality to the class or type fields.
In the backend, you want to make a list of all the elements you want to show, with nested dictionaries:
forms = [ # Each form
[ # Each field within the form, this way, you can have a different amount each time
{'display_name': 'Product Size', # label Display name
'name': 'prod_size'}, # name tag value
{'display_name': "it's value", # This is a different field
'name': 'just an example'}
],
]
Then you can do a for loop in the templates:
{% for form in forms %}
{$ for field in form %}
<label>{{field.display_name}}:</label>
<input type="text" name="{{field.name}}" class="form-control w-50">
I'm not exactly sure what you're trying to do in your code, so I didn't make this example too specific, but hopefully, it will give you inspiration to get you on the right track, if you need more help, just ask
urls.py
path('teacher_dashboard/<str:id>', views.TeacherDashboard , name='teacher_dashboard'),
path('student_dashboard//<str:id>', views.StudentDashboard , name='student_dashboard'),
views.py
def Login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
# print(request.POST)
user = authenticate(request , username=username , password=password)
if user is not None:
try:
is_teacher= Teacher.objects.get(profile_id=user.id)
except Teacher.DoesNotExist:
is_teacher = None
if is_teacher is not None:
login(request , user)
is_teacher= Teacher.objects.get(profile_id=user.id)
return redirect( 'teacher_dashboard', user.id)
else:
login(request , user)
student= Student.objects.get(profile_id=user.id)
return render(request ,'pages/student_dashboard.html' )
return render (request , "pages/login.html")
def TeacherDashboard(request , id):
is_teacher= Teacher.objects.get(profile_id = id)
students=Student.objects.all()
print(students)
context={
'student' : students
}
return render (request , "pages/teacher_dashboard.html" , context)
teacher_dahboard.html
{% for student in student %}
{{student}}
{%endfor %}
teacher_dashboard.html
{% extends 'pages/main.html'%}
{% block content%}
<div class="row">
<div class="col-md">
<div class="card card-body total-orders">
<h5>Teacher : {{teacher.first_name }} {{teacher.last_name}}</h5>
<hr>
<p>First Name:<b>{{teacher.first_name }}</b></p>
<p>Last Name: <b>{{teacher.last_name }}</b></p>
<p>Qualifications: <b>{{teacher.qualifications }}</b></p>
<p>Gender: <b>{{teacher.teacher_gender }}</b></p>
</div>
</div>
<div class="col-md">
<div class="card card-body total-orders">
<h5 style="text-align: center;">Contact Information</h5>
<hr>
<p>Email: <b>{{teacher.email}}</b></p>
<p>Phone: <b>{{teacher.teacher_contact}}</b></p>
</div>
</div>
</div>
<br>
{% for student in student %}
{{student.first_name}}
{%endfor %}
<div class="row">
<div class="col-md" >
<div class="card card-body total-orders">
<h5>Students Information</h5>
<table class="table table-sm">
<tr>
<th>No.</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
<th>Grade</th>
<th>Join Date</th>
<th>Gender</th>
<th>Status</th>
<th>Update</th>
<th>Remove</th>
</tr>
{% for studen in student %}
<tr>
<td>{{order.product}}</td>
<td>{{student.first_name}} {{student.last_name}}</td>
<td>{{student.email}}</td>
<td>{{student.student_contact}}</td>
<td>{{student.student_grade}}</td>
<td>{{student.student_gender}}</td>
<td>{{student.created_date}}</td>
<td>{{order.status}}</td>
<td>Update</td>
<td>Remove</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</div>
{%endblock%}
that's my code plz help if you can
in the teacher_dashbard/4 is dynamic route so the id came from there as 4
i want to render the students list on teacher_dashboard page
views.TeacherDashboard run the query and i pass it to render function but in response this issue comes
The updateorder function in these links does not exist in your urls.py
<td>Update</td>
<td>Remove</td>
Create the function in your views and reference it in your urls file.
my check in is as automatic and my checkout as None, and I wanted the page to update register inside the html, I put a button checked and when I click on it that the checkout was updated with the current time and it was already filled in the form, without needing leave the page
I tried and I can not make the mistake
Model.py
PAGO_CHOICES = (
('Não', 'Não Pago'),
('Sim', 'Pago')
)
class MovRotativo(models.Model):
checkin = models.DateTimeField(auto_now=True, blank=False, null=False,)
checkout = models.DateTimeField(default=None, null=True, blank=True)
email = models.EmailField(blank=False)
placa = models.CharField(max_length=7, blank=False)
modelo = models.CharField(max_length=15, blank=False)
valor_hora = models.DecimalField(
max_digits=5, decimal_places=2, null=False, blank=False)
pago = models.CharField(max_length=15, choices=PAGO_CHOICES)
views.py
#login_required
def movrotativos_update(request, id):
data = {}
mov_rotativo = MovRotativo.objects.get(id=id)
form = MovRotativoForm(request.POST or None, instance=mov_rotativo)
data['mov_rotativo'] = mov_rotativo
data['form'] = form
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect('core_lista_movrotativos')
else:
return render(request, 'core/update_movrotativos.html', data)
html.
{%extends 'basenew.html' %}
{% load bootstrap %}
{% block main %}
<main role="main" class="col-md-12 ml-sm-auto col-lg-10 px-50">
<br>
<br><br>
<div class="row">
<div class="col">
<h2>UpDating MovRotativos: {{ mov_rotativo}}</h2>
<form action="{% url 'core_movrotativos_update' mov_rotativo.id %}"
method="POST">
{% csrf_token %}
{{form|bootstrap}}
<table class="table table-bordered sortable" >
<thead class="p-3 mb-2 bg-primary text-white">
<tr>
<th scope="col">Horas</th>
<th scope="col">Pagar</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="" style="color:black">
{{mov_rotativo.horas_total}}</a></td>
<td><a href="" style="color:black">
{{mov_rotativo.total}}</a></td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-
primary">Salvar</button>
<form action="{% url 'core_movrotativos_checkout'
mov_rotativo.id %}" method="POST">
<button type="submit" class="btn btn-
primary">Checkout</button>
</form>
<a href="{% url 'core_movrotativos_delete' mov_rotativo.id%}"
class="btn btn-danger">Delete</a>
</form>
</div>
</div>
</main>
{% endblock %}