How decode base64 image PIL - python

I've some trouble with decode base64 image in my django project.
I am passing the image to views like this (I've some form. I'm passing image to function from views.py through this form):
{% extends "blog/base.html" %}
{% block content %}
<div id="content" class="container-fluid d-flex h-100 justify-content-center align-items-center p-0">
<div class="row bg-white shadow-sm">
<div class="col border rounded p-4">
<h3 class="text-center mb-4">Диагноз</h3>
<form action="" id="post-form">
<div class="form-group">
<p align="center" style="font-weight:bold"><label for="exampleFormControlFile1">Снимок</label></p>
<input type="file" class="form-control-file" id="image-selector">
</div>
</form>
<p align="center" style="font-weight:bold">Predictions</p>
<p>Covid: <span id="covid-prediction"></span></p>
<p>Health: <span id="health-prediction"></span></p>
<table align="center">
<tr>
<td>
<img id="selected-image" class="img-thumbnail" width="300px" height="300px" src=""/>
</td>
</tr>
<tr align="center">
<td>
<button id="predict-button" type="submit" class="btn btn-primary">Predict</button>
</td>
</tr>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
let base64Image;
$("#image-selector").change(function() {
let reader = new FileReader();
reader.onload = function(e) {
let dataURL = reader.result;
$("#selected-image").attr("src", dataURL);
base64Image = dataURL.replace("data:image/jpeg;base64,","");
console.log(base64Image);
}
reader.readAsDataURL($("#image-selector")[0].files[0]);
$("#covid-prediction").text("");
$("#health-prediction").text("");
});
$("#predict-button").click(function(event){
let message = base64Image;
console.log(message);
$.post("{% url "diagnose:submit_prediction" %}", message, function(response){
$("#covid-prediction").text(response.prediction.covid.toFixed(3) * 100 + "%");
$("#health-prediction").text(response.prediction.health.toFixed(3) * 100 + "%");
console.log(response);
});
});
</script>
And in my views file I'm trying to decode this image like this:
#csrf_exempt
def predict_chances(request):
myDict = request.POST.dict()
encoded = 0
for k in myDict:
encoded = k
print(encoded)
im = Image.open(io.BytesIO(base64.b64decode(encoded)))
processed_image = preprocess_image(image, target_size=(224, 224))
prediction = model.predict(processed_image).tolist()
response = {
'prediction': {
'covid': prediction[0][0],
'health': prediction[0][1]
}
}
return jsonify(response)
But this is not working. I get this error:
binascii.Error: Incorrect padding
How I can fix this?

Related

How to take the value from the field and send it to the Flask code for use in the updated page

