fetch variables in django templates - django

I am new to django .
I am facing a small problem but unable to solve it.
In my template when I try to access any variable using {{ }} but it returns blank while displaying something as detailview.whereas it works fine in listview.
CODE:urls.py
urlpatterns = patterns('',
url(r'^$', ListView.as_view(
queryset=Profile.objects.all().order_by("First_Name"),
template_name="STUDENT_REGISTRATION.html")),
url(r'^(?P<pk>\d+)/$',DetailView.as_view(
model=Profile,
template_name="Profile.html")),
TEMPLATE:
{%extends "base.html" %}
{% block content %}
<h2>Registration No. :- {{ Profile.Registration_No }} <br>
Full Name : {{ Profile.First_Name }} {{ Profile.Last_Name }} </h2>
<div class="Profile_meta">
{{ Profile.Date_of_Birth}}
</div>
<div class="Profile_body">
{{ Profile.Permanent_Address|safe|linebreaks }}
</div>
{%endblock%}
Plz help..

You should refer to your Profile instance as:
{{ object.First_Name }} {{ object.Last_Name }}
By the way, take a look at PEP8, try to keep CamelCaseNames for class names and underscores_names for instances. It will make your code easier to read.

Related

Django ListView works but DetailView not displaying Model Data

I am helping my daughter with her computing Project for school. It is a simple generic forum type application.
She has a ListView for a model which works fine:
{% extends 'users/main.html' %}
<!-- Here is where our content will begin -->
{% block content %}
<h1>This is posts.html!</h1>
<br/>
{% for obj in object_list %}
<h2>{{ obj.topic }}</h2>
{{ obj.date_posted }}
<br/>
{{ obj.content }}
<br/>
Author: {{ obj.author }}
<br/><br/>
{% endfor %}
{% endblock %}
She then added a DetailView which is simply the same code with the loop removed:
{% extends 'users/main.html' %}
<!-- Here is where our content will begin -->
{% block content %}
<h1>This is posts.html!</h1>
<br/>
{{ obj.id }}
<h2>{{ obj.topic }}</h2>
{{ obj.date_posted }}
<br/>
{{ obj.content }}
<br/>
Author: {{ obj.author }}
<br/><br/>
{% endblock %}
This is then called with a '....post/1/' (post id = 1 does exist (checked via DB Browser and in the ListView) and the path and naming of the template is correct.
Frustratingly, this displays the page but not the details inside the django temp language brackets (object.topic etc)!
When I look at the page source for the section dealing with the detail, I get:
screenshot of page
and the source code looks like so:
<h1>This is posts.html!</h1>
<br/>
<h2></h2>
<br/>
<br/>
Author:
<br/><br/
It is simply ignoring the bracketed templating code - any ideas?
Django DetailView returns 'object' inside context by default.
If you did not change 'context_object_name' variable, then use {{object}} instead of {{obj}}
<h1>This is posts.html!</h1>
<br/>
{{ object.id }}
<h2>{{ object.topic }}</h2>
{{ object.date_posted }}
<br/>
{{ object.content }}
<br/>
Author: {{ object.author }}
<br/><br/>
Really thanks a lot for all of this.
I corrected my template to include 'object' and made it march all conventions to avoid having to send in context information.
It still wouldn't work.
I rebooted localhost repeatedly because it all made no sense.
Finally, I rebooted my daughters PC and immediately, everything worked.
A lesson learned and as a dad helping a 17 year old daughter who did his Computer Science degree 40(!) years ago, another lesson in how complicated and challenging understanding a framework can be.
I must say - it has been fun.
Thanks again,
Howard.

How to pass the value from v-for to a simple django filter

I have the following component in a django template
<div class="trow" v-for="(item, idx) in data">
</div>
Now if I try to write the following inside the div
{{ item.co.name }}
I won't get the value, I will have to write the following to get the value
{% verbatim %} {{ item.co.name }} {% endverbatim %}
Now my problem is that I have to do something with this value so I wrote a simple filter like this
from django import template
from django.templatetags.static import static
register = template.Library()
#register.filter
def define(val=None):
return static(f"images/{val.lower()}.svg")
but I can't do the following
<div class="trow" v-for="(item, idx) in data">
{% verbatim %} {{ item.co.name | define }} {% endverbatim %}
</div>
I've also tried a lot of combinations with no luck, how can I solve this?
Edit: I changed the data and added the path I want inside it, now I want to use this value inside an img tag like this
<img src="{{ item.icon_path }}">
but this again won't give me the value because it needs a verbatim tag, and doing it like this
<img src="{% verbatim %}{{ item.icon_path }} {% endverbatim %} ">

Django template if statement always evaluates to true

This seems like it should be pretty straightforward, but for some reason I am unable to solve this problem. I'm using Django 1.4. I am trying to do a basic check to see if a list QuerySet is empty or not during template rendering, but the if statement I'm using seems always to evaluate to true.
I have a Django template that reads:
{% extends 'includes/base.html' %}
{% if object_list %}
...
{% block data %}
{% for object in object_list %}
...
{{ object.create_date }}
...
{% endfor %}
{% endblock data %}
...
{% endif %}
'base.html' has the block:
<body>
{% block content %}
...
<div class="row-fluid">
<div class="span12">
{% block data %}
<div align="center"><i>No data.</i></div>
{% endblock data %}
</div><!-- span12 -->
</div><!-- row -->
{% endblock content %}
...
</body>
The view function generating the QuerySet is here:
def barcode_track(request, model):
query = request.GET.get('barcode_search', '')
object_list = model.objects.all()
if query:
object_list = model.objects.filter(barcode__icontains=query)
return render_to_response('barcode_track/barcode_list.html',
{'object_list': object_list, 'query': query},
context_instance=RequestContext(request))
Which is called via this form:
<form id="barcode_search_form" method="get" action="" class="form">
<input type="text" name="barcode_search" value="{{ query }}" />
<button type="submit" class="btn">Search</button>
</form>
And the urls.py line:
urlpatterns = patterns('barcode_track.views',
url(r'^$', 'barcode_track', {'model': Barcode},
name="barcode_track"),)
The idea is that results will only be presented if they exist in object_list, and otherwise the parent block will remain unaltered. I have tried changing the name of object_list, and I have printed {{ dicts }} to the page to ensure that object_list is, in fact, empty (which it is). I am not using a generic view, although I realize that the name suggests as much. I have actually had this trouble in a different app I wrote using similar logic, so I must be doing something systematically incorrectly.
What am I missing here?
You can't wrap control flow tags like if around a block. Your problem is that the child template's definition for block data is being used simply because it's there.
You can fix it by placing the if tag inside block data. If you want to inherit the parent's contents when the list is empty, add an else case that expands to {{ block.super }}.

Django template not showing database contents

This is for certain a newbie mistake, I have googled for plenty of hours now, not finding a working solution. I assume part due to not being sure what to search for exactly.
I am working on a tiny blog application, I have models for user, post, blogComment and that is all.
I have written views for blogIndex and for blogPost, that is a listing of all posts and a listing of specific posts.
The blogIndex is working in the view that it belongs to, it shows {{ post.content }} {{ post.author.firstname }} and so on with no problem.
The blogPost is however not. The view looks like this:
def blogPost(request, postID):
blogPost = post.objects.get(id=postID)
return render_to_response("blog_post.html", {"post":post})
The blog_post.html looks like this:
title: {{ post.title }}</br>
content: {{ post.content }}</br>
datetime: {{ post.datetime }}</br>
author: {{ post.author.first_name }} {{ post.author.last_name }}</br></br>
{% for comment in post.blogcomment_set.all %}
Comment.firstName: {{comment.firstName}}</br>
{{comment.lastName}}</br>
{{comment.email}}</br>
{{comment.datetime}}</br>
{{comment.content}}</br>
{% endfor %}
With the same code in blog_index.html, I get a proper listing of title, content and so on.
This is from urls.py:
url(r'^blog/$', blogIndex),
url(r'^blog/(?P<postID>\d+)$', blogPost),
I suspect something is wrong with the regex?
I suspect something is more likely wrong with the view?
This is the view for blogIndex, which is working, but maybe helps with answers:
def blogIndex(request):
posts = post.objects.all()
return render_to_response("blog_index.html", {"posts":posts})
This, finally, is the code in blog_index.html:
{% for post in posts %}
<h3>{{ post.title }}</h3>
{{ post.content }}
<p>Posted by: {{ post.author.first_name }} {{ post.author.last_name }}<br /> At:
{{ post.datetime }}</p>
<p><strong>Comments: </strong><br />
{% for comment in post.blogcomment_set.all %}
By: {{ comment.firstname }}<br />
Title: {{ comment.title }},<br />
Content: {{ comment.content }}<br />
Date: {{ comment.datetime }}</p>
{% endfor %}
{% endfor %}
Links to possible solutions or pointing me on the nose for being narrow sighted are both welcome input.
def blogPost(request, postID):
blogPost = post.objects.get(id=postID)
return render_to_response("blog_post.html", {"post":post})
Should be:
def blogPost(request, postID):
blogPost = post.objects.get(id=postID)
return render_to_response("blog_post.html", {"post":blogPost})

Tiny_mce + comments in Django = problem

I written a small comments app.
Part of forms.py:
class TinyCommentForm(CommentSecurityForm):
comment = forms.CharField(widget=TinyMCE(attrs={'cols': 80, 'rows': 30}))
Part of models.py:
class TinyComment(BaseCommentAbstractModel):
comment = tinymce_models.HTMLField()
Part of template which using TinyCommentForm:
{% if user.is_authenticated %}
{% get_comment_form for object as form %}
<form action="{% comment_form_target %}" method="POST">
{{ form.comment }}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="submit" name="post" class="submit-post" value="Add" />
</form>
{%endif%}
Here I can adding and saving comments, but only without tinymce editor and that is working fine.
If I add to my comment form in template field: {{form.media}} tinymce editor show up, but if I write something there, my POST form seems to be without content, saying that I need to write something to it.
Giving {{form.media}} to <HEAD> sector does not working even if I render through my view the TinyCommentForm as 'form' to this template.
So i tried to import JS more manually and I add to <HEAD> section(using Django 1.3):
<script type="text/javascript" src="{{STATIC_URL}}js/tiny_mce/tiny_mce.js"></script>
Then I check that the src link and it is correct.
So next I add second line there:
<script type="text/javascript" src="{% url tinymce-js "NAME" %}"></script>
Then I create NAME/tinymce_textareas.js with JS code and add containing this folder to TEMPLATE_DIRS. MY urls including tiny_mce urls. But still without results.
Does somebody could illumine me a little?
Got it working good. Answer:
{% if user.is_authenticated %}
{% get_comment_form for object as form %}
<form action="{% comment_form_target %}" method="POST">
{{ form.media }} <!-- This is needed -->
{{ form.comment }}
{{ form.content_type }}
{{ form.object_pk }}
{{ form.timestamp }}
{{ form.security_hash }}
<input type="submit" name="post" class="submit-post" value="Add" />
</form>
{%endif%}
And any JS in section was needless.
But the devil lives in my forms.py which should looks like this:
class TinyCommentForm(CommentSecurityForm):
comment = forms.CharField(widget=forms.Texarea)
And now everythigng works properly.
Edit: The reason of why my comment form need to using widget=forms.Texarea is, i think, that my texareas.js has mode : "textareas". If I am wrong please correct me.