Why doesn't this loop run? - python

As you can see, this code lets the user create models called Images. The problem is, no images are actually created when I want them to be. The print test with the obnoxious caps (print images) returns an empty list after I've inputted information multiple times.
Perhaps related to this issue, I simply cannot add print tests to any of the if/else loops in the code. It returns an indentation error, even when I check all of the indents for four spaces.
I'm really confused. I suspect I'm misunderstanding the control flow?
views.py:
from django.shortcuts import render
from images_app.models import Image
def index(request):
images = Image.objects.all()
image_names = [a.name for a in images]
print images ### THIS RETURNS AN EMPTY LIST!!
if request.method == 'POST':
image_string = request.POST.get('get_image')
index = image_string.find('(')
# divide input into parent and child
if index == -1:
parent = image_string
child = None
else:
parent = image_string[0:index]
child = image_string[index+1:len(image_string)-1]
# print "Child is.. ", child.name ### THIS RETURNS AN INDENTATION ERROR
# create models based on input
if parent not in image_names and child not in image_names:
parent_model = Image(name=parent)
child_model = Image(name=child, parent=parent_model)
elif parent in image_names and child not in image_names:
parent_model = images.get(name=parent)
child_model = Image(name=child, parent=parent_model)
elif parent not in image_names and child in image_names:
child_model = images.get(name=child)
parent_model = Image(name=parent)
child_model.parent = parent_model
print "descendants are: ", parent_model.get_descendants()
else:
print "else"
return render(request, 'images_app/index.html', {'images':images})
def get_images(request):
term = request.GET.get('terms') #jquery-ui.autocomplete parameter
images = Image.objects.filter(name__istartswith=terms)
res = []
for i in images:
#make dict with the metadatas that jquery-ui.autocomple needs
dict = {'id':i.id, 'label':i.__unicode__(), 'value':i.__unicode__()}
res.append(dict)
return HttpResponse(simplejson.dumps(res))
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<title> images </title>
<script>
<script type="text/javascript">
$(function() {
$("#terms").autocomplete({
source: "{% url 'images_app:get_images' %}",
minLength: 1,
});
});
</script>
</head>
<nav>
associate
</nav>
<body>
{% for images in images %}
{{ image.name }}
{% endfor %}
<section>
<h1>create an image</h1>
<form action="{% url 'images_app:index' %}" method="post">
{% csrf_token %}
<div class="ui-widget">
<label for="get_image">create image: </label>
<input id="get_image" name="get_image">
</div>
<div id="buttons">
<input type="submit" value="create" class="submit" name="create" />
</div>
</form>
</section>
</body>

You don't ever save any of your images.
Doing Image(blah) simply instantiates an object in memory. You need to call .save() on the instance, or alternatively do Image.objects.create(blah) to instantiate and save at the same time.

Related

Data input from template file is not storing in .txt file in Django Python ( Get method)?

I'm trying to store some data from a html form in a .txt file. But when I store data from my variable used to recieve data it give "None". But when I pass string directly it successfully store.
def write(request):
p_no = request.GET.get('p_no')
# temp = "% s" % p_no
# Str_value = '{}'.format(p_no)
temp = p_no.__str__()
with open('C:\\Users\\The Goat\\Desktop\\testp\\Files\\sample.txt', 'w+') as f:
testfile = File(f)
testfile.write(temp)+
testfile.close
f.close
return render(request,'index.html')
Perhaps in the form you use form method="post", and in the view you request request.GET.get.
The following code works for me(bboard replace with the name of your folder where the templates are located):
views.py
def form(request):
return render(request, 'bboard/index3.html')
def write(request):
p_no = request.GET.get('p_no')
temp = p_no.__str__()
with open('test12345.txt', 'w+') as f:
f.write(temp)
f.close
return HttpResponse(f"<h2>Name: {temp}")
index3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h2>User form</h2>
<form method="get" action="{% url 'write'%}">
{% csrf_token %}
<p>Name:<br> <input name="p_no" /></p>
<input type="submit" value="Send" />
</form>
</body>
</html>
urls.py
urlpatterns = [
path("form/", form),
path("write/", write, name="write"),
]

