I am unable to retrieve any search results when searching for items. I am using Postgresql and Django. Below is my code. I am not sure if I am not doing the search query right or I just cannot display the results.
I have the search bar in "inventory_management.html". I am trying to get it to where the user searches for an item, and then a list of the displayed items are shown.
models.py
class Inventory(models.Model):
product = models.CharField(max_length=50)
description = models.CharField(max_length=250)
paid = models.DecimalField(null=True, max_digits=5, decimal_places=2)
bin = models.CharField(max_length=4)
listdate = models.DateField(null=True, blank=True)
listprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True)
solddate = models.DateField(null=True, blank=True)
soldprice = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True)
shipdate = models.DateField(null=True, blank=True)
shipcost = models.DecimalField(null=True, max_digits=5, decimal_places=2, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
def __str__(self):
return self.product + "\n" + self.description + "\n" + self.paid + self.bin + "\n" + self.listdate + "\n" + self.listprice + "\n" + self.solddate + "\n" + self.soldprice + "\n" + self.shipdate + "\n" + self.shipcost
views.py
#login_required(login_url="/login")
def search(request):
q = request.GET.get('q')
if q:
vector = SearchVector('product', 'description')
query = SearchQuery(q)
searchinv = Inventory.objects.annotate(search=vector).filter(search=query)
else:
searchinv = None
return render(request, 'portal/search.html', {"searchinv": searchinv})
inventory_management.html (where the search bar is located)
{% extends 'portal/base.html' %}
{% block title %}{% endblock %}
{% block content %}
<br>
<div class="row">
<div class="col">
<form class="d-flex" role="search" action="/search" method="get">
<input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success">Search</button>
</form>
</div>
<div class="col">
<a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Update Item</th>
<th>Product ID</th>
<th>Product</th>
<th>Description</th>
<th>Purchase Price</th>
<th>Location</th>
<th>List Date</th>
<th>List Price</th>
<th>Sold Date</th>
<th>Sold Price</th>
<th>Ship Date</th>
<th>Ship Cost</th>
</tr>
</thead>
{% for inventory in inventory %}
<tr>
<td><a class='btn btn-success btn-sm' href='/update/{{inventory.id}}'>Update</a>
<td>{{inventory.id}}</td>
<td>{{inventory.product}}</td>
<td>{{inventory.description}}</td>
<td>{{inventory.paid}}</td>
<td>{{inventory.bin}}</td>
<td>{{inventory.listdate}}</td>
<td>{{inventory.listprice}}</td>
<td>{{inventory.solddate}}</td>
<td>{{inventory.soldprice}}</td>
<td>{{inventory.shipdate}}</td>
<td>{{inventory.shipcost}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
search.html
{% extends 'portal/base.html' %}
{% block title %}{% endblock %}
{% block content %}
<br>
<div class="row">
<div class="col">
<form class="d-flex">
<input class="form-control me-2" type="text" name="q" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success">Search</button>
</form>
</div>
<div class="col">
<a class="btn btn-primary me-md-2" href="/newitem" type="button">Input New Purchase</a>
</div>
</div>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Update Item</th>
<th>Product ID</th>
<th>Product</th>
<th>Description</th>
<th>Purchase Price</th>
<th>Location</th>
<th>List Date</th>
<th>List Price</th>
<th>Sold Date</th>
<th>Sold Price</th>
<th>Ship Date</th>
<th>Ship Cost</th>
</tr>
</thead>
{% for inventory in inventory %}
<tr>
<td><a class='btn btn-success btn-sm' href='/update/{{inventory.id}}'>Update</a>
<td>{{inventory.id}}</td>
<td>{{inventory.product}}</td>
<td>{{inventory.description}}</td>
<td>{{inventory.paid}}</td>
<td>{{inventory.bin}}</td>
<td>{{inventory.listdate}}</td>
<td>{{inventory.listprice}}</td>
<td>{{inventory.solddate}}</td>
<td>{{inventory.soldprice}}</td>
<td>{{inventory.shipdate}}</td>
<td>{{inventory.shipcost}}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
You don't have inventory in your view's context, yet you try to use it in template:
{% for inventory in inventory %}
Change it to:
{% for inventory in searchinv %}
And it should be better.
Related
I'm trying to create Update view for Customer model which have Onetoone relation with User(django model. After five hours and trying function base and class views I'm unable to get this working. Where am I making a mistake?
my models.py
class Customer(Model):
user = OneToOneField(User, on_delete=CASCADE)
mobile = CharField(max_length=12,null=True)
dob = DateField(null=True)
def __str__(self):
return self.user.username
my views.py
class ProfileUpdateView(UpdateView):
template_name = 'forms.html'
form_class = AdminUserUpdateForm
model = User
success_url = reverse_lazy('controls')
def get_object(self, queryset=None):
return Customer.objects.get(pk=self.kwargs['pk']).user
# Not working
def customer_list_view(request):
customer = Customer.objects.filter(user__groups__name='customer')
premium = Customer.objects.filter(user__groups__name='premium')
context = {'customer': customer, 'premium': premium}
return render(request, 'customercontrol.html', context)
my forms.py
class AdminUserUpdateForm(UserChangeForm):
class Meta:
model = User
fields = ['username', 'email', 'groups']
mobile = CharField(max_length=30)
dob = DateField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
#atomic
def save(self, commit=True):
user = super().save(commit)
mobile = self.cleaned_data['mobile']
dob = self.cleaned_data['dob']
customer = Customer.objects.get(user__pk=user.pk)
customer.mobile = mobile
customer.dob = dob
if commit:
customer.save()
return user
my templates, where I get PK for the queries.
{% extends "base.html" %}
{% block content %}
<h1 class="font1">Our premium customers:</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col"><a class="btn btn-secondary" href="">Username</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Name</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Email</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Phone</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Date of Birth</a></th>
</tr>
</thead>
<tbody>
{% for c in premium %}
<tr>
<td>{{c.id}}</td>
<td>
{{ c.user.username }}</td>
<td>{{c.user.first_name}} {{c.user.last_name}} </td>
<td>{{ c.user.email}}</td>
<td>{{ c.mobile}}</td>
<td>{{ c.dob}}</td>
<td><ul>{% for item in c.user.groups.all %}<li>{{ item}}</li>{% endfor %}</ul></td>
<td><a class="btn btn-danger" href="{% url 'user-delete' c.id %}">Delete</a></td>
<td><a class="btn btn-success" href="{% url 'user-update' c.pk %}">Update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<h1 class="font1">Our customers:</h1>
<table class="table table-dark">
<thead>
<tr>
<th scope="col">User ID</th>
<th scope="col"><a class="btn btn-secondary" href="">Username</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Name</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Email</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Phone</a></th>
<th scope="col"><a class="btn btn-secondary" href="">Date of Birth</a></th>
</tr>
</thead>
<tbody>
{% for c in customer %}
<tr>
<td>{{c.id}}</td>
<td>
{{ c.user.username }}</td>
<td>{{c.user.first_name}} {{c.user.last_name}} </td>
<td>{{ c.user.email}}</td>
<td>{{ c.mobile}}</td>
<td>{{ c.dob}}</td>
<td><ul>{% for item in c.user.groups.all %}<li>{{ item}}</li>{% endfor %}</ul></td>
<td><a class="btn btn-danger" href="{% url 'user-delete' c.id %}">Delete</a></td>
<td><a class="btn btn-success" href="{% url 'user-update' c.pk %}">Update</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
the one with form
{% extends "base.html" %}
{% block content %}
<form method="post">
{% csrf_token %}
<table>{{ form }}</table>
<input type="submit" value="Submit" class="btn btn-primary">
</form>
{% endblock %}
urls.py
path('<int:pk>/groupupdate', GroupUpdateView.as_view(), name='groupdate'),
path('customercontrol', customer_list_view, name='customercontrol'),
I found solution to my own problem, I had to add function into my view which is passing initial data into form:
def get_initial(self):
initial = super().get_initial()
initial['dob'] = Customer.objects.get(pk=self.kwargs['pk']).dob
initial['mobile'] = Customer.objects.get(pk=self.kwargs['pk']).mobile
return initial
I have been trying to make an 'update function' in my table so that my data can be changed by a user.
So here is my html with the form where i want my data to go back in to, so when the user presses submit again it saves that value to the database:
<h3>Add a location </h3></br></br>
<div class="addition">
<form method="POST" action="" autocomplete="off">
{% csrf_token %}
<div class="row">
<div class="col">
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Location name" name="name" autocomplete="off">
</div>
<div class="col">
<input type="text" class="form-control" aria-describedby="emailHelp" placeholder="Description" name="desc" autocomplete="off">
</div>
<div class="col">
<button type="submit" class="btn btn-primary">Submit</button>
</div></br></br>
</form> </br></br>
<h3>Overview locations</h3>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{% for item in all_locations %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.name }}</td>
<td>{{ item.desc }}</td>
<td><a class="btn btn-sm btn-info" href="{% url 'update_location' item.id %}" >update</a></td>
</tr>
my views.py with my creation function and my update function
def location(request):
all_locations = Location.objects.all()
if request.method == "POST":
loc_form = LocationForm(request.POST or None)
if loc_form.is_valid():
loc_form.save()
return render(request, 'location.html', {"all_locations": all_locations})
else:
return render(request, 'location.html', {"all_locations": all_locations})
return render(request, 'location.html', {"all_locations": all_locations})
def updateLocation(request, pk):
all_locations = Location.objects.all()
location = Location.objects.get(id=pk)
loc_form= LocationForm(instance=location)
name = loc_form.instance.name
desc = loc_form.instance.desc
print(name)
print(desc)
return render(request, 'location.html', {"all_locations": all_locations, "name": name, "desc": desc})
my models.py
class Location(models.Model):
creation_date = models.DateTimeField(auto_now = True)
name = models.CharField(max_length=50, default=None)
desc = models.CharField(max_length=250, default="", null=True, blank=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
and my urls.py
urlpatterns = [
path('', views.index, name="index"),
path('locations', views.location, name="location"),
path('locations/<str:pk>', views.updateLocation, name="update_location"),
]
So basically i'm stuck at putting the old data back into the html input.
I've tried with a different view as well but i had basically the same issue.
Any suggestions? Thanks a lot!
I figured it out whilest doing something else:
add value="{{ name }}" to the html file on the input line. Do the similar thing for description
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.
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 %}
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 %}