How to send data with Url Django - python

I want to send {{order.id}}, but getting error like pictuce in bellow, please helping me to solve problem
Image Error
Views.py:
def Detail_pem(request, idor):
print(idor)
return render(request, 'store/detail.html' )
pemby.html:
<!-- <button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button> -->
<button data-product="{{order.id}}" data-act="{{order.name}}" class="btn btn-warning id_order btntam" >Detail</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- <script type="text/JavaScript" src="{% static 'js/pem.js' %}"></script> -->
<script>
var id_order = document.getElementsByClassName('id_order')
for (i = 0; i < id_order.length; i++) {
id_order[i].addEventListener('click', function(){
var orid = this.dataset.product
var ornm = this.dataset.act
console.log('orid :', orid)
console.log('ornm :', ornm)
window.location.href = "{% url 'Detail_pem' %}"
})
}
urls.py:
path('Detail_pem/<idor>', Detail_pem, name='Detail_pem'),

You are redirecting through
window.location.href = "{% url 'Detail_pem' %}" without a variable.
But in your urls.py you are passing idor variable.
It should be: window.location.href = "{% url 'Detail_pem' order.id } %}".
And your urls.py change to this:
int:id
#if you are passing integer
path('Detail_pem/<int:id>', Detail_pem, name='Detail_pem'),
#or if you are passing string
path('Detail_pem/<str:id>', Detail_pem, name='Detail_pem'),

Related

Update a variable every 5 second using jquery

I am using django to create a webpage and this is the first time I am doing so. I am trying to fetch the value of a variable from .py file at an interval of 5 seconds. Below is the HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Like Post App</title>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class = "display-3 color-red"><center>DataFlair AJAX Tutorial<br>Post APP</center></div>
{% for post in posts %}
<div class = 'container jumbotron'>
<h3 class="display-5">{{ forloop.counter }}. {{ post.post_heading }}</h3>
<p class="lead">{{ post.post_text }} </p>
<p>
<div type="text/css" class = "container">Author : {{ post.post_author }}</div>
<a class="likebutton btn btn-primary btn-lg" id="like{{ post.id }}" data-catid="{{ post.id }}">Like({{ post.like_ref.counter }})</a> </p> <p id="message{{post.id}}">
</p>
</div>
{% endfor %}
<script type="text/javascript">
setInterval(function() {
getvalue(); // Do something every 5 seconds
}, 5000);
getvalue();
function getvalue(){
var id;
id = $(this).attr("data-catid");
$.ajax(
{
type:"GET",
url: "like",
data:{
post_id: id
},
success: function( data )
{
$( '#like'+ id ).text("Like(" + data +")");
var i=parseInt(data);
console.log("Value= "+i);
}
}
)
}
</script>
</body>
</html>
Below is the views.py code:
import json
from django.shortcuts import render
from .models import Post, Like
from django.http import HttpResponse
# Create your views here.
#DataFlair #AJAX_tutorial
def index(request):
posts = Post.objects.all()
return render(request, 'post/index.html', { 'posts': posts })
def like(request):
if request.method == 'GET':
post_id = request.GET['post_id']
likedpost = Post.objects.get(id = post_id )
m = Like.objects.filter( post=likedpost ).first()
m.counter +=1
m.save()
value1= int(m.counter)
#data1= {'cmd': 'success', 'ctr': str(m.counter) }
return HttpResponse(value1)
#return HttpResponse(json.dumps(data1))
else:
return HttpResponse("unsuccesful")
I keep getting the following errors:
1) GET http://localhost:8000/ajax/like/ 500 (Internal Server Error)
2) GET http://localhost:8000/favicon.ico 404 (Not Found)
Please help.
I believe:
id = $(this).attr("data-catid");
is not pointing to the button... maybe you should try:
id = $(".likebutton").attr("data-catid");

Flask variables not showing up in HTML