My point annotation in Chart.js 3.3.2 won't render in my Django template. Making a realtime graph of temperature for my wood-fired pizza oven

The goal and problem:
I'm having trouble getting an annotation to render in Chart.js. My project is a Django/Chart.js-run graph that shows the temperature of my wood fire pizza oven. I would like to see the temperature graphed over time and be able to submit a model form indicating when I have shut the door, and to have that annotated on the graph.
Specific issue
The issue is that I can't get the annotation to render on my graph, partly because I am unsure what x/y coordinate to put in. This can be seen in the const options variable in my index.html. In order, have attached my base.html, index.html, view.py, and forms.py. I also included a link to a screen shot of the graph so far and of my pizza oven in case you're curious. :P
Versions
I'm using Python 3.9.5, Chartjs 3.3.2, and Django 3.2.4.
Would be grateful for some help!
-Mike
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<!--Chartjs CDN-->
<!--<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}
{% endblock content %}
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper)
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns"
crossorigin="anonymous"></script>-->
</body>
</html>
{% extends 'base.html' %}
{% block content %}
<body>
<canvas id="myChart" width="600" height="400"></canvas>
<!--This chart will graph temperature of my oven. I would like to be able to annotate
the graph to show when I have closed my oven door. This annotation will be handled by a form, which
will store data inthe sqlite database. I would like to display an annotation on the graph but
I can't seem to get it working-->
<script>
const options = {
plugins: {
autocolors: false,
annotation: {
annotations: {
point1: {
type: 'point',
xValue: '{{ q_recent.dateposted }}', //I don't know what to put here to get the annotation
yValue: '{{ q_recent.dateposted }}', //I don't know what to put here to get the annotation
backgroundColor: 'rgba(255, 99, 132, 0.25)'
}
}
}
}
};
const config = {
type: 'line',
data: {
/* the labels and data are created in the view variable "q_recent" and then using the for loop
the labels and data are plugged in to the labels and data below*/
labels: [{% for q_recent in q_recent %} '{{ q_recent.dateposted }}', {% endfor %}],
datasets: [{
label: 'Pizza Oven Temp',
data: [{% for q_recent in q_recent %} '{{ q_recent.oventemperature }}', {% endfor %}],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.3
}]
},
options
};
var myChart = new Chart(document.getElementById('myChart'),config);
</script>
<!--reference to the model form below (called form, see forms.py) allows me to submit a true value
for the boolean variable "isdoorclosed'" to the database, marking when I have closed my oven door-->
<br>
<div class="col-md-4">
<div class="border p-3 shadow">
<form method="POST">
{% csrf_token %}
{{form}}
<input class="btn btn-danger btn-lg btn-block" type="submit" value="Enter">
</form>
</div>
</div>
</body>
{% endblock content %}
from django.shortcuts import render, redirect
from django.utils import timezone
import random
import time
from .forms import OvenDataForm
from .models import OvenData
def index(request):
#The next oven temperature data and store it in the database.
for i in range(1,15):
temp_random = random.randint(400,1000)
ambient_random = random.randint(13,20)
#the below two lines puts values in the database and sets the object to q for further refernece in the context
q = OvenData.objects.create(oventemperature=temp_random, ambienttemperature = ambient_random, dateposted = timezone.now(), timecloseddoor = timezone.now(), isdoorclosed = False)
q.save()
#this gives me the last 10 database values to be printed in the graph.
q_recent = OvenData.objects.all().order_by('-id')[:5]
#this will confirm that the latest value I am getting from the database is properly printed to the template
print(ambient_random)
print(temp_random)
"""the model variables below:
oventemperature = models.FloatField(null = True)
ambienttemperature = models.DecimalField(decimal_places=2, max_digits=20, null=True)
dateposted = models.TimeField(null = True)
timecloseddoor = models.DateTimeField(blank = True, null=True)
isdoorclosed = models.BooleanField(blank = True, default=False) """
if request.method == 'POST':
form = OvenDataForm(request.POST)
if form.is_valid():
# here I'm saying, don' save it yet, I want to change something about the data.
# In my case I'm putting other values along with the door closed variable coming from the form.
obj = form.save(commit=False)
obj.oventemperature = 799.9
obj.ambienttemperature = ambient_random
obj.dateposted = timezone.now()
obj.timecloseddoor = timezone.now()
print(q.isdoorclosed)
obj.save()
#I took out this redirect to the home page because it was loading the page again. I stopped
# this given this cues up the index view which causes random data to be generated and saved.
#return redirect('/')
else:
form = OvenDataForm()
context = {
'q_recent': q_recent,
'q': q,
'form': form
}
return render(request, 'index.html', context)
from django import forms
from .models import OvenData
"""
oventemperature = models.FloatField(null = True)
ambienttemperature = models.DecimalField(decimal_places=2, max_digits=20, null=True)
dateposted = models.TimeField(null = True)
timecloseddoor = models.DateTimeField(blank = True, null=True)
#using blank=false means that the field is required. Null=True means it can be empty in the database
isdoorclosed = models.BooleanField(blank = True, default=False)
"""
class OvenDataForm(forms.ModelForm):
#meta describes anything thats not a field
class Meta:
model = OvenData
fields = ['isdoorclosed']
exclude = []
#the labels section is a piece of meta data in the form allowing you to cutomize a field.
labels = {
'isdoorclosed': 'Tick here and submit when the door is closed ',
}
Goal Graph
My pizza oven
The reason there are no annotations showing is because you don't have a script tag pointing to the annotations plugin so it's never installed, if you add a script tag pointing at a CDN for the annotations lib as described here they will show: https://www.chartjs.org/chartjs-plugin-annotation/guide/integration.html#script-tag