Have a good day!
I don't know much about Flask
I try to depict insert several (two) objects on the page and embed add the ability (so that you can) update these objects.
There is a main element on the page - the choice of a date range.
When you select a start date and an end date and click the button in the same way (two objects should be updated).
The first object is a table. The table (object) is updated.
The second object is a graph. This object is not updated.
What can be done to update the second object (chart)?
I would be extremely grateful for any help.
It's HTML
<div class="row">
<div class="col-md-3">
<input type="text" name="From" id="From" class="form-control" placeholder="From Date"/>
</div>
<div class="col-md-3">
<input type="text" name="to" id="to" class="form-control" placeholder="To Date"/>
</div>
<div class="col-md-6">
<input type="button" name="range" id="range" value="Range" class="btn btn-success"/>
</div>
</div>
<div id="purchase_order"></div>
<hr>
<div class="row" style="align-content: center">
<div class="text" style="align-content: center">
</div>
<div class="outer-wrapper" style="align-content: center">
<div class="table-wrapper" id="table-wrapper" style="align-content: center">
<table>
<thead>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div>
<canvas id="myChart" width="800px" style="align-content: center"></canvas>
</div>
</div>
<div class="col-md-1">
</div>
</div>
it's script
<script>
$(document).ready(function (){
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(function (){
$("#From").datepicker();
$("#to").datepicker();
});
$('#range').click(function (){
var From = $('#From').val();
var to = $('#to').val();
if (From != '' && to != '')
{
$.ajax({
url:"/range",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#table-wrapper').html(data);
$('#table-wrapper').append(data.htmlresponse);
}
});
$.ajax({
url:"/range2",
method:"POST",
data:{From:From, to:to},
success:function (data)
{
$('#myChart').html(data);
$('#myChart').append(data.htmlresponse2);
}
});
}
else
{
alert("Please Select the Date")
}
});
});
</script>
it's Flask code
#app.route('/', methods=['GET','POST'])
#app.route('/index')
def home_page(): # put application's code here
if request.method=="POST":
upload_excel=request.files['upload_excel']
if upload_excel.filename != '':
filepath=os.path.join(app.config["UPLOAD_FOLDER"],upload_excel.filename)
upload_excel.save(filepath)
data=pd.read_excel(upload_excel)
data.to_sql('kotel', con=db.engine, if_exists="append", index=False)
return print(data)
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = df['date'].dt.round('2min')
y_data = df['tnv'].tolist()
x_data = df['date'].tolist()
print(y_data)
type(y_data)
print(x_data)
df_graph = df.copy()
df_graph.drop(df_graph.columns[[0, 1, 2]], axis=1, inplace=True)
print(df_graph)
# df['date'] = pd.to_datetime(df['date'], format="%Y.%d.%B %H")
return render_template('index new.html', column_names=df.columns.values, row_data=list(df.values.tolist()), column_names_graph=df_graph.columns.values, os_y = y_data, os_x = x_data)
#app.route("/range", methods=["POST","GET"])
def range():
if request.method == 'POST':
From = request.form['From']
to = request.form['to']
df = pd.read_sql('select * from kotel', con=db.engine)
df['date'] = pd.to_datetime(df['date'])
df = df.loc[(df['date'] >= From) & (df['date'] <= to)]
df['date'] = df['date'].dt.round('2min')
return jsonify({'htmlresponse': render_template('response.html', column_names=df.columns.values, row_data=list(df.values.tolist()))}), df
#app.route("/range2", methods=["POST","GET"])
def range2():
df_new = pd.read_sql('select * from table_1', con=db.engine)
y_data = df_new['temper'].tolist()
x_data = df_new['rashod'].tolist()
return jsonify({'htmlresponse2': render_template('response2.html', os_y = y_data, os_x = x_data)})
it's extended html 1 add
<table>
<thead>
{% for col in column_names %}
<th>{{col}}</th>
{% endfor %}
</thead>
<tbody>
{% for row in row_data %}
<tr>
{% for cell in row %}
<td>{{ cell }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
it's extended html 2 add
<script>
const labels = [{% for item in os_x %}
"{{ item }}",
{% endfor %}];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [{% for item in os_y %}
{{ item }},
{% endfor %}],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
</script>
<script>
const myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
I would really like to be able (so that I can) take a value variable from a form field (dropdown ) and send it to the Flask code so that I can use it in the updated page.
image screen
image screen

Django No Reverse Match Error - Nothing is working

When rendering a new page, the html form action on that new page is stopping the page from being rendered... even though it has nothing to do with the page itself being rendered (if I remove that one line of HTML code, the page loads just fine). I've been working on solving this problem for over 3 days, tried hundreds of possible solutions, nothing works. Please help
This is the error:
NoReverseMatch at /newgallery/rodneyadmin
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Request Method: GET
Request URL: http://127.0.0.1:8000/newgallery/rodneyadmin
Django Version: 4.0
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
Exception Location: /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/urls/resolvers.py, line 729, in _reverse_with_prefix
Python Executable: /Library/Frameworks/Python.framework/Versions/3.9/bin/python3
Python Version: 3.9.7
Python Path:
['/Users/rodneyrussell/Desktop/github/Capstone/Capstone',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload',
'/Users/rodneyrussell/Library/Python/3.9/lib/python/site-packages',
'/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']
Server time: Thu, 10 Feb 2022 16:41:21 -0500
Error during template rendering
In template /Users/rodneyrussell/Desktop/github/Capstone/Capstone/templates/galleries/newgallery.html, error at line 21
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found. 1 pattern(s) tried: ['editgallery/(?P<username>[^/]+)/(?P<new_gallery>[0-9]+)\\Z']
11 Create new gallery
12 </h1>
13 </div>
14 </div>
15
16
17 <div class="row mb-3 d-flex justify-content-center">
18
19 <div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">
20
21 <form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
22
23 {% csrf_token %}
24
25
26 <div class="form-group mb-5">
27 <label style="margin-right: 20px;">Public Gallery</label>
28 {{form.public_gallery}}
29 </div>
30
31 <div class="form-group mb-5">
This is the line of code being highlighted as cause for error (form action):
<form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
Views.py:
#login_required
def newgallery(request, username):
if request.method == 'GET':
form = NewGalleryForm
context = {
'form': form,
'username': username,
}
return render(request, 'galleries/newgallery.html', context)
def editgallery(request, username):
if request.method == "POST":
form = NewGalleryForm(request.POST)
if form.is_valid():
new_gallery = form.save(commit = False)
## connect the new gallery with the user (foreign key)
new_gallery.user = request.user
new_gallery.save()
url = "https://api.opensea.io/api/v1/assets?order_direction=desc&offset=0&limit=5"
params={'owner': new_gallery.wallett_address}
headers = {
"Accept": "application/json",
"X-API-KEY": ""
}
response = requests.request("GET", url, headers=headers, params=params)
response = response.json()["assets"]
list_of_nfts = []
for dictionary in response:
token_id = dictionary["token_id"]
token_address = dictionary["asset_contract"]["address"]
contract_address = 'https://api.opensea.io/api/v1/asset/' + token_address + '/' + token_id + '/'
name = dictionary["name"]
if len(name) > 50:
name = (name[:50] + '...')
nft_created_date = dictionary["asset_contract"]["created_date"]
nft_created_date = nft_created_date[:10]
nft_created_date = datetime.strptime(nft_created_date, '%Y-%m-%d').strftime('%m/%d/%Y')
image = dictionary["image_url"]
description = dictionary["description"]
if description is not None and '*' in description:
head, sep, tail = description.partition('*')
description = head
if description is not None and len(description) > 50:
description = (description[:150] + '...')
if isinstance(description, str) != True:
description = 'No description provided'
link = dictionary["permalink"]
nft_dict = {
'contract_address': contract_address,
'name': name,
'image': image,
'description': description,
'link': link,
'nft_created_date': nft_created_date,
}
list_of_nfts.append(nft_dict)
context = {
'new_gallery': new_gallery,
'list_of_nfts': list_of_nfts,
'raw_nft_data': json.dumps(list_of_nfts),
'new_gallery_name': new_gallery.gallery_name,
'user': new_gallery.user,
username:username,
}
return render(request, 'galleries/editgallery.html', context)
New Gallery HTML (page where user enters basic information regarding New Gallery that he or she is creating... when this form is submitted, the user is brought to a page where they can edit the gallery that was just created (by edit, I mean add new NFT's to that gallery):
<div class="row mb-3">
<div class="col-lg-12 col-sm-12 text-primary d-flex justify-content-center align-items-center">
<h1
class="homepagetitle mt-4 mb-5"
style="font-size: 2.4rem; color: rgb(231, 114, 208)"
>
Create new gallery
</h1>
</div>
</div>
<div class="row mb-3 d-flex justify-content-center">
<div class="col-lg-4 col-med-8 col-sm-8 text-primary" style="height: fit-content;">
<form action="{% url 'gallery_app:editgallery' user.username new_gallery.id %} " style="font-weight: bolder;" enctype='multipart/form-data' method='POST' class='gap-2'>
{% csrf_token %}
<div class="form-group mb-5">
<label style="margin-right: 20px;">Public Gallery</label>
{{form.public_gallery}}
</div>
<div class="form-group mb-5">
<label>Gallery Name </label>
{{form.gallery_name}}
</div>
<div class="form-group mb-5">
<label>Wallett Address</label>
<span class="hovertext" style="color: rgb(231, 114, 208); font-weight: normal;" data-hover="You will be adding NFT's from this wallet. Max wallet size: 50 NFT's">?</span>
{{form.wallett_address}}
</div>
<div class="form-group mb-5">
<label style="margin-right: 20px;">Category </label>
{{form.gallery_category}}
</div>
<button
type="submit"
class="btn btn-dark mt-4 mb-4"
style="
font-size: 1.1rem;
height: 50px;
width:fit-content;
"
>
Add NFT's &nbsp <i class="far fa-arrow-alt-circle-right"></i>
</button>
</form>
</div>
</div>
User Profile HTML (page where user clicks on an a tag to bring them to the the New Gallery HTML (the other HTML I have listed above). That is when the code breaks and gives that error. The url in that a tag is href="{% url 'gallery_app:newgallery' user.username %}":
<h1 class="homepagetitle mt-4 mb-5 d-flex justify-content-center align-items-center" style="font-size: 2.4rem; color: rgb(231, 114, 208);">
Hello&nbsp
<span style="font-size: 2.4rem; color: rgb(231, 114, 208);"
>{{user.username}}&nbsp<i class="far fa-hand-paper" style="font-size: 2.4rem; color: rgb(231, 114, 208);"></i></span
>
</h1>
{% endif %}
<div class="row col-12">
<div class="col-lg-6">
<div class="pt-3 profile-image">
<img
src="{% static user.avatar.url %}"
alt="{{user.username}}'s avatar"
class="rounded-circle shadow"
height="300"
width="275"
/>
</div>
{% if request.user == user %}
<span>
<div class="editicon">
<a
href="{% url 'users_app:update' user.username %}"
style="
color: rgb(226, 81, 197);
-webkit-text-stroke: 1px black;
text-decoration: none;
"
>
<i class="fas fa-user-edit"></i>
</a>
</div>
</span>
{% endif %}
<!-- 'users_app:update' user.username -->
<table class="table profile-margin">
<tbody>
{% if request.user == user %}
<tr>
<th scope="row"></th>
<td>Name:</td>
<td>{{user.first_name}} {{user.last_name}}</td>
</tr>
<tr>
<th scope="row"></th>
<td>Email:</td>
<td>{{user.email}}</td>
</tr>
{% endif %}
<tr>
<th scope="row"></th>
<td>Username:</td>
<td>{{user.username}}</td>
</tr>
<tr>
<th scope="row"></th>
<td>Profile created:</td>
<td>{{user.date_joined|date}}</td>
</tr>
<tr>
<th scope="row"></th>
<td>Galleries:</td>
<td>0</td>
</tr>
<tr>
<th scope="row"></th>
<td>Followers:</td>
<td>0</td>
</tr>
<tr>
<th scope="row"></th>
<td>Following:</td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<div class="col-lg-6">
{% if request.user.is_authenticated %}
<h3 class=" d-flex homepagetitle" style="justify-content:center; margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
<i><a class="homepagetitle far fa-plus-square" href="{% url 'gallery_app:newgallery' user.username %}" style="text-decoration: none; font-size: 2.2rem; color: rgb(231, 114, 208); position:relative; left: -70px; font-size: 2rem;"></i></a>
Your Galleries:
</h3>
{% else %}
<h3 class=" d-flex justify-content-center homepagetitle" style="margin-top: 30px; margin-bottom: 0px; padding:10px; height: 75px; font-size: 2.2rem; color: rgb(231, 114, 208);">
{{user.username}}'s Galleries:
</h3>
{% endif %}
<div class='user-galleries d-flex justify-content-center' style="background-color: rgb(247, 229, 243); border-radius: 8px;">
<div class="gallery-posts py-3">
<table class="table profile-margin" style="color:rgb(231, 114, 208); font-weight: bolder;">
<tbody>
{% for gallery in user.newgallery.all %}
<tr>
<th scope="row"></th>
<td>{{ gallery.gallery_name }}</td>
<td>NFT's: 0</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
Urls.py:
app_name = 'gallery_app'
urlpatterns = [
path('newgallery/<str:username>', views.newgallery, name='newgallery'),
path('editgallery/<str:username>/<int:gallery_id>', views.editgallery, name='editgallery'),
path('galleryview/<str:username>/<int:gallery_id>', views.galleryview, name='galleryview'),
]
It looks like the url argument new_gallery.id is empty when you render the html template.
update: so the template is called from view newgallery.
In your original code there is 2 things to change:
to instantiate the form please add () after NewGalleryForm. Without you just handover a link to the class.
in this view/template you do not yet have an instance of newgallery (just the form). So you can not use newgaller.id. Implement a POST branch in newgallery to save it and remove newgallery.id from the form action and point the action back to newgallery view.
after saving you have a newgallery instance with an id and you can call the edit view if you need to with newgallery in the context
def newgallery(request, username):
if request.method == 'POST':
# save newgallery here
if request.method == 'GET':
form = NewGalleryForm()
context = {
'form': form,
'username': username,
}
return render(request, 'galleries/newgallery.html', context)
<form action="{% url 'gallery_app:newgallery' user.username %} " style .... >
You need to pass the gallery as context into the view that has the edit form. I don't see in the views that you posted that you have a detail view but I do see a detail view url. So I'm assuming you're passing the edit form to your create view instead? That view doesn't return a context with new_gallery as a context variable. I would create a detail view for your gallery instead and pass the edit form, user and gallery as context to the template.
Reverse for 'editgallery' with arguments '('rodneyadmin', '')' not found.
New context
def galleryview(request, username, gallery_id):
# Logic
gallery = get_object_or_404(Gallery, pk=gallery_id)
context = {
'form': form,
'username': username,
'new_gallery': gallery,
}
# return an html response with context
Also, when you instantiate an unbound form you should add parenthesis after it.
form = NewGalleryForm()

How can I append data from html to array in views from a button?

I'm trying to build a website that generates a power hour style video from a list of music videos that the user selects by searching through the youtube api. I'm having trouble figuring out how to append selected videos to a list (addedVideos) in view.py from a button (add) in my html. I need to append each added video to a list so I can display them and loop through them in an embedded youtube player. This is my first django project so I don't have a good understanding of what the potential problems could be. index.html and views.py below:
views.py
import requests
from isodate import parse_duration
from django.conf import settings
from django.shortcuts import render, redirect
def index(request):
addedVideos = []
videos = []
if request.method == 'POST':
search_url = 'https://www.googleapis.com/youtube/v3/search'
video_url = 'https://www.googleapis.com/youtube/v3/videos'
search_params = {
'part' : 'snippet',
'q' : request.POST['search'],
'key' : settings.YOUTUBE_DATA_API_KEY,
'maxResults' : 3,
'type' : 'video'
}
#print(request.POST['submit'])
r = requests.get(search_url, params=search_params)
#print(r)
results = r.json()['items']
#print(results)
video_ids = []
for result in results:
video_ids.append(result['id']['videoId'])
if request.POST['submit'] == 'lucky':
return redirect(f'https://www.youtube.com/watch?v={ video_ids[0] }')
video_params = {
'key' : settings.YOUTUBE_DATA_API_KEY,
'part' : 'snippet,contentDetails',
'id' : ','.join(video_ids),
'maxResults' : 3
}
r = requests.get(video_url, params=video_params)
results = r.json()['items']
for result in results:
video_data = {
'title' : result['snippet']['title'],
'id' : result['id'],
'url' : f'https://www.youtube.com/watch?v={ result["id"] }',
'duration' : int(parse_duration(result['contentDetails']['duration']).total_seconds() // 60),
'thumbnail' : result['snippet']['thumbnails']['high']['url']
}
videos.append(video_data)
if request.POST['add'] == 'addValue':
print("add clicked")
context = {
'videos' : videos,
'addedVideos': addedVideos
}
return render(request, 'search/index.html', context)
index.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Search YouTube</title>
<!-- Bootstrap core CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
<!-- Custom styles for this template -->
<link href="{% static 'search/album.css' %}" rel="stylesheet">
</head>
<body>
<main role="main">
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Build Your Power Hour</h1>
<p class="lead text-muted">Select music videos to add to your power hour</p>
<form method="POST">
<div class="input-group mb-3">
{% csrf_token %}
<input type="text" name="search" class="form-control" aria-label="Username">
</div>
<p>
<button type="submit" name="submit" value="search" class="btn btn-primary my-2">YouTube Search</button>
<button type="submit" name="submit" value="lucky" class="btn btn-secondary my-2">I'm Feeling Lucky</button>
</p>
</form>
</div>
</section>
<div class="album py-5 bg-light">
<div class="container">
<div class="row">
{% for video in videos %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<img class="bd-placeholder-img card-img-top" width="100%" height="225" src="{{ video.thumbnail }}" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail"></img>
<div class="card-body">
<p class="card-text">{{ video.title }}</p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<form method="POST">
{% csrf_token %}
<button type="submit" name="add" value="addValue" id='{{ video }}' class="btn btn-sm btn-outline-secondary">Add</button>
</form>
</div>
<small class="text-muted">{{ video.duration }} mins</small>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</main>
</body>
</html>
Running this as is gives a MultiValueDictKeyError at 'q' : request.POST['search'],
Any help would be appreciated, thanks.
You should put / in front of search/index.html instead of search/index.html.
And you don't have to have the https:// you can just put // instead.

AJAX unable to define the key's method in Django

First off, sorry for the odd phrasing of the title.
I currently have a webapp that allows users to order food from a resturant. In the menu html I currently have the following snippet.
{% if latest_order %}
<table class="table" id="checkout-table">
<thead class="thead-dark">
<tr>
<th scope="col"></th>
<th scope="col">YOUR</th>
<th scope="col">CART</th>
<th scope="col"></th>
</tr>
</thead>
{% for order in latest_order %}
<tr>
<td>{{ order.order_name }}</td>
<td class="change-quantity">
<form method="post">
{% csrf_token %}
<div class="row">
<div class="col-sm">
<button type="submit" name="remove_quantity" value="{{ order.id }}"
class="mr-3 btn btn-outline-info">-</button>
</div>
<div class="col-sm">
{{ order.order_quantity }}
</div>
<div class="col-sm">
<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn
btn-outline-info">+</button>
</div>
</div>
</form>
</td>
<td>${{ order.order_individual_price }}</td>
in my JS I have the following AJAX code running
$(document).ready(function(){
$(".ramen").click(function(event){
event.preventDefault()
var serializedData = $("#ramen-form").serialize()
$.ajax({
url: $("ramen-form").data("url"),
data: serializedData,
type: 'post',
success: function(response) {
$("#checkout-table").append('<tr><td>' + response.new_order.order_name + '</td><td class="change-quantity">' +
'<form method="post">{% csrf_token %}<div class="row"><div class="col-sm">' +
'<button type="submit" name="remove_quantity" value="{{ order.id }}"class="mr-3 btn btn-outline-info">-</button>' +
'</div><div class="col-sm">'+ response.new_order.order_quantity +'</div><div class="col-sm">' +
'<button type="submit" name="add_quantity" value="{{ order.id }}" class="ml-3 btn btn-outline-info">+</button>' +
'</div></div></form></td><td>$'+ response.new_order.order_individual_price +'</td><form method="post">{% csrf_token %}<th>' +
'<button type="submit" name="delete" value="{{ order.id }}" class="btn btn-danger">Delete Item</button></th></form></tr>')
}
})
});
})
In my views.py I have the following to return a JsonResponse
get_price = menu_name.Menu_price
get_desc = menu_name.Menu_Desc
new_order = Order.objects.create(
customer=request.user,
order_name=menu_name,
order_individual_price=get_price,
order_default_price=get_price,
order_desc = get_desc,
)
return JsonResponse({'new_order':model_to_dict(new_order)}, status=200)
AJAX returns the following error after I try to add an item to cart
I think the problem is you don't parse the response. So, JQuery doesn't read it becase it is a string, not JSON. You might add the following to your AJAX call to parse it automatically:
$.ajax({
...
dataType: 'json',
success: function(response) {
...
}
}
Since you're using JQuery, you might also use $.parseJSON() to parse response.

Reverse for `view` with arguments '('',)' not found. 1 pattern(s) tried: `[u'bms/update/(?P<id>[0-9]+)/$']`

This is my update view which I'm using to get pre-populated form. Although this is also not working.
def update(request, id):
item = get_object_or_404(BookEntry, id=id)
if request.method=="POST":
form = UpdateForm(request.POST, instance=item)
if form.is_valid():
post=form.save(commit=False)
post.save()
return HttpResponseRedirect(reverse('bms:index'), id)
else:
form=EntryForm(instance=item)
return HttpResponseRedirect(reverse('bms:index'), id)
return render(request, 'index.html', {'form':form})
This is my urls.py
url(r'^update/(?P<id>[0-9]+)/$', views.update, name='update'),
This is the error that I'm getting again and again:
NoReverseMatch at /bms/
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: [u'bms/update/(?P[0-9]+)/$']
I'm not sure if passing the url in right way. This is what i'm doing:
<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
When I look at traceback, it's showing something's wrong in above line and this line:
return render(request, "bms/index.html", context)
This is my index view:
def index(request):
context = {}
book_detail = BookEntry.objects.all()
context.update({
'book_detail': book_detail
})
response = {"status": False, "errors": []}
if request.is_ajax():
id = request.POST['id']
csrf_token = request.POST['csrfmiddlewaretoken']
response = {}
response['status'] = False
book = BookEntry.objects.filter(id=id).first()
context = {
"book": book,
"csrf_token": csrf_token
}
template = render_to_string("bms/index.html", context)
response['template'] = template
response['status'] = True
return HttpResponse(json.dumps(response), content_type="applicaton/json")
return render(request, "bms/index.html", context)
My index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Raleway">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function update_entry(id) {
var id = id
$.ajax({
url: "{% url 'bms:index' %}",
type: "POST",
data:{
'csrfmiddlewaretoken': '{{ csrf_token }}',
'id' : id,
},
success: function(response){
$("#updateform").modal("show");
}
});
}
function update_property(id) {
window.location.replace("/bms/update" + id+"/");
}
</script>
<style>
body{
font-family: Raleway;
}
</style>
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Details of Books</h1>
</div>
<table class = "table table-bordered table-hover">
<tr>
<th>S No.:</th>
<th>Title:</th>
<th>Author:</th>
<th>Edition:</th>
<th>Publisher:</th>
<th>Genre:</th>
<th>Detail:</th>
<th>Language:</th>
<th>Price:</th>
<th>ISBN:</th>
<th>Action:</th>
</tr>
{% for item in book_detail %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ item.title }}</td>
<td>{{ item.author }}</td>
<td>{{ item.edition }}</td>
<td>{{ item.publisher }}</td>
<td>{{ item.genre }}</td>
<td>{{ item.detail }}</td>
<td>{{ item.language }}</td>
<td>{{ item.price }}</td>
<td>{{ item.isbn }}</td>
<td>
<a data-href="bms:update({{item.id}})" onclick="update_entry({{item.id}})" class="btn btn-warning" data-toggle="modal">
<span class = "glyphicon glyphicon-pencil"></span> Edit
</a>
</td>
</tr>
{% endfor %}
</table>
<div class="modal fade" id="updateform" role="dialog">
<div class="modal-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss="modal">×</button>
<h3 class="modal-title">
<b>Update Details</b>
</h3>
</div>
<div class = "modal-body">
<form action="{% url 'bms:update' book.id %}" id="updateform" name="updateform" method="POST">
{% csrf_token%}
<div class = "form-group">
<label for = "title">
Title:
</label>
<input class = "form-control" id="book_title" type = "text" name="title" value="{{ book.title }}">
</div>
<div class="form-group">
<label for = "author">
Author:
</label>
<input id="book_author" class = 'form-control' type = "text" name="author" value="{{ book.author }}">
</div>
<div class = "form-group">
<label for = "edition">
Edition:
</label>
<input id="book_edition" type = "text" class = 'form-control' name="edition" value="{{ book.edition }}">
</div>
<div class = "form-group">
<label for ="publisher">
Publisher:
</label>
<input id="book_publisher" type = "text" name="publisher" class = 'form-control' value="{{ book.publisher }}"/>
</div>
<div class = "form-group">
<label for ="genre">
Genre:
</label>
<input id="book_genre" type = "text" name="genre" class = 'form-control' value="{{ book.genre }}"/>
</div>
<div class = "form-group">
<label for ="language">
Language:
</label>
<input id="book_language" type = "text" name="language" class = 'form-control' value="{{ book.language }}"/>
</div>
<div class = "form-group">
<label for ="price">
Price:
</label>
<input id="book_price" type = "text" name="price" class = 'form-control' value="{{ book.price }}"/>
</div>
<div class = "form-group">
<label for ="isbn">
ISBN:
</label>
<input id="book_isbn" type = "text" name="isbn" class = 'form-control' value="{{ book.isbn }}"/>
</div>
<input type = "submit" value="Update" id="update" class = "btn btn-success" style="font-size:18px;" />
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Does the BookEntry model have a primary key column? I started having the same error when I added a primary key field on the model the id was referencing. Apparently the id column is replaced by the primary key field. I removed the key and migrated the changes.The error is gone now.

Categories