I have two functions in views.py, the first one allows you to display information from tables. The second is to get data from the form and redirect to the page with the result. How can I pass the data received from the form to the first function to display information from the tables based on this very data?
In the first function:
def SuOp(request):
allrooms = Rooms.objects.all()
allfood = Food.objects.all()
alltours = Tours.objects.all()
data = {
'allfood': allfood,
'allrooms': allrooms,
'alltours': alltours,
}
return render(request, './obj.html', data)
in the second function:
def Main(request):
error = ''
if request.method == 'POST':
form = SearchMain(request.POST)
if form.is_valid():
budget = form.cleaned_data.get("budget")
arrival_date = form.cleaned_data.get("arrival_date")
departure_date = form.cleaned_data.get("departure_date")
number_of_people = form.cleaned_data.get("number_of_people")
count_days = (departure_date-arrival_date).days
return redirect('allobject')
else:
error = 'The form has been filled out incorrectly'
form SearchMain()
data = {
'formS': form,
'error': error,
}
return render(request, './main.html', data)
urls.py:
urlpatterns = [
path('', views.Main, name='main'),
path(r'allobject/$', views.SuOp, name='allobject')
]
You can use sessions to pass values from one view to another. First set the session:
if form.is_valid():
budget = form.cleaned_data.get("budget")
request.session['budget'] = budget
...
return redirect('allobject')
Then your other view can get the session variable:
def SuOp(request):
budget = request.session.get('budget')
...
allrooms = Rooms.objects.all()
allfood = Food.objects.all()
alltours = Tours.objects.all()
data = {
'allfood': allfood,
'allrooms': allrooms,
'alltours': alltours,
}
return render(request, './obj.html', data)
The other option is to do all the calculations in the view that receives the budget, arrival_date, departure_date, number_of_people, save the desired results to the Rooms, Food and Tours objects.
I'm working on a Django project where I want to use ajax jquery to complete my search in my search form.
Tried everything, but it does not seem to work.
Pls, where have I missed it?
used this tutorial
views.py
import json
def search(request):
if request.method == 'POST':
form = SearchForm(request.POST)
if form.is_valid():
query = form.cleaned_data['query']
catid = form.cleaned_data['catid']
if catid == 0:
products = Product.objects.filter(name__icontains=query)
else:
products = Product.objects.filter(name__icontains=query, category_id=catid)
category = Category.objects.all()
context = {
'products': products,
'category': category,
'query': query,
}
return render(request, 'shop/product/search.html', context)
return HttpResponseRedirect('/')
def search_auto(request):
if request.is_ajax():
q = request.GET.get('term', '')
products = Product.objects.filter(name__icontains=q)
results = []
for pl in products:
product_json = {}
product_json = pl.name
results.append(product_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
<script>
$(function() {$("#query").autocomplete({
url: "{% url 'shop:search_auto' %}",
select: function (event, ui) {AutoCompleteSelectHandler(event, ui)},
minLength: 2,
});
});
function AutoCompleteSelectHandler(event, ui)
{var selectedObj = ui.item;}
</script>
path('search', views.search_auto, name='search_auto'),
Thanks.
i'm using an api to get informations about coronavirus cases around the world and i have an issue in the last line of code
from django.shortcuts import render
import requests
from django import forms
from django.views.generic import TemplateView
from .forms import homeform
def home(request):
if request.method =='POST':
form = homeform(request.POST)
if form.is_valid():
text = form.cleaned_data
field = text['name']
print(field)
country = field
else:
form = homeform()
country = 'algeria'
url = "https://covid-193.p.rapidapi.com/statistics"
querystring = {"country": country}
headers = {
'x-rapidapi-host': "covid-193.p.rapidapi.com",
'x-rapidapi-key': "36b864062emshac7e191eb5087e6p169e6bjsn24c86f3408c1"
}
response = requests.request("GET", url, headers=headers, params=querystring).json()
data = response['response']
print(data)
d = data[0]
context = {
'all': d['cases']['total'],
'recovered': d['cases']['recovered'],
'deaths': d['deaths']['total'],
'new': d['cases']['new'],
'serioz': d['cases']['critical'],
'active':d['cases']['active'],
'deaths_new':d['deaths']['new']
}
return render(request, 'index.html',{'form':form}, context)
here i have a problem with rendering the page it just shows my html code in the webpage but when i remove context from the last line of code evrything becomes normal , please help me
I think you are trying to pass two context dictionaries. Your {'form':form} is in the place of the context argument so your context isn't actually getting passed as a context. Add the form to the context dictionary in the line above return and remove {'form':form} from your render function.
I think you need to change your code to this :
return render(request, 'index.html',{'form':form,
'context':context})
This way you will get both in the html file.
This is the first page, in there I can use ajax to request url, and pass request data to it.
My ajax code is below:
$.ajax({
type:'post',
url:'/app_api/server_payment/',
contentType:'application/json',
data:JSON.stringify({'params':buy_data}),
dataType:'json',
success:success_func
})
function success_func(response){
console.log(response)
}
In the views.py:
def server_payment(request):
if request.method == 'POST':
is_login = request.session['is_login']
if is_login:
print ('server_payment_2 ', is_login) # it prints
return render(request, 'app_admin/payment.html')
else:
return render(request, 'frontend/login.html')
In the views.py I want to render the payment.html and skip to it.
This is my payment.html.
But the server.html page did not skip to the payment.html, and I don't know how to realize it.
I tried use the self.location=/app_api/server_payment/ but I can not pass the data with post method.
There are some detail information in the first snapshot.
You need to check AJAX header before you make any logic and return JsonResponce
request.is_ajax()
More in the documentation
def server_payment(request):
if request.method == 'POST':
is_login = request.session['is_login']
if is_login:
print('server_payment_2 ', is_login) # it prints
if request.is_ajax():
return JsonResponse({'foo': 'bar'})
return render(request, 'app_admin/payment.html')
else:
return render(request, 'frontend/login.html')
I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.
This is the server-side script:
/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;
if($validateValue =="Testuser"){ // Validate??
$arrayToJs[2] = "true"; // RETURN TRUE
echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURN ARRAY WITH success
}
else{
for($x=0;$x<1000000;$x++){
if($x == 990000){
$arrayToJs[2] = "false";
echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}'; // RETURNS ARRAY WITH ERROR.
}
}
}
And this is the converted code
def validate_user(request):
if request.method == 'POST':
vld_value = request.POST.get('validateValue')
vld_id = request.POST.get('validateId')
vld_error = request.POST.get('validateError')
array_to_js = [vld_id, vld_error, False]
if vld_value == "TestUser":
array_to_js[2] = True
x = simplejson.dumps(array_to_js)
return HttpResponse(x)
else:
array_to_js[2] = False
x = simplejson.dumps(array_to_js)
error = 'Error'
return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
return render_to_response('index.html',context_instance=RequestContext(request))
I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'.
I usually use a dictionary, not a list to return JSON content.
import json
from django.http import HttpResponse
response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'
Pre-Django 1.7 you'd return it like this:
return HttpResponse(json.dumps(response_data), content_type="application/json")
For Django 1.7+, use JsonResponse as shown in this SO answer like so :
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
New in django 1.7
you could use JsonResponse objects.
from the docs:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
I use this, it works fine.
from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Alternative:
from django.utils import simplejson
class JsonResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JsonResponse, self).__init__(
content=simplejson.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
Since Django 1.7 you have a standard JsonResponse that's exactly what you need:
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
You don't even need to json.dump your array.
With Django Class-based views you can write:
from django.views import View
from django.http import JsonResponse
class JsonView(View):
def get(self, request):
return JsonResponse({'some': 'data'})
and with Django-Rest-Framework you can write:
from rest_framework.views import APIView
from rest_framework.response import Response
class JsonView(APIView):
def get(self, request):
return Response({'some': 'data'})
For those who use Django 1.7+
from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
official docs
from django.http import HttpResponse
import json
class JsonResponse(HttpResponse):
def __init__(self, content={}, mimetype=None, status=None,
content_type='application/json'):
super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
status=status, content_type=content_type)
And in the view:
resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
You'll want to use the django serializer to help with unicode stuff:
from django.core import serializers
json_serializer = serializers.get_serializer("json")()
response = json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
return HttpResponse(response, mimetype="application/json")
Its very convenient with Django version 1.7 or higher as you have the JsonResponse class, which is a subclass of HttpResponse.
from django.http import JsonResponse
def profile(request):
data = {
'name': 'Raghav',
'location': 'India',
'is_active': False,
'count': 28
}
return JsonResponse(data)
For older versions of Django, you must use an HttpResponse object.
import json
from django.http import HttpResponse
def profile(request):
data = {
'name': 'Raghav',
'location': 'India',
'is_active': False,
'count': 28
}
dump = json.dumps(data)
return HttpResponse(dump, content_type='application/json')
How to use google app engine with ajax (json)?
Code Javascript with JQuery:
$.ajax({
url: '/ajax',
dataType : 'json',
cache: false,
success: function(data) {
alert('Load was performed.'+data.ajax_resp);
}
});
Code Python
class Ajax(webapp2.RequestHandler):
def get(self):
my_response = {'ajax_resp':'Hello, webapp World!'}
datos = json.dumps(my_response)
self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
self.response.out.write(datos)
First import this:
from django.http import HttpResponse
If you have the JSON already:
def your_method(request):
your_json = [{'key1': value, 'key2': value}]
return HttpResponse(your_json, 'application/json')
If you get the JSON from another HTTP request:
def your_method(request):
response = request.get('https://www.example.com/get/json')
return HttpResponse(response, 'application/json')
This is my preferred version using a class based view.
Simply subclass the basic View and override the get()-method.
import json
class MyJsonView(View):
def get(self, *args, **kwargs):
resp = {'my_key': 'my value',}
return HttpResponse(json.dumps(resp), mimetype="application/json" )
Django code views.py:
def view(request):
if request.method == 'POST':
print request.body
data = request.body
return HttpResponse(json.dumps(data))
HTML code view.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#mySelect").change(function(){
selected = $("#mySelect option:selected").text()
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/view/',
data: {
'fruit': selected
},
success: function(result) {
document.write(result)
}
});
});
});
</script>
</head>
<body>
<form>
{{data}}
<br>
Select your favorite fruit:
<select id="mySelect">
<option value="apple" selected >Select fruit</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
</form>
</body>
</html>
Most of these answers are out of date. JsonResponse is not recommended because it escapes the characters, which is usually undesired. Here's what I use:
views.py (returns HTML)
from django.shortcuts import render
from django.core import serializers
def your_view(request):
data = serializers.serialize('json', YourModel.objects.all())
context = {"data":data}
return render(request, "your_view.html", context)
views.py (returns JSON)
from django.core import serializers
from django.http import HttpResponse
def your_view(request):
data = serializers.serialize('json', YourModel.objects.all())
return HttpResponse(data, content_type='application/json')
Bonus for Vue Users
If you want to bring your Django Queryset into Vue, you can do the following.
template.html
<div id="dataJson" style="display:none">
{{ data }}
</div>
<script>
let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
var app = new Vue({
el: '#app',
data: {
yourVariable: dataParsed,
},
})
</script>
This way the json contents can be downloaded as a file with a specific filename.
import json
from django.http import HttpResponse
def download_json(request):
data = {'some': 'information'}
# serialize data obj as a JSON stream
data = json.dumps(data)
response = HttpResponse(data, content_type='application/json charset=utf-8')
# add filename to response
response['Content-Disposition'] = 'attachment; filename="filename.json"'
return response
In View use this:
form.field.errors|striptags
for getting validation messages without html
def your_view(request):
response = {'key': "value"}
return JsonResponse(json.dumps(response), content_type="application/json",safe=False)
#Specify the content_type and use json.dump() son as the content not to be sent as object