django returns MultiValueDictKeyError at /
'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself.
MultiValueDictKeyError at /
'q'
def dashboard(request):
photos = Photo.objects.all()
query = request.GET['q']
card_list = Photo.objects.filter(category__contains=query)
context = {'photos': photos, 'card_list':card_list}
return render(request, 'dashboard.html', context)
<div class="container">
<div class="row justify-content-center">
<form action="" method="GET">
<input type="text" name="q" class="form-control">
<br>
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
<br>
<div class="container">
<div class="row justify-content-center">
{% for photo in photos reversed %}
<div class="col-md-4">
<div class="card my-2">
<img class="image-thumbail" src="{{photo.image.url}}" alt="Card
image cap">
<div class="card-body">
<h2 style="color: yellowgreen; font-family: Arial, Helvetica,
sans-serif;">
{{photo.user.username.upper}}
</h2>
<br>
<h3>{{photo.category}}</h3>
<h4>{{photo.price}}</h4>
</div>
<a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn-
sm m-1">Buy Now</a>
</div>
</div>
{% empty %}
<h3>No Files...</h3>
{% endfor %}
</div>
</div>
try this
query = request.GET['q']
query = request.GET.get('q', '') # use get to access the q
The get() method returns the value of the item with the specified key.
Related
I'm trying to create a functionnality where the user is able to upload and delete some images on the fly. The deleting part works but not completely... it successfully deletes an image from my static folder, but for some reason it only deletes the first image it finds, and not the one that linked to the bootrap card.
For some reason it is not properly identifying the correct value and I can't figure out why :
1. Flask
#app.route('/deleteImg', methods=['GET', 'POST'])
def deleteImg(row):
if request.method == 'POST':
image_to_del = request.values.get('image_to_del', None)
print(f'image_to_del:{image_to_del}')
os.remove(os.path.join(UPLOAD_FOLDER,image_to_del))
return redirect('/uploadimg')
return render_template('uploadimg.html')
2. HTML
<form action="{{url_for('deleteImg')}}" method="POST">
<div class="row">
{% for row in pics %}
<div class="col-md-3 mt-3">
<div class="card">
<img src="{{ url_for('static', filename='pics/'+row)}}" alt="{{row}}" class="card_img_top" height="200">
<input type="hidden" name="image_to_del" class="image_to_del" value="{{row}}">Filename : {{row}}</input>
<h5 class="text-cent" >Filename : {{row}}</h5>
</div>
<div class="card-footer text-center">
<input type="submit" value="Delete" class="btn btn-success" />
</div>
</div>
{% endfor %}
</div>
</form>
I found this solution for those who might be interested. This is based on the work of "Cairocoders" Flask delete image from db
1. FLASK
#app.route('/deletelogo/<string:get_ig>', methods=['GET', 'POST'])
def deletelogo(get_ig):
print(f'get_ig :{get_ig}')
os.remove(os.path.join(LOGO_FOLDER,get_ig))
return redirect('/logoimg')
2. HTML
<div class="row">
{% for row in pics %}
<div class="col-md-3 mt-3">
<div class="card">
<img src="{{ url_for('static', filename='logo/'+row)}}" alt="{{row}}" class="card_img_top" height="200">
<input type="hidden" name="image_to_del" class="image_to_del" value="{{row}}">Filename : {{row}}</input>
<h5 class="text-cent" >Filename : {{row}}</h5>
</div>
<div class="card-footer text-center">
<td><p><span class="glyphicon glyphicon-trash"></span></p></td>
</div>
</div>
I'd like to get data from one form that has multiple textareas inside , In my views: 'compare_ingredients' I've tried requesting data from my form id 'compareform' also the textarea id 'ingredients', but when I enter something into one texture and click on submit it comes back as 'None' when I print. Here is my html and views:
html :
<div class="container-fluid">
<h4>Please enter in your ingredients:</h4>
<h6>(Seperate each item by comma)</h6>
<br>
<button class="add_item">Add Item</button>
<br>
<div class="row row-cols-1 row-cols-md-2 mx-auto">
<form action="{% url 'compare_ingredients' %}" method="POST" name="compareform" id="compare">
{% csrf_token %}
<br>
<button type="submit" class="btn btn-info sub_btn">Submit</button>
<button type="submit" class="btn btn-secondary back_button">
Back
</button>
<br>
<br>
<div class="row form_row">
<div class="col mb-4">
<h5>Item 1</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients1" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
<div class="col mb-4">
<h5>Item 2</h5>
<div class="card form_card">
<div class="card-body compare_cardbody">
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compareform"></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
views.py:
def compare_ingredients(request):
if request.method == "POST":
ingredients = request.POST.get('compareform')
print(ingredients)
return render(request, 'result/compare.html')
ok, I figured it out , the problem was in the html textarea I had the name of the form as 'compareform' when it should have been 'compare' :
<textarea name="ingredients2" id="ingredients" cols="30" rows="10" form="compare"></textarea>
then in my views I did:
ingredients1 = request.POST.get('ingredients1')
I want to display card first which have status=True, so how can i arrange it by status in my views.py or in template
this is my views.py:
def myItem(request):
context = {}
if Item.objects.filter(status=True).exists():
context['data'] = Item.objects.all()#here i am taking all data but i want to arrange it so that which data have status=True will come first.
else:
context['data'] = Item.objects.all()
context['data_false'] = True
return render(request,'frontend/myeoffice.html',context)
this is in my Template:
{% for i in data %}
{% if i.status %}
<div class="col-xl-4">
<div class="card shadow-sm p-4">
<div class="card-header p-0 text-center">
<h2 class="title">{{i.name}}</h2>
</div>
<div class="content text-break p-2">
<p class="copy">{{i.description|truncatechars:100}}</p>
</div>
<div class="card-footer text-left p-0">
<button class="btn btn-primary m-3">View</button>
</div>
</div>
</div>
{% else %}
<div class="col-xl-4">
<div class="card shadow-sm p-4" data-toggle="modal" data-target=".bd-example-modal-lg" style="background: #ccc;">
<div class="card-header p-0 text-center">
<h2 class="title">{{i.name}}</h2>
</div>
<div class="content text-break p-2">
<p class="copy">{{i.description|truncatechars:100}}</p>
</div>
<div class="card-footer text-left p-0">
<button class="btn btn-primary disabled m-3" data-toggle="modal" data-target=".bd-example-modal-lg">
View
</button>
</div>
</div>
</div>
{% endif %}
{% endfor %}
NOTE : I want data which have both status=False and status=True but order should be True first and False last
You want to do this with the query to get the first one out of the result where status is True.
context['data'] = Item.objects.filter(status=True).first()
This will give you the first result with this status. Or if you want all results and order it by the status then do this:
context['data'] = Item.objects.all().order_by('-status')
You can arrange the results via the order function:
def myItem(request):
context = Item.objects.all().order_by('-status')
return render(request,'frontend/myeoffice.html',context)
The - in -status is used to reverse order.
I am trying to delete django model multiple objects using html checkboxes but i can't. Kindly guide me what I need to do complete my this task.
I try the following code for this purpose but i failed.
views.py
class DeleteProducts(SuccessMessageMixin, View):
success_url = reverse_lazy('stock:stock')
success_message = "Products are deleted successfully."
def post(self, request, *args, **kwargs):
products = self.request.POST.getlist('product')
Product.objects.filter(pk__in=products).delete()
messages.success(self.request, self.success_message, extra_tags='alert-danger')
return redirect('stock:stock')
In template i used checkboxes prefectly or not??
template.html
<form method="POST" action="{% url 'stock:deleteproducts' %}">
{% csrf_token %}
{% for product in page_obj %}
<div class="row" >
<input type="checkbox" value="{{ product.id }}">
<div class="col-sm-2" >
<h5>{{ product.id }}</h5>
<img src="{{ product.Picture.url }}" height="120px" />
</div>
<div class="col-sm-4" >
<h5><u>Product Name</u>: {{ product.pro_name }}</h5>
<h6><u>Company Name</u>: {{product.companyName}}</h6>
<div class="row" >
<div class="col-sm" >
<p>Purchase Price: <b>{{product.Purchase_Price}}</b></p>
</div>
<div class="col-sm" >
<p class="pt-0">Sale Price: <b>{{product.Sale_Price}}</b> </p>
</div>
</div>
<div class="row" >
<div class="col-sm" >
<p>Quantity <b>{{product.Quantity}}</b></p>
</div>
<div class="col-sm" >
<p> Added By: <b>{{product.saler}}</b> </p>
</div>
</div>
</div>
<div class="col-sm-4" >
<p><b>Added Date</b>:{{ product.pub_date }}</p>
<hr/>
<center>
<a href="{% url 'stock:editproduct' product.id %}" class="btn btn-success" >Edit</a>
</center>
</div>
</div>
<hr/>
{% endfor %}
<input type="submit" class="btn btn-danger" value="Delete" >
</form>
urls.py
path('delete/', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'),
You need to assign name="product" attribute to checkboxes since you are trying to get it with self.request.POST.getlist('product'):
<input type="checkbox" value="{{ product.id }}" name="product">
I have a custom form validation that runs on my popup window form. If the form validation occurs i get a bad request error which is what i have programmed in my views.py . How do i render it so the user stays on the form and the validation message displays. Thanks for the help. Here is my code.
#login_required
def K8_Points_Classroom(request):
#context_from_k8_points = request.session['k8_points_context']
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
else:
return HttpResponseBadRequest("Bad Request")
else:
return render(request, 'points/k8_points_classroom.html', {'form': form} )
Updated form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% crispy K8Points_ClassroomForm %}
{% load static %}
{% block content %}
<br>
<h2>{% load static %}
<img src="{% static 'forms/star.png' %}" alt="chain" height="62" width="62"> {{class_name}}</h2>
<br>
<br>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<!-- Start Date -->
<div class="container">
<div class="container">
<div class='row'>
<div class="col-4">
<p> Recording Data as User : {{user.username}} </p>
</div>
</div>
<div class='row'>
<div class = "col-2">
{{form.date|as_crispy_field }}
</div>
<div class = "col-2">
{{form.week_of|as_crispy_field }}
</div>
<div class = "col-2">
{{form.day|as_crispy_field }}
</div>
</div>
</div>
</form>
<div class="jumbotron" align="middle">
<img src="{% static 'forms/levelup.png' %}" alt="levelup" height="120" width= "120">
<h1>My Students</h1>
<!-- Line Break -->
<hr style="border: 1px solid black;"/>
<!-- Line Break -->
<div class="row mb-3">
{% for i in students%}
<div class="col-md-4 themed-grid-col"><h2>{{i.student_name}}</h2>
<p align="left"> Today's Score: {{total}}</p>
<h4>
<button type="button" class="btn btn-primary btn-lg btn-block" data-toggle="modal"
data-target="#PointsBox{{ student.pk }}">Level Up
</button>
</h4>
<div id="PointsBox{{ student.pk }}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img src="{% static 'forms/star.png' %}" align="left" alt="chain" height="42"
width="42">
<h4 class="modal-title">Points Confirmation </h4>
<button type="button" class="close" data-dismiss="modal"> ×</button>
</div>
<div class="modal-body">
<h6>
<div class="modal-body">Please add the selected points for the current
student.</div>
</h6>
<form action="/points/k8_points_classroom" method="POST">
{% csrf_token %}
<div class="form-row" align='left'>
<div class="col-7">
{{form.class_name|as_crispy_field }}
<input type="student_name" class="form-control" value ="{{i}}" >
{{form.time_frame|as_crispy_field }}
</div>
</div>
<div class="form-row">
<div class="col-3" align='left'>
{{form.behavior|as_crispy_field }}
{{form.academic|as_crispy_field }}
<button type="submit" class="btn btn-success" ><i
class="fas fa-star"></i> Level Up
</button>
</div>
</div>
</div>
<div class="modal-foot"></div>
</div>
</div>
</div>
</div>
</form>
{% endfor %}
{% endblock %}
You can't return a bad response if the form is invalid. Instead, render the page again with the invalid form and in the temolate you will be able to render the errors. Try starting rendering the form just using {{ form.as_p }} and you will see the errors. The form errors are in form.errors and each field has its own errors, you can access to them form.field.erorrs
if request.method == 'POST':
form = K8Points_ClassroomForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.save()
class_name = form.cleaned_data.get('class_name')
getstudents = Student.objects.filter(class_name = class_name)
students = getstudents.all()
form = K8Points_ClassroomForm()
context = {'form': form ,'students' : students, 'class_name': class_name,}
return render(request,'points/k8_points_classroom.html', context)
return render(request, 'points/k8_points_classroom.html', {'form': form} )