I want to show the RandomId which is saved in database in my HTML, but I am not sure how to do it. Anyone know how to do it?
Here is my html
</script>
<button onclick="myFunction()"><input type="submit" value="Place Order"></button>
<script>
function myFunction() {
alert("Order has been placed in the kitchen \n Your order ID is
{{% random_id %}}")
}
</script>
here is my views.py
RandomId = request.POST.get("RandomId")
RandomId = get_random_string(length=5) #get random string id
#RandomId = request.POST.get("RandomId")
customerOrder = CustomerOrder(Table_Num=Table_Num , Food=Food, Quantity=Quantity, Message=Message, RandomId=RandomId) #get data into the CustomerOrder db
customerOrder.save() #save data into db
random_id = CustomerOrder.objects.all()
#order_summary = CustomerOrder.objects.filter(Table_Num = request.Table_Num)
#order_summary = CustomerOrder.objects.filter(Table_Num = 15)
return render(request, 'restaurants/customer_page.html', {'random_id': random_id}) #return customer page
here we go
in your html
{% for id in random_id %}
{{ id }}
{% endfor %}
Please shorten your code to the relevant parts. And split up your code into different sections to make it easier to read. Like
template:
<p>Some html here </p>
view:
def my_view(request):
# things that happen here
Additionally your code defines RandomId twice and you seem to be inserting uncleaned data into your database. Use forms, use form.is_valid(), provide your model information, and double check when to use {{ something_here }} and {% something_else_here %}. Hint: {{ variable }}, and {% if variable == 'hello world' %}.
Related
I want to display the list "response_body" to my html page "home.html"
For that I retrieved id attribute from response_body and the last id which was stored in "id" variable is printed to my html file.
I want to retrieve all the id's and print it to the html page
I know this will be done through loop but how?
I am new to django and python any help will be greatly appreciated.
I have tried printing the last id before the loop ended and I was successful with it but now I want to print all the id'd in the loop.
i tried passing response_body to html instead of context but it gives me an error as response_body is a list type and it asked me to pass a dictionary variable like context which works fine.
how can I print all the id's in the reponse_body list
home.html
<p>results</p>
<p>{{id}}</p>
views.py
as this is a fairly long code i am posting just the code which maybe useful.
response_body = json.loads(response.read().decode('utf-8'))
for j in response_body:
print(j['id'])
id = j['id']
context = {
'id': id,
}
return render(request, 'home.html', context)
Its pretty simple. Just send the list in a dictionary:
context = {
'ids': [j['id'] for j in response_body],
'response' : response_body,
'dict_values': {'a':1, 'b':2} # a dummy dictonary
}
return render(request, 'home.html', context)
And update the template:
<p>results</p>
{% for id in ids %}
<p>{{id}}</p>
{% endfor %}
<p> Response Body </p>
{% for r in response %}
{{ r.id }}
{{ r.description }}
// and so on
{% endfor %}
<p> dummy dict </p>
{% for key, value in dict_values.items %}
{{ key }} {{ value }}
{% endfor %}
I've been trying to figure this out for days and was unable to find any useful information online.
What I am trying to do is paginate objects from my model after filtering them using a drop down menu and supplying the data to python via AJAX. I know where the problem is but I am not sure how to solve it. I have two templates, first one is:
entry_index.html:
{% extends 'main/base.html' %}
<form action="" method="get" accept-charset="utf-8">
<select class="selectpicker" name="times" onchange="FilterCategories()" id="times">
<option value="1">last 24 hours</option>
<option value="30">past month</option>
<option value="365">past year</option>
<option value="10000">all time</option>
</select>
</form>
<ul id="all-games" class="list-unstyled">
{% include page_template %}
</ul>
The template that is being included in the above template is entry_index_page.html:
{% if objects %}
{% for object in objects %}
do something
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if objects.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ objects.number }} of {{ objects.paginator.num_pages }}.
</span>
{% if objects.has_next %}
next
{% endif %}
</span>
</div>
urls.py:
url(r'^$', views.entry_index, name='index')
views.py:
def entry_index(
request,
template='entry_index.html',
page_template='entry_index_page.html'):
date_from = timezone.now() - timezone.timedelta(days=1)
obj_list=Object.objects.filter(submitted__gte = date_from).order_by('-votes')
message=[]
context = {
'objects': obj_list,
'page_template': page_template}
if request.is_ajax():
template = page_template
message = []
if request.method == "GET":
time_range = request.GET.get('time_range')
if time_range is not None and time_range != u"":
time_range = request.GET['time_range']
date_from = timezone.now() - timezone.timedelta(days=int(time_range))
obj_list= Object.objects.filter.filter(submitted__gte=date_from)
paginator = Paginator(obj_list, 2)
page = request.GET.get('page')
try:
objects= paginator.page(page)
except PageNotAnInteger:
objects= paginator.page(1)
except EmptyPage:
objects= paginator.page(paginator.num_pages)
context.update({"message":message,"objects":objects})
return render_to_response(
template, context, context_instance=RequestContext(request))
ajax.js:
function FilterCategories() {
var timePosted = document.getElementById('times');
$.ajax({
type: "GET",
url: "",
data: {
'time_range': timePosted.value,
'csrfmiddlewaretoken': $("input[csrfmiddlewaretoken]").val()
},
success: filterResults,
dataType: 'html'
});
}
Now to explain what I think is going on and hopefully someone can help me find a solution.
When the home page is loaded (entry_index.html) the model gets filtered based on the first option in the drop down menu (i.e. value="1", which is filtering for the data entries submitted within the last day). The obj_list variable gets populated and is passed to the paginator and everything works as expected. I get a certain number of pages and can navigate through pages. Now lets assume we are on the home page again and I select "all time" from the drop down menu. This will trigger the onchange callback and it will call the FilterCategories() function. Note the url in AJAX is "" (an empty string, so pointing to my index page). According to urls.py, it will call my entry_index() view. Because request is ajax, the template used will change (page_template becomes the new template, page_template = entry_index_page.html). Because the new time range specified with the drop down menu and passed on with ajax, I get a new obj_list which is then paginated and produces "objects" which are then passed as context onto the template. Up until this point everything works as expected. I get right amount of pages etc. However, the problem starts when I try to go to the next page with the newly selected filter. When I click the next page button, the request that is being made is not an ajax request so everything that is in the request.is_ajax() conditional is not executed. So in another words a click to the next page is calling my entry_index view again and the template being used this time around is entry_index.html and my filter is reset back to the default, which is the "last 24 hours" filter. Therefore, when I click the next page what I end up getting is actually the default home page again instead of getting the next page of objects with my newly selected drop down filter.
My question is, is there an easy way to fix this so that I can scroll through the pages of my filtered model? Or should I completely abandon this approach and there is an easier way to do this? I apologize for a long post and I hope someone out there will be able to help me out. Thank you for taking your time to read this.
Here's an example of an approach I've taken to having dynamic content displayed on a page using Django and Ajax:
I was tooling a little browser Sci-fi game just to practice this specific technique. Everything took place in a single view:
class GameViewport(TemplateView):
template_name = "game_viewport.html"
#cached_property
def slug(self):
return self.kwargs['slug']
#cached_property
def game(self):
return Game.objects.get(url=self.kwargs['slug'])
#cached_property
def player(self):
return Player.objects.get(game=self.game)
#cached_property
def current_planet(self):
return self.player.current_planet
#cached_property
def left_column(self):
player = self.player
if player.current_location:
node = player.current_node
if len(Location.objects.filter(node=node)) == 0:
spawn_locations(node)
locations = Location.objects.filter(node=node)
else:
locations = Location.objects.filter(planet=node)
html = "Other Sites in ".format(str(node))
for location in locations:
html += '<li>{} ({})</li>'.format(location.name, location.type.name)
return html
elif player.current_node:
planet = player.current_planet
if len(Node.objects.filter(planet=planet)) == 0:
spawn_nodes(planet, get_name_choices())
nodes = Node.objects.filter(planet=planet)
else:
nodes = Node.objects.filter(planet=planet)
html = '<h4><b>Other Starports on {}:</b></h4>'.format(planet.name)
for node in nodes:
html += '<li> {} ({})</li>'.format(node.name, node.type.name)
return html
elif player.current_planet:
system = player.current_system
html = '<h4><b>Known Planets in {}:</b></h4>'.format(system.name)
for known_planet in player.known_planets.filter(solar_system=system):
html += '<li> {} ({})</li>'.format(
known_planet.name,
known_planet.classification.name
)
return html
else:
html = '<h4><bShip Status</b></h4>'
html += '<p><b>Fuel:</b> 100%</p>'
return html
So as you can see, the left column would generate different html data based on what the player's current settings are. This would be plugged into the template like so:
<div class="col-md-3">
<div class="leftColumn">
{% autoescape off %}
{{ view.left_column }}
{% endautoescape %}
</div>
</div>
If the user clicked on a new location, I would send her decision through AJAX:
$(".planetChoice").click(function(){
event.preventDefault();
var submission_data = {planet: $(this).text()};
console.log(submission_data);
$.ajax({
url: $('#visitPlanet').attr('href'),
type: 'GET',
dataType: "json",
data: submission_data,
success: function(html_data) {
window.location.reload();
},
failure: function(data) {
alert('Something went wrong. Please refresh the page.');
}
});
});
All this would do is update the player's state and reload the page according to her new settings:
def visit_planet(request, slug):
player = Game.objects.get(url=slug).player_1
planet = Planet.objects.get(name=request.GET.get('planet', "").strip())
if planet:
player.current_location = None
player.current_node = None
player.current_planet = planet
player.save()
response = {'status': 1, 'message': "Ok"}
return JsonResponse(response)
Thus displaying the new data, as determined by the left_column property.
I went about this by changing the state in the database, but it could just as easily be accomplished with session variables. I found it to be a relatively clean and DRY way of cycling dynamic content. It also has the advantage of giving Django an opportunity to generate or modify data in between clicks.
Not sure if this applies to your situation, but hopefully it sparks an idea!
EDIT: You don't even necessarily need to output HTML. Here's an approach I am using in a different application:
<!--Product Tile #1-->
{% if view.tile_data.0 %}
<div class="col-md-4">
<div class="card hoverable">
<!--Card content-->
<div class="card-block" id="tile_{{ view.tile_data.0.invoice }}_id">
<!--Title-->
<h4 class="card-title">Shipment {{ view.tile_data.0.invoice }}</h4>
<!--Text-->
<p class="card-text">{{ view.tile_data.0.supplier.name }}
<br>
<b>{{ view.tile_data.0.lbs|floatformat }} Lbs # {{ view.tile_data.0.price }} USD</b>
<br>
{{ view.tile_data.0.variety.commodity }} {{ view.tile_data.0.variety }} {{ view.tile_data.0.inshell|shell_display }}</p>
</div>
<!--/.Card content-->
</div>
</div>
{% endif %}
<!--./Product Tile #1-->
This data is directly fed through the view from a model manager:
def tile_data(self, status, first, last):
return self.model.objects.filter(status=status)[first:last]
I'm working with Django v1.4 (Python v.2.7.3) and I'm trying to build a proofchecking application. My proofchecker has an "Examples" page with a list of links to example proofs for the user, and these are rendered on the screen one after the other. A small sample is shown below:
These example files are saved at MEDIA_ROOT on the server, and what I want is a way to make it so that clicking the link will pass the contents of the file in a POST message to a particular view. That view already has code designed to handle the user uploading a proof file directly from their file system, so essentially what I want to do is make it so that the examples.html template (shown below) passes the same kind of information except for files already stored on the server.
The code for examples.html is:
{% load staticfiles %}
<html>
<head>
<title>Anaconda</title>
<style>
body
{
overflow-y: scroll;
}
</style>
</head>
<body>
<center>
<img src="{% static "AnacondaTitleText.png" %}" alt="Title" height="40%" width="40%"/>
<div align="left" style="width:800px;">
<h2>Anaconda Examples</h2>
<p>You can click the button beside each example on this page to load it into the proof window.
{% if examples %}
The following examples are included with Anaconda:</p>
<br>
{% for example in examples %}
<p>{{ example.exampleFile.name|cut:"./" }}: link</p>
<br>
{% endfor %}
{% else %}
There are no examples currently included with Anaconda.</p>
{% endif %}
</div>
</center>
</body>
</html>
The "a href..." part will need to be changed because currently, clicking it will bring up a "Save file" dialog which is not what I want.
In my server's views.py file, I have the following code capable of handling uploaded files:
def proof(request):
if request.method == 'POST':
defaultText = request.FILES['docfile'].read()
proofText = ProofForm(request.POST)
else:
defaultText = ""
proofText = ProofForm()
c = {}
c.update(csrf(request))
c['form'] = proofText
c['default_text'] = defaultText
return render_to_response('server/proof.html', c)
I suppose what I want is a way to do the following:
The user clicks the link next to a particular example proof
All the necessary information gets loaded into request.FILES
This gets sent to the server as a POST request to proof(request)
proof(request) treats it like a regular uploaded file and reads the file contents
My models.py file looks like this:
from django.db import models
class Example(models.Model):
exampleFile = models.FileField(upload_to='.')
I'd be happy to provide additional information if necessary.
I found a solution to this, but I suspect it's a bit hacky.
Inside examples.html I include the following:
{% for example in examples %}
<form name="example" action="/server/proof" method="post">
{% csrf_token %}
<p>{{ example.exampleFile.name|cut:"./" }}</p>
<input type="hidden" name="example" value="{{ example.exampleFile.name|cut:"./" }}">
<input type="submit" value="Select">
</form>
<br>
{% endfor %}
I associate the name of the file with a hidden input element, and then in views.py I have the following code:
def proof(request):
if request.method == 'POST':
print "DATA"
print str(request.POST)
try:
defaultText = request.FILES['docfile'].read()
except:
examplePath = request.POST.get('example')
with open(join(MEDIA_DIR, examplePath), 'r') as f:
defaultText = f.read()
proofText = ProofForm(request.POST)
else:
defaultText = ""
proofText = ProofForm()
c = {}
c.update(csrf(request))
c['form'] = proofText
c['default_text'] = defaultText
return render_to_response('server/proof.html', c)
It's patchwork, but it does what I want. Hopefully I'll have time to improve the code at some later time.
I have used Django in one of my project.I have also used angularjs. In mention I am very new in Django and Angularjs.Now This is one of my view where i have retrieving data from one of my model namely SubscribePlan.
def subscribed(request):
from django.core import serializers
subscribedplan = SubscribePlan.objects.filter(user = request.user)
subscribing = serializers.serialize('json',subscribedplan)
return HttpResponse(subscribing)
and the models.py for the SubscribePlan is
class SubscribePlan(models.Model):
plan = models.ForeignKey(Plan)
expiriary_date = models.DateTimeField()
user = models.ForeignKey(User)
here you can see that the plan is a foreign key.Now i have used the anuglarjs in my template to get data to show the name of the plan of the associated user using the above given view subscribed.i have used angularjs in this tempalate like this..
{% extends 'userena/base_userena.html' %}
{% load i18n %}
{% load url from future %}
{% block title %}{% blocktrans with profile.user.username as username %}{{ username }}'s profile.{% endblocktrans %}{% endblock %}
{% block content_title %}<h2>{{ profile.user.username }} {% if profile.user.get_full_name %} ({{ profile.user.get_full_name }}){% endif %}</h2>{% endblock %}
{% block content %}
<div class="panel-body">
<h4 ng-controller='SubscribedPlanCtrl'>Subscribe Plan: <span style = "color:red">{[{subscribedplan.0.plan}]}</span></h4>
</div>
{%block extrajs%}
<script type="text/javascript">
var app = angular.module('shutter',[]);
app.config(function($httpProvider){
//$httpProvider.defaults.headers.post['X-CSRFToken'] = {% csrf_token %};
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
app.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
});
app.controller('SubscribedPlanCtrl',['$scope','$http',function($scope,$http){
$http.get('/showphoto/subscribing/').success(function(subdata){
$scope.subscribedplan = subdata;
}).error(function(subdata,status){
$scope.datas = subdata || "Request Fail";
$scope.status = status;
console.log(status);
});
}]);
</script>
{%endblock%}
{% endblock %}
here in the template you can see that i have used {[{subscribedplan.0.plan}]} to show the name of the plan.
But the problem is, instead of showing the name of the plan ,its showing the id of the plan.Remember that the plan is a foreign key.Now how can i show name of plan.
You can use Django's natural keys or construct the JSON object yourself. The latter is fine, in this case, since it is a small model and you don't need to deserialize it. An example code (untested):
from json import json
def subscribed(request):
subscribedplan = SubscribePlan.objects.filter(user=request.user)[0]
json_obj = [{"plan": subscribedplan.plan.name }, ]
return HttpResponse(json.dumps(json_obj))
Would recommend a more complete package like django-angular for better integration.
I am using ajax to sort the data which came from search results.
Now I am wondering whether it is possible to render just some part of html so that i can load this way:
$('#result').html(' ').load('/sort/?sortid=' + sortid);
I am doing this but I am getting the whole html page as response and it is appending the whole html page to the existing page which is terrible.
this is my views.py
def sort(request):
sortid = request.GET.get('sortid')
ratings = Bewertung.objects.order_by(sortid)
locations = Location.objects.filter(locations_bewertung__in=ratings)
return render_to_response('result-page.html',{'locs':locations},context_instance=RequestContext(request))
how can I render only that <div id="result"> </div> from my view function? or what am I doing here wrong?
From what I understand you want to treat the same view in a different way if you receive an ajax request.
I would suggest splitting your result-page.html into two templates, one that contains only the div that you want, and one that contains everything else and includes the other template (see django's include tag).
In your view then you can do something like the following:
def sort(request):
sortid = request.GET.get('sortid')
ratings = Bewertung.objects.order_by(sortid)
locations = Location.objects.filter(locations_bewertung__in=ratings)
if request.is_ajax():
template = 'partial-results.html'
else:
template = 'result-page.html'
return render_to_response(template, {'locs':locations},context_instance=RequestContext(request))
results-page.html:
<html>
<div> blah blah</div>
<div id="results">
{% include "partial-results.html" %}
</div>
<div> some more stuff </div>
</html>
partial-results.html:
{% for location in locs %}
{{ location }}
{% endfor %}