I have a small flask app I am using it to:
Make an HTML page with a leaflet map
Take user input from the HTML page...
Run calculations on that input using certain python modules
Return those variable to JS functions in the page to populate the map
I cannot get ANYTHING but lat and lng to return into my HTML {{}} flask variables.
Here is my HTML page:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 != None and lng1 != None %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
Here is my Flask Python code:
from flask import Flask, render_template, request, flash, redirect, url_for,jsonify
from forms import RegistrationForm
import json
import osmnx as ox
import networkx as nx
import matplotlib.pyplot as plt
from networkx.readwrite import json_graph
import pandas as pd
import mplleaflet
app = Flask(__name__)
app.config.update(dict(
SECRET_KEY="powerful secretkey",
WTF_CSRF_SECRET_KEY="a csrf secret key"
))
#app.route('/')
def my_form():
return render_template('map.html')
#app.route('/', methods=['GET', 'POST'])
def my_form_post():
lat = (request.form['lat'])
lng = (request.form['lng'])
lat = lat
lng = lng
point = (lat,lng)
G = ox.core.graph_from_point(point, distance = 500, network_type='walk')
fig, ax = ox.plot_graph(G)
GJ = mplleaflet.fig_to_geojson(fig=ax.figure)
#return lat, ",", lng
return render_template('map.html', lat1=lat, lng1=lng, GeJ=GJ, point="test_string")`
if __name__ == "__main__":
app.run(host='0.0.0.0',port=5000,debug=True)
The Flask app is working fine so the file structure is not a concern. I just cannot get any other variables to return into my HTML. I even tried making little string dummy variables other that the real ones. No Dice.
Thanks
You could try using the builtin none value http://jinja.pocoo.org/docs/templates/#none
Then do something like:
{% if lat1 is not none and lng1 is not none %}
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.1/dist/leaflet.css"
integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
crossorigin=""/>
<script src="https://unpkg.com/leaflet#1.3.1/dist/leaflet.js"
integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
crossorigin="">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<title>Page Title</title>
<meta charset="utf-8"/>
<style>
#mapid { height: 300px; }
</style>
<body>
<form method="POST">
Latitude to PY: <input name="lat" id="lat"/>
<br/>
Longitude to PY: <input name="lng" id="lng"/>
<br/>
<button>Get data</button>
</form>
{% if lat1 is not Null and lng1 is not Null %}
{{lat1}},{{lng1}}
<script>
var lat1 = {{lat1}}
var lng1 = {{lng1}}
</script>
{% endif %}
{% if point != None %}
<p>{{point}}</p>
{% endif %}
{% if GeJ != None %}
{{GeJ}}
<script>
var GeJ = {{GeJ}}
</script>
{% endif %}
<div id="mapid"></div>
<script>
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox.high-contrast',
accessToken: 'pk.eyJ1IjoiY2dyb3RoIiwiYSI6ImNqZ2w4bWY5dTFueG0zM2w0dTNkazI1aWEifQ.55SWFVBYzs08EqJHAa3AsQ'
}).addTo(mymap);
function zoomTo() {
mymap.panTo(new L.LatLng(lat1, lng1));
}
function addGJ(){
var myLayer = L.geoJson(GeJ).addTo(mymap);
}
window.onload = zoomTo();
window.onload = addGJ();
</script>
</body>
</html>
It would help if you provided an example of what exactly happens when you pass all the values.
Otherwise, what according to me, could be causing the problem is that the 'Null' object in python is the singleton None. The best way to check things for "Noneness" is to use is not None or better still, something as simple as:
{%if lat%} {{lat}} {% endif %}
Also, can't you assign GeJ to the var GeJ within the div instead of putting a line of JS in an abrupt manner up there?
P.S. I wanted to add this as a comment, but don't have enough reputation. Apologies.

Django form won't show up on template

I'm making a sign in system in Django Python, i've been preparing the forms.py, views.py and the template itself, but so far the form fail to load on the template, can anyone help?
Forms.py
class Email_Only_SignUp_Form(forms.Form):
email = forms.EmailField(initial='Your Email...')
Views.py
def email_only_signup_form(request, template_name):
if request.method == 'POST':
signup_form = Email_Only_SignUp_Form(request.POST)
if signup_form.is_valid():
email = signup_form.cleaned_data['email']
username = email
try:
#check for duplicate username
User.objects.get(username=username)
email_error = 'email already exist'
except:
#initial creation of user object
try:
import os, random, string
length = 13
chars = string.ascii_letters + string.digits + '!#$()'
random.seed = (os.urandom(1024))
password = ''.join(random.choice(chars) for i in range(length))
User.objects.create_user(username,
username,
password,
)
user = User.objects.get(username=username)
user_profile=UserProfile(user=user)
user_profile.save()
#send email to user
try:
admin_email = settings.EMAIL_ORIGIN_MEMBERS
email_txt = loader.get_template('account/emails/createaccount.html')
email_html = loader.get_template('account/emails/createaccounthtml.html')
email_context = Context({'u_name': username,
'username': username,
'password': password,
})
new_user_mail = EmailMultiAlternatives('Welcome!',
email_txt.render(email_context),
admin_email,
[user.email, ],
headers={'Reply-To': 'admin#admin.com'}
)
new_user_mail.attach_alternative(email_html.render(email_context), 'text/html')
new_user_mail.send()
except:
pass
return redirect('/account/thankyou/?next=%s'%next)
except:
pass
else:
print('user form in not valid')
else:
signup_form = Email_Only_SignUp_Form()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
email_only_signup_form.html
{% extends "index.html" %}
{% block heroslider %}
<div class="page_title2" style="padding:150px 0px 50px 0px;">
<div class="container">
<h1>User Registration</h1>
</div>
</div><!-- end page title -->
{% endblock %}
{% block main_body %}
<style type="text/css">
input[type='radio'], input[type='checkbox'] {
width:20px;
vertical-align: middle;
}
div.reg_error {
position:relative;
top:-10px;
margin-top:0px;
padding-top:0px;
color:red;
}
</style>
<div class="container">
<form class="pagesignup logiform" action="" method="POST">{% csrf_token %}
<div class="row">
<div class="large-12 columns" style="margin-bottom: 30px;">
<div class="reg_form">
<div class="sky-form">
<header>REGISTER</header>
</div>
<div class="row">
<div class="large-12 columns">
<p>Email<br/>
{{signup_form.email}}
<div class="reg_error">{{ signup_form.email.errors.as_text }}{{email_error}}</div></p>
</div>
</div>
<div class="row">
<div class="large-12 large-centered columns" style="text-align:center;padding:20px;">
<input class="but_medium1" style="border:none;" type = "submit" value="REGISTER" /><br>
<br>By clicking on register, you have read and agreed to our terms of use
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- Google Code for Sign Up Page (landed) Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 969557266;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "5zU4CJby_FoQkoqpzgM";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/969557266/?label=5zU4CJby_FoQkoqpzgM&guid=ON&script=0"/>
</div>
</noscript>
{% endblock %}
You have not passed the signup_form to the template.
return render_to_response(template_name, {'signup_form': signup_form}, context_instance=RequestContext(request))
I have no idea what locals() does.
Edit: I just saw locals which is a built in python function. It will be better if you explicitly pass the variables you need in the template.
Edit 2: Check if it is the correct template_name. In the template simply print and see the form {{ signup_form }}. See if it is available.
You are not returning the form.
Try changing the last line of the view to
return render_to_response(template_name, locals(), context_instance=RequestContext(request, {'signup_form' : signup_form ))

django two digit integer in choice field

I have a form that I want to submit date as mm/yyyy.
class Add_Serv(forms.Form):
month_add = forms.ChoiceField(required=True, choices=['01','02'])
year_add = forms.ChoiceField(required=True,
choices=[(x, x) for x in xrange(date.today().year - 1, date.today().year + 1)])
When my month prints out in form, it's only one digit integer 1 instead of 01. It doesn't sound like a big deal but it screws up my date format when handling these dates (and also looks very ugly). Is there any way to keep that zero before the number?
add validation in form's clean method and check if the length of month field is 1 or 2.
Append 0 before if length is 1 and return value of month
Print it out using format:
print("{:02d}".format(my_number))
See Pyformat for more formatting tips
use jquery library
You need only one field.
forms.py
class FormA(forms.Form):
fecha = forms.DateField(input_formats=['%m/%Y'])
views.py
def formulario(request):
if request.method == "POST":
form = FormA(request.POST)
if form.is_valid:
# action
else:
form = FormA()
return render(request,"add.html",{'form':form})
Your template
I add bootstrap css library and django-bootstrap-from
<div class="row">
<div class="col-lg-8">
<form id="form" action="" method="POST">
{{form|bootstrap_horizontal}}
{%csrf_token%}
<p align="right"><button id="enviar" type= 'submit' class="btn btn-success"> Guardar</button>
<button type= "reset" class="btn btn-warning"> Limpiar</button></p>
</form>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
$('#id_fecha').datepicker( {
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'mm/yy',
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
The result
http://prntscr.com/7qd01v

Facing problem in returning the ongoing upload status back to the HTML using AJAX in Django

I am trying to implement "Upload Progress Bar" in Django.
Following is my code in the template file:
{% extends "index_base.html" %}
{% block content %}
<script src="/media/js/functions.js" type="text/javascript"></script>
<script src="/media/js/jquery.js" type="text/javascript"> </script>
<script type="text/javascript">
var xhrObject1;
var xhrObject2;
function createXMLHttpObject()
{
var xhrObject; // The variable that makes Ajax possible!
try
{
xhrObject = new XMLHttpRequest();
}
catch (e)
{
try{
xhrObject = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e){
try {
xhrObject = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhrObject = null;
}
}
}
return xhrObject;
}
function ajaxFunction()
{
xhrObject1 = createXMLHttpObject();
if (xhrObject1 == null)
{
alert("Your browser does not support ajax.");
return;
}
xhrObject1.onreadystatechange = function(){
if(xhrObject1.readyState == 4){
document.getElementById("targetDiv").innerHTML = xhrObject1.responseText;
}
else
{
xhrObject2 = createXMLHttpObject();
xhrObject2.onreadystatechange = function(){
if(xhrObject2.readyState == 4){
document.getElementById("targetDiv").innerHTML = xhrObject2.responseText;
}
else
{
document.getElementById("targetDiv").innerHTML = "getting progress...";
}
}
xhrObject2.open("GET", "/upload_progress.psp", true);
xhrObject2.send(null);
}
}
var arrFiles = document.getElementById('id_file');
var fileToUpload = arrFiles.files[0];
xhrObject1.open("POST", "/upload.psp/", true);
xhrObject1.send(fileToUpload);
}
function submitForm()
{
document.forms["myform"].submit();
ajaxFunction();
return false;
}
</script>
<div id="main_container">
{% include "includes/nav.html" %}
<!------- Main Contents ---------->
<div id="contents_holder">
<div id="contents">
<div id="c_banner">
<span class="main_title">Upload File</span>
</div>
<div id="targetDiv" > </div>
<div id="setting">
<form name="myform" id="myform" action="/upload.psp/" method="post" enctype="multipart/form-data">
<h2>Upload File</h2></br>
<p>{{ form.file.label_tag }} {{ form.file }}</p></br>
<input type="button" value="Upload" name="uploadButton" onclick="javascript:return submitForm();"/>
<input type="button" value="Cancel" name="cancelUploadButton" onclick ="cancelUploadClicked()"/>
<input type="hidden" value="title" name="title" id="title" />
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Following are my two functions inside views.py:
#condition(etag_func=None)
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
#handle_uploaded_file(request.FILES['file'])
f = request.FILES['file']
filename = "/host_lighttpd/var/www/htdocs/satellite/static/Data/" + f.name
destination = open(filename, 'wb+')
for chunk in f.chunks():
destination.write(chunk)
#yield chunk
request.session['uploaded'] += chunk
destination.close()
return render_to_response('uploadsuccess.html')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
def upload_progress(request):
#uploaded = request.session['uploaded']
return HttpResponse("Upload progress function...")
#return HttpResponse(uploaded)
My problem is how can I return the upload status back to the
second ajax call (GET method), so that it can be eventually updated
inside the html.
I don't know how can I return the ongoing uploading status.
Any help would be appreciated. Thanks in advance.
I recently had to do a bit of digging to find a solution for this myself.
Check out :-
http://fairviewcomputing.com/blog/2008/10/21/ajax-upload-progress-bars-jquery-django-nginx/
I have not tried the solution referenced yet, but it looks reasonable enough.
It involves registering a custom file upload class to expose the upload progress information.

Categories

Resources