I am having trouble displaying the value on the html template from the mysql database.
my view:
from django.contrib.auth.decorators import login_required
from django.db.models import Count, Min, Sum, Avg, Max
from .models import Gwtable
import datetime
def index(request):
max_value = Gwtable.objects.all().aggregate(Max('salesprice'))
return render(request, 'sql/index.html', context)
my html:
{{ max_value.values|floatformat:2 }}
Did you fill the context object like that context= { 'max_values':max_values} your html tag is correct one.
Related
from django.shortcuts import render
import random
Create your views here.
def home(request):
l=[]
for i in str(random.randint(1,40)):
l.append(i)
return render(request,
'check/web.html',
{'list':l}
)
templates:
{% for i in list %}
{{i}}
{% endfor %}
I am getting only two boxes instead of 40 boxes
Made a few changes in your code, the below should work for you.
import numpy as np
def home(request):
l=[]
for i in range(40):
l.append(str(np.random.randint(1,40)))
return render(request,'check/web.html',{'list':l})
or
import numpy as np
def home(request):
l=[str(np.random.randint(1,40)) for i in range(40)]
return render(request,'check/web.html',{'list':l})
All my views are being rendered properly but when i try to render a list using iteration nothing is displayed on the page, without error.
the view:
from django.shortcuts import render
from haleys_chemist.models import anti_bacterials
from django.http import HttpResponse
from .table import anti_bacterials_Table
from django_tables2 import RequestConfig
from datetime import datetime
from django.http import HttpResponseRedirect
from .forms import notepadform
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView,ListView
class retriever(TemplateView):
template_name='index.html'
def expiry_days(self,request):
expired_drugs= anti_bacterials.objects.all()
args={'expired_drugs':expired_drugs}
return render (request, self.template_name,args)
template(index.html):
<h6><i>Drugs about to expire</i></h6>
{%for expired_drug in expired_drugs%}
<ul>
<li>{{expired_drug.Drug_name}}</li>
<li>{{expired_drug.expiry_date}}</li>
</ul>
{%endfor%}
</div>
model:
class anti_bacterials(models.Model):
Drug_id= models.IntegerField(primary_key=True);
Drug_name= models.CharField(max_length=50);
expiry_date= models.DateField();
Price_per_mg= models.DecimalField(decimal_places=2, max_digits=20)
i need to list the expired drugs on the left bar. i know i have queried for all objects on the view but still i should get a list of all the objects names and expiry dates.
You are not using the generic TemplateView properly.
The method expiry_days will never be called because the generic TemplateView doesn't know about it.
Simply you can use the method get_context_data to achieve what you want:
class retriever(TemplateView):
template_name='index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['expired_drugs']= anti_bacterials.objects.all()
return context
Read more about the generic TemplateView in Django's official documentation and here.
I was wondering if there is a way to pass view variables directly to dajaxice?
Actually I convert the id to a json string and load them via the dajaxice function.
I like to avoid passing the id this way and have to handle it as user manipulated input.
view.py
from django.shortcuts import render_to_response, redirect
from django.shortcuts import get_object_or_404
from django.template import RequestContext
from django.utils import simplejson
def site(request, slug, number):
collection = get_object_or_404(Collection, slug=slug)
site = get_object_or_404(Site, collection=collection, number=number)
json_id = simplejson.dumps(site.pk)
return render_to_response('base/site.html',
{
'site': site,
'json_id': json_id,
},
context_instance=RequestContext(request))
site.html
...
var id = {{ json_id|safe }};
var user_changes = "";
...
Dajaxice.base.submit_changes(callback, {'id': id, 'user_changes': user_changes});
ajax.py
from django.utils import simplejson
from dajaxice.decorators import dajaxice_register
#dajaxice_register
def submit_changes(request, id, user_changes):
...
return simplejson.dumps({'message':'You changed:%s in Site #%s!' % (user_changes, id)})
The best way is probably to store such information in the session to prevent manipulation
view.py
...
request.session['id'] = site.pk
...
ajax.py
...
id = request.session['id']
...
views
from calendar import HTMLCalendar
from django.shortcuts import render
def foo(request):
cal = HTMLCalendar()
calendar = cal.formatmonth(2013, 6)
return render(request, 'foo.html', {calendar = calendar})
template
{{calendar}}
It just display the html makrup. Not the calendar. So do I need to pass it as a template tag?
Try this:
from calendar import HTMLCalendar
from django.shortcuts import render
def foo(request):
cal = HTMLCalendar()
calendar = cal.formatmonth(2013, 6)
return render(request, 'foo.html', { 'calendar': calendar})
or you could even do dict(calendar=calendar)
and in template
{{calendar|safe}}
This is my views.py:
# Create your views here.
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.db import models
from display.forms import CodeForm
from display.forms import CodeFormSet
from ExamPy.questions.models import QuestionBase
def codepost(request):
if request.method == 'POST':
form = CodeFormSet(request.POST)
if form.is_valid():
titles = []
for i in range(0, self.total_form_count()):
form = self.forms[i]
title = form.cleaned_data['title']
if title in titles:
raise forms.ValidationError("Articles in a set must have distinct titles.")
titles.append(title)
return render_to_response('quesdisplay.html')
else:
form = CodeFormSet()
return render_to_response('quesdisplay.html', {'form':form})
Thus, when I click on submit button, it should show the quesdisplay.html without any form in it. But, it is taking me to some contact page which doesn't even exist.
Error:
The current URL, contact/, didn't match any of these.
I've tried all possible ways to debug this but its not possible as there is no trace of anything called "contact" in this.
Edit:
This is the warning I get:
/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:101: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")
[10/Nov/2011 05:34:17] "
As seen in the comment before, using Requestcontext solve your problem.
Here is the documentation about csrf_token : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it
As we can read :
Use RequestContext, which always uses
'django.core.context_processors.csrf' (no matter what your
TEMPLATE_CONTEXT_PROCESSORS setting). If you are using generic views
or contrib apps, you are covered already, since these apps use
RequestContext throughout.
So here it seems we're not using a generic view, neither a contrib app.
So what we need it to pass the RequestContext because it's like that csrf protection works in Django.
from django.core.context_processors import csrf
from django.shortcuts import render_to_response
def my_view(request):
c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)
or
from django.views.generic.simple import direct_to_template
def app_view(request):
return direct_to_template(request, 'app_template.html', app_data_dictionary)
or
from django.shortcuts import render_to_response
from django.template import RequestContext
def app_view(request):
return render_to_response('app_template.html',
app_data_dictionary,
context_instance=RequestContext(request))
Also the documentation speaks about : extras/csrf_migration_helper.py script.
Seems to be helpful for your case :)
Hope it helps ;)