I want to filter products by price range from min price to max price. I tried but I am getting all products. Please suggest to me how can I do that?
def search(request):
price_from = request.GET.get('price_from', None)
price_to = request.GET.get('price_to', None)
products = Product.objects.filter(price__range=(price_from,price_to))
context = {
'price_from': price_from,
'price_to': price_to,
'products': products,
}
return render(request, 'search.html', context)
my template code
<div class="range-slider">
<form method="get" action="{% url 'search' %}" class="d-flex align-items-center justify-content-between">
<div class="price-input">
<label for="amount">PriceFrom </label>
<input type="number" name="price_from" value="{{price_from}}">
</div>
<div class="price-input">
<label for="amount">PriceTo</label>
<input type="number" name="price_to" value="{{price_to}}">
</div>
<button class="filter-btn">filter</button>
</form>
</div>
<div class="range-slider">
<form method="get" action="{% url 'search' %}" class="d-flex align-items-center justify-content-between">
<div class="price-input">
<label for="amount">PriceFrom </label>
#Just Apply For loop for evry price form
{% for i in price form %}
<input type="number" name="price_from" value="{{price_from}}">
{% end for %}
</div>
<div class="price-input">
<label for="amount">PriceTo</label>
{% for i in price to %}
<input type="number" name="price_to" value="{{price_to}}">
{% end for %}
</div>
<button class="filter-btn">filter</button>
</form>
</div>
</div>
Tell me if this worked for you
Related
View.py
if req.method == 'POST':
df = DocumentForm.objects.filter(document_id=id)
logging.info('LOG: I am here')
if df.exists():
for d in df:
description = req.POST['{}'.format(d.description, False)]
displayName = req.POST['{}'.format(d.displayName, False)]
df.update(displayName=displayName, description=description)
return redirect('/adboard/upd')
HTML File
<form class="needs-validation" action="{{id}}" method="POST" enctype="multipart/form-data" novalidate>
{% csrf_token %}
<div class="row mt-3 mb-3"></div>
{% if messages %}
<div class="alert alert-danger" role="alert">
{% for message in messages %}
{{ message }}
{% endfor %}
</div>
{% endif %}
{% for df in data %}
<div class="form-group">
<small class="text-muted bold-label m-lower">{{{df.field}}}</small>
<label for="validationCustom01">{{df.displayName}}</label>
<input type="text" class="form-control" id="validationCustom01" name="{{df.displayName}}" value="{{df.displayName}}" placeholder="Enter Display Name">
<label for="validationCustom01">{{df.description}}</label>
<input type="text" class="form-control" id="validationCustom01" name="{{df.description}}" value="{{df.description}}" placeholder="Enter description">
<div class="invalid-feedback">
Please enter required fileds.
</div>
<!-- <div class="valid-feedback">
Looks good!
</div> -->
</div>
{% endfor %}
<button type="submit" class="btn btn-primary btn-red btn-block">SAVE</button>
</form>
What I am trying to achieve is.
Pass a variable form to the user to fill
And I get the result.
I can't tell what the input id/name would be because it's a variable.
But I am finding it difficult getting the value from the view.py file.
change
req.POST['{}'.format(d.description, False)]
to
req.POST.get('{}'.format(d.description, False))
I'm building a Django web-app where the user needs to upload a file. This file should go through a machine-learning alogritme after that the results will be presented on a different page.
right now it works if I have text fields present for every feature but when I want to upload a csv file(the csv file is called test.csv) put it in a pandas dataframe the resultpage doesn't show and it looks like the csv file isn't processed.
what it should do is if file is uploaded keep the uploaded file in memory process it and return the output on the results page.
HTML
{% extends "base.html" %}
{% block content %}
<div class="content">
<div class="row">
<div class="col-lg-4">
<div class="card card-tasks">
<h1> </h1>
<form action="{% url 'result' %}">
{% csrf_token %}
<p>temp_normal:</p>
<input class="form-control" type="text" name="temp_normal">
<br>
<p>hour:</p>
<input class="form-control" type="text" name="hour">
<br>
<p>hour_x:</p>
<input class="form-control" type="text" name="hour_x">
<br>
<p>hour_y:</p>
<input class="form-control" type="text" name="hour_y">
<br>
<input class="form-control" type="submit" value='Submit'>
</form>
</div>
</div>
<div class="col-lg-4">
<div class="card card-tasks">
<form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label>
<div class="col-md-8">
<input type="file" name="csv_file" id="csv_file" required="True" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">
<button class="btn btn-primary"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock content %}
views.py
def handle_uploaded_file(f):
with open('test.csv', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
# custom method for generating predictions
def getPredictions(data):
import pickle
model = pickle.load(open("test_model.sav", "rb"))
prediction = model.predict(data)
return prediction
#login_required
def result(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
data = form
data = pd.read_csv(data,header=0)
result = getPredictions(data)
return render(request, 'result.html', {'result': result})
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
try:
<form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal">
{% csrf_token %}
<div class="form-group">
<label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label>
<div class="col-md-8">
{{ form }}
</div>
</div>
<div class="form-group">
<div class="col-md-3 col-sm-3 col-xs-12 col-md-offset-3" style="margin-bottom:10px;">
<button class="btn btn-primary" type="submit"> <span class="glyphicon glyphicon-upload" style="margin-right:5px;"></span>Upload </button>
</div>
</div>
</form>
as we discussed for the view:
#login_required
def result(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
file = request.FILES['file']
handle_uploaded_file(file)
data = pd.read_csv(file,header=0)
result = getPredictions(data)
return render(request, 'result.html', {'result': result})
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
Dear all of the Django developer community, I am facing this below issue:
I try to update a db table data which has one field and one drop down field. But I only get basic field data and not drop down list data.
I request expert help me. How can I fix this issue?
Advanced Thanks For All
views.py
def update_brands(request, id):
brand = Brand.objects.get(id=id)
form = AddBrandForms(request.POST, instance=brand)
if form.is_valid():
form.save()
return redirect('/parts/brands')
return render(request, 'parts/edit_brands.html', {'brand': brand })
edit_brands.html
{% extends 'parts/base.html' %}
{% block content %}
<form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form">
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<input type="text" name="country" value="{{ brand.brand_name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<select id="cars" name="cars">
{% for db in dbf.all %}
<option value="{{ db.db}}">{{ db.db}}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock %}
try this
{% extends 'parts/base.html' %}
{% block content %}
<form method="post" action="/parts/update_brands/{{brand.id}}/" class="post-form">
{% csrf_token %}
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<input type="text" name="country" value="{{ brand.brand_name }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Country Name:</label>
<div class="col-sm-4">
<select id="cars" name="cars">
{% for car in brand.all %}
<option value="{{ car }}">{{ car }}</option>
{% endfor %}
</select>
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
{% endblock %}
I have problem with my code which is i try to submit my Event form in the models. But when i run the form it will show the whole form (and another thing is that it will not show the values in the select box of the rounds) and when i click on the the submit button it will through an error.Please help me out this.
VIEW SIDE CODE:--
def addevents(request):
if request.method=="POST":
name=request.POST['events']
est=request.POST['starttime']
eet=request.POST['endtime']
s=Event()
s.ename=name
s.event_start_time=est
s.event_end_time=eet
s.save()
cats = request.POST.getlist('cats')
for i in cats:
s.categories.add(Category.objects.get(id=i))
s.save()
roundd = request.POST.getlist('rround')
for j in roundd:
s.rounds.add(Round.objects.get(id=j))
s.save()
return render(request,'adminside/addevents.html')
else:
rounds = Round.objects.all()
categories = Category.objects.all()
return render(request,'adminside/addevents.html',{'categories':categories,'rounds':rounds})
MODELS SIDE:-
class Event(models.Model):
ename=models.CharField(max_length=200)
categories = models.ManyToManyField(Category)
event_data = models.DateField()
event_start_time = models.TimeField()
event_end_time = models.TimeField()
rounds = models.ManyToManyField(Round)
EVENT PAGE FORM:-
{% extends 'adminside/master.html' %}
{% block content %}
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Events</h4>
<p class="card-description"> All fields are Compulsory </p>
<form class="forms-sample" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="exampleInputEmail1">Add Event</label>
<input type="text" class="form-control" name="events" id="exampleInputEmail1" placeholder="Enter Event">
</div>
<div class="form-group">
<label>Categories:</label>
<select class="form-control" multiple name="cats">
{% for i in categories %}
<option value="{{ i.id }}">{{ i.cname }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Event Start Time</label>
<input type="text" class="form-control" name="starttime" id="exampleInputEmail1" placeholder="Enter Event Start Time">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Event End Time</label>
<input type="text" class="form-control" name="endtime" id="exampleInputEmail1" placeholder="Enter Event End Time">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Round Name</label>
<select class="form-control form-control-lg" id="exampleFormControlSelect1" multiple name="rround">
{% for i in rounds %}
<option value="{{i.id}}">{{i.round}}</option>
{% endfor %}
</select>
</div>
<button type="submit" value=Addme class="btn btn-success mr-2">Submit</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
{% endblock %}
in addevents view you need to add something in event_data before saving because this value do not accept null or modify your models.py
event_data = models.DateField()
modify this to default value like the current time
event_data = models.DateField(default=timezone.now)
hope this helps
I am trying to get the value of a textbox from views.py but its not working for some reason.
Below is my code
base.html
<form method="POST" role="form" >
{% csrf_token %}
<div class="tab-content">
<div class="tab-pane active" role="tabpanel" id="step1">
<div class="mobile-grids">
<div class="mobile-left text-center">
<img src="{% static 'images/mobile.png' %}" alt="" />
</div>
<div class="mobile-right">
<h4>Enter your mobile number</h4>
<!-- <label>+91</label><input type="text" name="mobile_number" class="mobile-text" value="asdfasd" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = '';}" required=""> -->
<label>+91</label><input type="text" name="mobile_number" class="mobile-text" value="" >
</div>
</div>
<ul class="list-inline pull-right">
<li><button type="button" class="mob-btn btn btn-primary btn-info-full" data-dismiss="modal">Finish</button></li>
</ul>
</div>
<div class="clearfix"></div>
</div>
</form>
views.py
def home(request):
mobile_number = request.POST.get('mobile_number')
print(mobile_number)
return render(request,"home.html", {'mobile_number': mobile_number})
I am getting None when I try to get the value of textbox mobile_number.
How can I get the correct value?
You are missing a submit-button (<input type="submit" value="submit"/>) from the from.
To see the value on the form after submitting it, change value=""on the mobile_number -row, to value="{{ mobile_number }}".
My solution
1. You have to set action in form field as your functon in view.py
<form class="forms-sample" name="form" action="{% url "update_size" %}" method="post">
You have make button type as submit.
<button type="Submit" value="Submit" name="Submit" class="btn btn-primary">
url.py
path('updatesize/', views.updatesize, name='update_size')
View.py
def updatesize(request):
if (request.method == 'POST'):
temp = request.POST.get('size_name')
print("==================form================",temp)
return redirect("/collection.html")