Flask - how to keep list index after form submit?

I have a list of images that I want to display on a page. These image names are formatted basically YYYYMMDD_HHMMSS.jpg. I want this single page to either list all images, or only list and show those taken on a certain date (meaning a main page, not like /index to show all images, /date-specific to show some images).
So far, I have been able to show all images, and click "next"/"previous" buttons to loop through all images. I also have a table below the image, showing all the images that are in the index.
Works great - no issues.
However, I am also trying to implement a date filter, where the user can select a date from the Calendar Picker, and have the site filter out and only show photos on that day. So far, I can successfully filter one time. However, when I click "next"/"previous" buttons, or choose an image from the table, it resets back to the full list of images.
How do I keep the filtered list? I thought I could do it by keeping the date chosen in the Input field, but after using the "next"/"previous" buttons, the whole page resets and it clears that field.
I also tried including the list in the HTML portion, but it still returns all the photos. (Also makes the URL ugly, since it includes the image list for each photo listed in the table):
<td> {{ image }} </td>
Here's a .gif of the page I'm working on.. First, you'll see I can successfully click around, navigate between all photos. Then, I can successfully filter to show photos on a specific date. However, anything past that keeps sending me back to the full image list.
Anyways, without further ado, here's the codes. (Note I try to keep it minimal, so might have omitted an important piece, so please let me know if I need to post something else here):
routes.py
import os
import random
from flask import render_template, url_for, request, Blueprint, redirect # noqa
from app import app
IMAGE_FOLDER = r"C:/MyPath/Test"
FAVORITE_LIST = os.path.join(IMAGE_FOLDER, "favorites.txt")
blueprint = Blueprint('images', __name__,
static_url_path='/static/images',
static_folder=IMAGE_FOLDER)
app.register_blueprint(blueprint)
images = os.listdir(IMAGE_FOLDER)
image_urls = ["20190411_123200.jpg", ... other images in a list]
class Photo_Index():
def __init__(self, index=0):
self.index = index
def increase_number(self, num_images):
if self.index == num_images:
self.index = 0
else:
self.index = self.index + 1
return self.index
def decrease_number(self, num_images):
if self.index == 0:
self.index = num_images
else:
self.index = self.index - 1
return self.index
def random_number(self, num_images):
self.index = random.randint(0, num_images)
return self.index
def set_number(self, number):
self.index = number
return self.index
# functions to create and edit Favorites. this works so I'm excluding]
def day_month_year(filename):
"""
Takes a string `20190212` and pulls out Year, Month, Date
"""
year = filename[:4]
month = filename[4:6]
day = filename[6:8]
return str(year + "-" + month + "-" + day)
def get_files_on(specific_date):
_files = []
print("\nLooking for files on:", specific_date, "\n")
for file in image_urls:
# print(file, day_month_year(file))
if day_month_year(file) == specific_date:
_files.append(file)
return _files
photo_index_obj = Photo_Index()
fav_photo_index = Photo_Index()
def update_index(rqst, indx_obj, num_images):
print("Updating index, have", num_images, "photos")
if num_images == 1:
indx_obj.set_number(0)
elif 'prev-photo' in rqst.form:
indx_obj.decrease_number(num_images)
elif 'next-photo' in rqst.form:
indx_obj.increase_number(num_images)
elif 'random-photo' in rqst.form:
indx_obj.random_number(num_images)
return indx_obj
#app.route("/<chosen_image>", methods=["GET", "POST"])
#app.route("/", methods=["GET", "POST"])
def default_template(date=None, image_list=None, chosen_image=None):
if image_list is None:
image_list = image_urls
num_images = len(image_list) - 1
if request.method == "POST":
if 'go-to-date' in request.form:
date = request.form['go-to-date']
image_list = get_files_on(date)
num_images = len(image_list) - 1
photo_index_obj.set_number(0)
if len(image_list) == 0:
image_list = ["no_images_for_date.jpg"]
elif 'prev-next-buttons' in request.form:
print("Updating index, have", num_images, "photos")
update_index(request, photo_index_obj, num_images)
elif 'favorite-photo' in request.form:
add_to_favorites(image_list[photo_index_obj.index])
elif 'un-favorite-photo' in request.form:
remove_from_favorites(image_list[photo_index_obj.index])
if chosen_image is None:
chosen_image = image_list[photo_index_obj.index]
elif chosen_image is not None:
photo_index_obj.set_number(image_list.index(chosen_image))
favorite = is_favorite(image_list[photo_index_obj.index])
print("Images:", image_list)
return render_template('index.html',
title="Local Image Viewer",
photo_index=photo_index_obj.index,
image=chosen_image,
image_list=image_list,
favorite=favorite)
#app.route("/<chosen_image>", methods=["GET", "POST"])
def chosen_image(chosen_image):
date = request.form['go-to-date']
return default_template(date=date,
chosen_image=chosen_image)
index.html (I omitted the Select list, as that's kind of superfluous for this post)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
<link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/index.css') }}">
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}">
</head>
<body>
{% extends "layout.html" %}
{% block content %}
<h3>Index: {{ photo_index }}</h3>
<h3>Filename: {{ image }}</h3>
<div id="calendar-selector">
{% include "/HTML Snippets/calendar.html" %}
</div>
<div class='image-container' id='image'>
{% include "/HTML Snippets/favorite_button.html" %}
<img src="{{ url_for('images.static', filename=image) }} " id="the-photo">
</div>
<div class='button-container' id='buttons'>
<form action="" method="post">
<input type="hidden" name="prev-next-buttons">
<input type="submit" value="Prev photo" name='prev-photo'>
<input type="submit" value="Next photo" name='next-photo'>
<input type="submit" value="Random photo" name='random-photo'>
<br/>
<button type='button' id='rotate-button' onclick="rotateMeCounterClockwise('#the-photo')">Rotate Photo CounterClockwise</button>
<button type='button' id='rotate-button' onclick="rotateMeClockwise('#the-photo')">Rotate Photo Clockwise</button>
</form>
</div>
<div class='table-container'>
<table id='image-list' name='select-from-table'>
{% for image_row in image_list | batch(3) %}
<tr>
{% for image in image_row %}
<td> {{ image }} </td>
{% endfor %}
</tr>
{% endfor %}
</table>
</div>
{% endblock %}
</body>
</html>
and the calendar bit, calendar.html
{% block topscripts %}
<link rel="stylesheet" type="text/css" href= "{{ url_for('static',filename='styles/calendar.css') }}">
<script>
$(function() {
$("#datepicker").datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
{% endblock %}
{% block content %}
<form method="post" action="{{ url_for('default_template') }}">
<input type="hidden" name="calendar-form">
<p>
Date: <input type="text" id="datepicker" name='go-to-date'
{% if request.form['go-to-date'] is not none %}
value="{{request.form['go-to-date']}}"
{% endif %}
></p>
<input type="submit">
</form>
{% endblock %}
{% block endscripts %}
{% endblock %}
You need to pass along enough information in your next/previous form and in the table links to re-apply the date filter. Your calendar form is separate from the next/previous navigation form, the browser won't serialise information from one when submitting the other. Clicks on <a href="..."> links will not include the date input field value either.
Note that clicks on the table links generate GET requests, so you need to look for go-to-date in the request.values mapping to accommodate both query parameters and form data.
You need to look for this parameter not only when you receive a POST request, but for all requests:
if 'go-to-date' in request.values:
date = request.values['go-to-date']
image_list = get_files_on(date)
photo_index_obj.set_number(0)
if len(image_list) == 0:
image_list = ["no_images_for_date.jpg"]
else:
image_list = image_list or image_urls
num_images = len(image_list) - 1
if request.method == 'POST':
# ...
Then generate URLs that include the parameter:
{%- set url_params = {'go-to-date': request.values['go-to-date']} if request.values['go-to-date'] else {} -%}
{% for image in image_row %}
<td> {{ image }} </td>
{% endfor %}
For the next/previous form, just add a hidden input field with the current go-to-date value:
<form action="" method="post">
<input type="hidden" name="prev-next-buttons">
{%- if request.values['go-to-date'] -%}
<input type="hidden" name="go-to-date" value="{{ request.values['go-to-date'] }}">
{%- endif -%}
<input type="submit" value="Prev photo" name='prev-photo'>
<input type="submit" value="Next photo" name='next-photo'>
<input type="submit" value="Random photo" name='random-photo'>
<br/>
<button type='button' id='rotate-button' onclick="rotateMeCounterClockwise('#the-photo')">Rotate Photo CounterClockwise</button>
<button type='button' id='rotate-button' onclick="rotateMeClockwise('#the-photo')">Rotate Photo Clockwise</button>
</form>

File object not saving to disk

This is my views.py
from django.shortcuts import render
# Create your views here.
from forms import DocumentForm
from models import Document
def SaveDocument(request):
saved = False
if request.method == "POST":
#Get the posted form
MyDocumentForm = DocumentForm(request.POST, request.FILES)
if MyDocumentForm.is_valid():
print 'It enters here'
document = Document()
document.name = MyDocumentForm.cleaned_data["name"]
document.document = MyDocumentForm.cleaned_data["document"]
print document.document
document.save()
saved = True
else:
print 'Fails'
else:
MyDocumentForm = DocumentForm()
return render(request, 'saved.html', locals())
profile.html
<html>
<body>
<form name = "form" enctype = "multipart/form-data"
action = "{% url "SaveDocument" %}" method = "POST" >{% csrf_token %}
<div style = "max-width:470px;">
<center>
<input type = "text" style = "margin-left:20%;"
placeholder = "Name" name = "name" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<input type = "file" style = "margin-left:20%;"
placeholder = "document" name = "document" />
</center>
</div>
<br>
<div style = "max-width:470px;">
<center>
<button style = "border:0px;background-color:#4285F4; margin-top:8%;
height:35px; width:80%; margin-left:19%;" type = "submit" value = "Login" >
<strong>Login</strong>
</button>
</center>
</div>
</form>
</body>
</html>
The code works perfectly fine but it does not seem to save the file to disk. Printing the document shows that there is a document.
May i know what i did wrongly? i was following this example with minor changes
Need a minimal Django file upload example
in this line document.document = MyDocumentForm.cleaned_data["document"]

How to retrieve value from checkbox defined in django template

I have created a menu with three options(home,change password and logout). In home I am displaying all the books stored in the database. Now I want to filter the contents based on categories of the books using checkbox. By default all the books are shown upon filtering the category only the books of that category should be shown.But for me it is showing all the books even after clicking on all the checkbox (checkbox contains the categories).I think there is some problem in my template file.
urls.py,
url(r'^welcome_user/$',views.welcome_user, name='welcome_user'),
Models.py,
class Add_cat(models.Model):
category = models.CharField("Name",max_length=25,unique=True)
def __unicode__(self):
return u'{0}'.format(self.category)
class Add_prod(models.Model):
book = models.CharField("Book Name",max_length=40)
author = models.CharField("Author",max_length=30)
price = models.PositiveIntegerField("Price")
image = models.ImageField(upload_to='images',null=True)
cat = models.ForeignKey(Add_cat,on_delete=models.CASCADE)
Template file,
{% block content %}
{% load staticfiles %}
<head>
<link rel="stylesheet" href="{% static 'style.css' %}">
</head>
<body>
<div class="box">
<div class="sideNav">
<form action="{% url 'welcome_user' %}">
<p id=id3>Categories</p>
<hr>
{% for i in products %}
<input type="checkbox" name="cat_name" value="{{i.cat}}">{{i.cat}}<br>
{% endfor %}
<button type="submit">Submit</button>
</form>
</div>
<div>
{% for i in products %}
<div style="display:inline-block;margin:30px">
<img src="{{i.image.url}}" alt="No Image" width=196px height=196px>
<p id=id4>Rs.{{i.price}}</p>
</div>
{% endfor %}
</div>
</div>
</body>
{% endblock %}
Views.py,
#login_required
def welcome_user(request):
if 'cat_name' in request.GET:
filter_category = request.GET.getlist('cat_name')
my_products = Add_prod.objects.filter(cat__in=filter_category)
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
To check whether checbox value is in sent form you should go with following condition
if 'cat_name' in request.GET:
#checkbox has been checked
else:
#it is not checked
Remember that in operator return boolean so you can also do
filter_category = 'cat_name' in request.GET
To get value you just need to get values of 'cat_name' key like:
value = request.GET['cat_name']
after checking whether it is in GET parameters or not
I think all you need to do is add __in to your filter:
#login_required
def welcome_user(request):
filter_category = request.GET.getlist('cat_name')
categories = Add_cat.objects.all()
if filter_category: # I couldn’t decipher the structure of an `Add_cat`, so I left off the `in` check since it would not work for lists
print filter_category
my_products = Add_prod.objects.filter(cat__in=filter_category) # the template implies that this field is `cat` and not `category`
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
Checkboxes work a little bit different from other form inputs, so if you examine a post sent from a form that includes a checkbox,
if the checkbox is checked, your queryset will look like:
the value will be 'on'
So, you have to check
if request.POST.get('cb1')=='on':
"item is selected"
else:
"item is not selected"
Try this below code
Add_prod.objects.filter(cat__in=filter_category)
#login_required
def welcome_user(request):
filter_category = request.GET.getlist('cat_name')
if filter_category:
my_products = Add_prod.objects.filter(cat__in=filter_category)
context = { "products":my_products}
else:
my_products = Add_prod.objects.all()
context = { "products":my_products}
return render(request,"welcome-user.html",context)
Template file
Remove quotes(') from {% url 'welcome_user' %}
<form method='get' action="{% url welcome_user %}">
UPDATE
Add quotes between views.welcome_user
urls.py
url(r'^welcome_user/$','views.welcome_user', name='welcome_user'),

Categories

Resources