I have the following code which seeks to pull a number "counter" out of a DB, add a value ("+1") to it, save the new "counter" value, wait for a specified amount of time, and then start again from the beginning. This same function would be called via a view on Django, so it is also responsible for generating the template as well.
According to the development server, the function IS performing the simple arithmetic and saving the new value to the DB. As I can see the value being updated every time I refresh the Django-Admin.
However, it fails to load the template. Specifically, the page stays loading indefinitely, while the calculations happen.
Sorry if the code isn't perfect, I'm new to everything ever.
Also, please note that I have previously tested the entire ecosystem with a much simpler index function (generates simple HTML) and the template indeed generates. So I'm assuming that the problem must come from this code specifically.
Views.py:
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.template import Context, loader
from home.models import DeathNum
import datetime
import time
def index(request):
while True:
counter = DeathNum.objects.get(pk=1)
counter.deaths += 1
counter.save()
print('Added # %s ' % datetime.datetime.utcnow())
time.sleep(35)
return render(request,
'home/basenum.html',
{'number_post': str(counter)}
)
basenum.html (extending template):
{% extends "home/index.html" %}
{% block content %}
<br />
<div class="banner">
<div class="bannerNum">
<p div class="numberOf">
Number of deaths in Blank since 1999:
</p>
<br /><br /><br />
<p class="death1">
{{ number_post }}
</p>
</div>
</div>
{% endblock %}
you have to change two things in view function and queryset.
def index(request,pk):
counter = DeathNum.objects.get(pk=pk)
"""your logic here""
return render(request, 'home/basenum.html, {'number_post': str(counter)})
make sure your urlconf should be correct
Related
Summary:
The purpose of this particular Django web app is to just show some lorem ipsum text on the home page, like a blog post. Django is not serving my blog post content. I know the problem is either with my views.py or urls.py (or both).
Details:
I’ve got the data declared inside my models.py. I’ve got my views.py to instantiate the model. I migrated sqlite and successfully logged into the Admin Dashboard and entered some placeholder data.
I’m trying to get Django to serve the placeholder content that I entered into the Admin Dashboard, but instead it’s blank.
Here is my what my test case looks like: https://i.imgur.com/IuOl3G4.jpg
To describe it, you can see The Blog Post, Date, Image, and Body Text HTML heading elements parsed, but none of the content is showing.
Here is my app’s urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.mortems, name='home'),
]
I’ve tried swapping out the quotation marks for the first path() parameter with alls/landings. I’ve tried swapping the name parameter from home to mortems. I also tried using mortem (without the s). None of these changes help.
I've also tried Googling (with variations):
'body text django not showing template'
'django not showing text contents'
Which turned up (among other) SO questions and answers which kind of sound related but are completely different from my issue:
Django Message framework is not showing message in template
Why django template is not showing any output?
Here is my app’s views.py:
from django.shortcuts import redirect, render, get_object_or_404
from mortems.models import Mortem
def mortems(request):
mortem = Mortem.objects.order_by('-pub_date')
context = {'mortem':mortem}
return render(request, 'alls/landings.html', context)
For what it is worth, here are the relevant lines in my model:
class Mortem(models.Model):
title = models.CharField(max_length=161)
pub_date = models.DateTimeField()
image = models.ImageField(upload_to='media/')
body = models.TextField()
now = datetime.datetime.now()
Also, here is my template with the relevant problematic lines (42-50):
<h1> BLOG POST:</h1>
<h4>Date: {{ mortem.pub_date_preference }}</h4>
<br />
Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" />
<br />
<!-- Body text should go here : -->
Body Text:
<p>{{ mortem.body|safe }}</p>
The full source code is up on GitHub. Here is the 'mortems' app source code specifically.
For generous SO users with time on their hands, I guess I’m accepting pull requests. haha
I think you need to update the views.py as:
from django.shortcuts import redirect, render, get_object_or_404
from mortems.models import Mortem
def mortems(request):
mortems = Mortem.objects.all().order_by('-pub_date') # returns an iterable queryset
context = {'mortems':mortems} # using plural as it's a list like object
return render(request, 'alls/landings.html', context)
In the template code, you need to iterate over the list to display a single object one at a time. i.e
<h1> BLOG POSTs:</h1>
{% for moertm in mortems}
<h4>Date: {{ mortem.pub_date_preference }}</h4>
<br />
Image: <img src="{{ mortem.image.url }}" class="img-responsive center-block" style="max-height:300px;" />
<br />
<!-- Body text should go here : -->
Body Text:
<p>{{ mortem.body|safe }}</p>
{% endfor %}
I am trying to hide a content when a user is visiting his own profile. I tried the code below but it didn't work. What could be wrong.
{% if request.path == "/account/users/{{ request.user.username }}/" %}
{% else %}
<img src="https://tyllplus.com/static/arrow-orange-down-vector-1.png" width="30" height="30">
{% endif %}
(Advanced) string processing should not be done in the template. Especially not with URLs, since you might later want to change the view. Even if you manage to get it work, if you later have a prefixed path, it can start failing. This method would also heavily depend on the format of the URL: if you later specify a URL where you use the id instead of the username, then you will need to look for all all URL processing that depends on this format. This is not elegant design.
Of course simple processing is no problem. For example adding comma separators to a number, etc. is typically handled by template tags. But URLs - in my opinion - do not really fit in that category.
You better encode this logic in the view (or make sure that you easily can detect it with elements from the view).
For example for a DetailView:
from django.views.generic.detail import DetailView
from django.contrib.auth.models import User
class UserDetailView(DetailView):
model = User
context_object_name = 'my_user'
template = 'user_detail.html'
We know that the my_user variable will carry the User object ot display, so then we can verify with:
{% if my_user != request.user %}
<!-- show something -->
{% else %}
<!-- show something else -->
{% endif %}
I am new to Django and in need of some help. I have my database entries being displayed on a template (6 entries). I am aware that to sort your database objects, you need to write Model_Name.objects.all().order_by('Choose_Sort_Option') in the views.py. I would like to make this function a link in that same template. So far, the only thing I've been able to come up with is making a new view, new url pattern, and new template just to display that one new sort. I don't want have to make 30 pages just for sorting. I am thinking that I need to assign that line of code above to a variable(see product d and product_a below). Then i would call that variable in the template, but I'm not sure how to replace the existing list of database items. In short: How do I create clickable links to sort my database objects all within the same template. This is already done in the admin. Thank you!
my views.py:
from django.http import Http404, HttpRequest
from django.contrib import messages
from vendor_db.models import Itemo
from django.db.models import Q
from django.shortcuts import HttpResponse, HttpResponseRedirect,
render_to_response, render, redirect, get_object_or_404
def index(request):
return render(request, 'vendor_db/index.html')
def vendors(request):
items = Itemo.objects.all()
var_2 = request.GET.get("q")
product_d = Itemo.objects.all().order_by('-Product_Name')
product_a = Itemo.objects.all().order_by('Product_Name')
if var_2:
items = items.filter(Vendor_Name__icontains=var_2)
context = {'items': items,
'product_d' :product_d,
'product_a' :product_a,
}
return render(request, 'vendor_db/vendors.html', context)
my template (it is already displaying all of my database objects in an arbitrary order):
{% extends "base.html" %}
{% block content %}
{% load static %}
<h2>All Vendors</h2>
<h3>Search</h3><div>
<form method='GET' action=''>
<input type='text' name="q" placeholder='Search Vendors'/>
<input type='submit' value='Search'/>
<form action="{% url 'vendors' %}">
<input type="submit" value="Reset">
</form>
</form>
<br>
{% if items %}
{% for stuff in items %}
<a href="{% url 'vendors_detail' stuff.id %}">
{{ stuff.Product_Name|capfirst }}<div></div>
</a>
{% endfor %}
{% else %}
<p>No Results Found</p>
{% endif %}
<h3>Sort by:</h3>
Product Name
{% endblock %}
EDIT
While I am sure the 2 answers below would the do the trick, I was unable to comprehend (my own fault). I places my database entries in a table and used a javascript library to change the sort order just by clicking the column header. You can see the question I asked and the code here
In your model.py class use
Class XYZ()
...................
...................
class Meta:
ordering = [
"your_first_field_name",
"your_second_field_name",
........................
]
You could use a form with a variable as you said, pass the form back to the same view and get the sort option from that and create the sorted query for your product items dynamically or using if statements. Then rerender the page. This means only one view would be needed.
Or you may be interested in an app called django-tables2, it gives you the ability to render a nice table which can then be sorted as you wish by clicking on arrows.
How would I return text with template markup from an expression and have the tags rendered by Jinja? It looks like Jinja only makes one pass, and just escapes and dumps the text in without further processing it as part of the template (which would be the right thing 99% of the time). Is there a way to make two passes with the renderer, or render the result of my expression first and pass it to the template?
Simplified Problem
I have included further details below in case there is more to this than I think, but this should be all the information needed for the problem.
If do_render() returns <p>Hello there {{ current_user.name }}</p>, how could I do the following in a template, so that I obtain the value of name?
<div>
{{ do_render() }}
</div>
This renders as <div><p>Hello there {{ current_user.name }}</p></div>, when I want <div><p>Hello there Sam</p></div>.
Complete Problem
I'm using Flask, Flask-Bootstrap, and Flask-Nav with Python 2.7. I could just create the navigation bar myself and none of this would matter, but "autogenerated" sounded so much simpler...
Flask-Bootstrap provides a Flask-Nav compatible renderer; I have subclassed it to modify my navigation bar. I'm trying to add a logon form in the navigation bar, right-aligned. Because the BootstrapRenderer generates the complete navbar, I have to inject my form into it prior to the closing tags (alternatively, I could skip super() and do it all myself).
class MyRenderer(BootstrapRenderer):
def visit_Navbar(self, node):
""" Returns the html for a Bootstrap navigation bar. """
root = super(MyRenderer, self).visit_Navbar(node)
# Replace the navbar style with my custom css
root['class'] = 'navbar navbar-mystyle'
# Here I try injecting a login form. This is the correct position,
# and it inserts properly; it just treats {{, }}, {%, %}
# as nothing special.
elem = root[0][1] # div class="navbar navbar-collapse"
elem.add(
dominate.util.include(
os.path.join(
config.app_path_root, app.template_folder, 'inc/login_form.jinja')))
# I have also tried
# elem.add('{% block nav_right %}{% endblock %}')
# thinking I would use inheritance later (still my preference).
return root
I then register the renderer with Flask-Nav, and render it by inserting {{ nav.main_nav.render() }} into my base template, which my .html files inherit from. All of this works.
My problem is that I only want the login form when the person is not logged in.
The login_form is:
{% if not current_user.is_authenticated() %}
<form class="navbar-form navbar-right" role="search" action="login" method="post">
<div class="form-group"><input type="text" name="username" /></div>
<div class="form-group"><input type="password" name="password" /></div>
</form>
{% else %}
<div class="navbar-right">
Welcome {{ current_user.name }} | Logout
</div>
{% endif %}
My HTML output is identical to the template; neither statements, expressions, nor comments are treated as such.
Other attempts: I have generated the navbar first, then passed it to the template via render_template('index.html', navbar=navbar) but I have the same problem. I have also tried macros. I'm about ready to write my navigation menu in the base template myself and be done with it, but now it feels like that would be giving up.
Other than {% include ... %} and {% extends ... %}, you're not going to be able to have the template system automatically render something that's added to a template during runtime without a bit of customization.
The beautiful part about Jinja 2 is that its API is very powerful and you can do many things without having to feel like your "hacking" the system. To do what your first example is implying, you just need to have the function render the included template snippet snd return a rendered string. If you're expecting the template to be rendered with the context of the parent template, that's not gonna happen automatically, but that's not a problem since you can pass in whatever you need directly in your function call in the template.
I'm currently trying to learn Django from the book and I read most of it and am now trying to write a webapp of my own. I just really can't figure out how they all interact and how they aren't fitting together.
My urls.py file reads like this...
from django.conf.urls.defaults import patterns, include, url
from users.views import homepageview, submitted, referral_create
urlpatterns = patterns('',
(r'^$', homepageview),
(r'^submitted/$', referral_create),
the views.py file looks like this...
# Create your views here.
from django.shortcuts import render_to_response
from django import forms
from datreferral.users.forms import ReferralCode
def homepageview(request):
now = 'your damn referral code'
return render_to_response('datreferraltemplate.html', {'now': now})
def referral_create(request):
if request.method == 'POST':
form = ReferralCode(request.POST)
if form.is_valid():
new_code = form.save()
return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,)))
else:
form = ReferralCode()
The form.py file looks like
from django import forms
class ReferralCode(forms.Form):
referralcode = forms.CharField()
and the template looks like this...
{% extends "base.html" %}
{% block title %}
Enter your referral codes!
{% endblock %}
{% block content %}
<h1>Enter your code</h1>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="" method="POST">
<p>Subject: <input type="text" name="subject" value="{{ referralcode }}"></p>
<input type="submit" value="Submit">
</form>
{% endblock %}
Hopefully that's enough info.
I am looking for two things. First off, when I try to view the page after submitting the form i get no where because I assume that the "if request.method == 'POST':" is not triggering. Obviously its something pretty obvious but I'm in one of those modes where I can find the bug for the life of me.
The second question I have is basically is plea for help. somehow after reading through those chapters multiple times I can't seem to nail down how all of the pieces interact with each other. I know that the template and the urls.py and the views.py interact and I get (I think) but I can't really grasp how the database and forms interact with each other and with the views/templates. like say I just wanted to a simple form where whatever the use inputted is written into the database... How would you do that? I'm using postgres if that matters.
Note: the form and the in the template is a modified version of code i found on here and tried to manipulate to meet my needs but failed so don't be overly thrown off if that doesn't make sense I wasn't able to mess with that part that much yet because of these problems.
As I'm new to web development I really appreciate any one willing to help me or point me in the right direction.
You don't return anything in you else clause. A views must always return a response, which can be pretty much anything, but in most cases you will return a instance of a (sub)-class of HttpResponse (I really like the render shortcut). It is a good idea to have a default return at the bottom of you view, add some early returns for "special" responses and otherwise let the execution reach the default return - this way you never have the case where you return nothing.
You have to use a Model to save data (have you work through the tutorial?). Usually the excution model is the following:
you app gets a request and the urls.py is searched for a view that should be called
the request is passed through the middleware
you view is called and "does" something. I.e. it fetches data from the database (again using a model) or stores something in the db (or saves a uploaded file, sends a mail, etc. - aview can really do anything)
you view returns "something"
the returned "something" is passed through the middleware and will eventually be tranformed in a stream of data that is passed to the browser
Thats it. This is a bit simplified but it pretty much covers all important parts.
Well, there are quite a few things wrong here.
First is that your form is being rendered by the base view, homepageview, and is submitting back to that same URL. However the form processing logic is in a separate view, which isn't being called. Either change the action parameter of the form to point to the other URL or - better - move all the logic into the same view.
Secondly, your form processing view isn't returning a response or rendering a template. That's an error in Django, and if you had managed to call that view you would see an exception.
Thirdly, I find it hard to believe you've read the entire Django book and not seen anything about models or databases. You've got no indication here that you've set up any models, but without them Django won't write anything to a database. You'll need to do that, then change your form into a ModelForm subclass, after which you can call form.save() successfully.