Django template not receiving variables - python

I am writing a django template Configuration_Detail.html and it renders correctly on the relevant urls. It does not, however, take any variables whatsoever from the view class. I had a very similar template Configuration_List.html which worked fine, though that was a ListView not a DetailView.
Configuration_Detail.html:
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans 'MySite Database' %}{% endblock %}
{% block branding %}
<h1 id="site-name">{% trans 'MySite Database: Current Instrumentation Configuration' %}</h1>
{% endblock %}
{% block content %}
Here is some text {{name}} with a variable in the middle.
{% endblock %}
The page renders the title bar fine, but the content block becomes "Here is some text with a variable in the middle."
I believe it should be taking the variable {{ name }} from here.
views.py:
class ConfigurationDetail(DetailView):
model = Configuration
def getname(self):
name = 'debug'
return name
But it does not...
Any suggestions on how to fix this would be greatly appreciated.
Edited to add:
Models.py - Configuration:
class Configuration(models.Model):
title = models.CharField(max_length=100,unique=True,blank=False)
author = models.ForeignKey(User)
created = models.DateField("date created",auto_now_add=True)
modified = models.DateField("date modified",auto_now=True)
description = models.CharField(max_length=512)
drawing = models.ForeignKey(Drawing,blank=True,null=True)
instruments = models.ManyToManyField(Instrument)
def __unicode__(self):
return self.title
The get_context_data() method is using ctx['author'] = Configuration.author

For DetailView, an object variable is added in the context which points to the database object for which the view is being rendered. So in your template you can do:
{% block content %}
Here is some text {{ object.author.get_full_name }}
with a variable in the middle.
{% endblock %}
The get_full_name method is from the User object.

if i understood correctly you need to access a model property from within a template, but for that is sufficient to do {{ configuration.author }} without modifying the context data at all!
the DetailView puts in the context the selected model, accessible with the dot notation.

Related

Content not visible on webpage

I am creating a database website with python and django. My problem is that the content I try to get data from my class' fields doesn't appear on the id-page on django. I am able to make a successful search, and I get links for my searches. The name-field is visible in searches and on the page, but nothing else appears. When I click on the link, I go to luokka_id/number. I must be missing something but can't figure out what the problem is.
models.py
class luokka(models.Model):
nimi = models.CharField('Pääkäyttöluokka', max_length=100)
vara = models.CharField('Varakäyttöluokka', max_length=100)
varaaja = models.CharField('Varakäyttöluokka', max_length=100)
def __str__(self):
return self.nimi
and on the näytä_luokka.html (show class):
{% extends 'tietokanta/base.html' %}
{% block content %}
<center>
{{luokkalistaus}}
{{luokka}}
{{ luokka.nimi }}
{{ luokka.vara }}
{{ luokka.varaaja }}
</center>
{% endblock %}
and views.py:
def näytä_luokka(request, luokka_id):
luokkalistaus = luokka.objects.get(pk=luokka_id)
return render(request, 'tietokanta/näytä_luokat.html',
{'luokkalistaus': luokkalistaus})
I don't get any errors to help me out here. It's just an empty page, but it should show some extra data.
You have named the key of context as luokkalistaus not luokka, so the template should be:
{% extends 'tietokanta/base.html' %}
{% block content %}
<center>
{{ luokkalistaus.nimi }}
{{ luokkalistaus.vara }}
{{ luokkalistaus.varaaja }}
</center>
{% endblock %}

Display different content based on Boolean

I want to allow only manager to create view a content on my website, So I added an entry to my model Profile
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
manager = models.BooleanField(default=False)
By default is false
If false the user cannot see the content.
So I tried :
{% if profile == manager %}
SHOW THE CONTENT
{% else %}
Does not show the content
{% endif %}
But nothing change.
What did I do wrong ?
You need to do it like that :
{% if user.profile.manager %}
SHOW THE CONTENT
{%else%}
Does not show the content
{% endif %}
You forgot to add user since it is connected
You added a property on your model.
Your Profile object won't == manager. You need to access the property on your Profile object.
Try
{% if profile.manager %}
This will check is that profile object's manager property is True
If you have not overridden your view context you need to access your fields with object.
{% if object.manager %}
SHOW THE CONTENT
{%else%}
Does not show the content
{% endif %}

Issues With Block Title in Django Template

I'm trying to add a custom Title to my product pages using the block title tag in Django.
I have a view function to return data to a template for the product page:
def deal_by_detail(request, slug):
deal_detail = Deal.objects.filter(slug=slug)
return render(request, 'deals/deal_detail.html', {'deal_detail': deal_detail})
and URL for the deal_detail page:
url(r'^(?P<slug>.*)/$', deal_by_detail, name='deal_detail'),
In my 'deal_detail.html' page I have successfully displayed all the information from a particular product... like so:
{% for deal in deal_detail%}
{{ deal.title}}
{{ deal.price}}
{% endfor %}
However i'm having an issue with the block title. Since it comes before the aforementioned loop, i realize I can't reference the title like so:
{% block title %}{{deal.title}}{% endblock %}
I've also tried it like this:
{% block title %}{{deal_detail.title}}{% endblock %}
But that doesn't work either --nor does just {{ title }}
I also experimented with a duplicate of the other loop and that doesn't work either.
Here is what I have on the base template page that is extended from this deal_detail template:
<title>My Site - {% block title %}{% endblock title %}</title>
Just kind of stumped and not sure if I need a class based view or something I'm totally missing here. Thanks in advance.

Rendering streamfield block a certain way if booleanBlock is True

Hello I'm currently new to django/wagtail. I'm working on an about page that shows previous and current work/positions. I've made the positions streamfield blocks since the amount of experience isn't limited. Here is the code to my models.
#Create experience block
class ExperienceBlockStruct(StructBlock):
position_title = CharBlock(help_text="Enter a previous position title.")
description = CharBlock(help_text="Job description")
current_position = BooleanBlock(required=False, help_text="Check if
current position")
class Meta:
template = 'blocks/experience_block.html'
class ExperienceBlock(StreamBlock):
experience = ExperienceBlockStruct(icon="form")
And here is the page where I use the models
class About(Page):
profile_pic = "some image reduced code bc it currently works"
bio = RichTextField(blank=True)
resume = "some document reduced code bc it currently works"
experience = StreamField(ExperienceBlock())
content_panels = Page.content_panels + [
ImageChooserPanel('profile_pic'),
FieldPanel('bio'),
DocumentChooserPanel('resume'),
StreamFieldPanel('experience'),
]
Now the issue I'm having is how to render the blocks where the current_position = True in a different area than those that are not.
I've tried
templates/about.html
{% for block in page.experience %}
{% if block.current_position %}
{% include_block block %}
{% endif %}
{% endfor %}
But that doesnt render anything. I've also tried to
<div class="experience">
{% if value.current_position %}
{{ value.position_title }}
{% else %}
{{ value.position_title }}
{% endif %}
</div>
but that creates a new div for every block. What I would like to achieve is something like in blocks/experience_block.html
<div>
Current position(s): {% blocks with current_postion == True %}
</div>
<div>
Past position(s): {% blocks with current_postion == False %}
</div>
How could I go about achieving something like this?
Your first template snippet was almost correct - you just need to check block.value.current_position rather than block.current_position:
{% for block in page.experience %}
{% if block.value.current_position %}
{% include_block block %}
{% endif %}
{% endfor %}
This is because looping over page.experience gives you a series of BoundBlock objects that tell you the block_type (always 'experience' in your case) alongside the block value. See BoundBlocks and values for a more detailed explanation.
You can do the same thing in your experience_block.html template (using {% for block in value %} rather than {% for block in page.experience %}) - although note that the Meta template definition needs to go on ExperienceBlock rather than ExperienceBlockStruct, because that's the one that has access to the full list to loop over, rather than a single record.
To make things neater, I'd suggest defining a get_context method on the block, so that you're doing the data manipulation within Python code rather than inside the template...
class ExperienceBlock(StreamBlock):
experience = ExperienceBlockStruct(icon="form")
def get_context(self, value, parent_context=None):
context = super(ExperienceBlock, self).get_context(value, parent_context=parent_context)
context['current_positions'] = [block for block in value if block.value.current_position]
context['past_positions'] = [block for block in value if not block.value.current_position]
return context
class Meta:
template = 'blocks/experience_block.html'
This will make the variables current_positions and past_positions available on the template.

Django: How to display author of query of posts?

I'm trying to make individual pages for each author showing their name and posts. I can't seem to get the username displayed.
views.py
class UserProfileView(generic.ListView):
template_name = 'howl/user-profile.html'
context_object_name = 'user_howls'
def get_queryset(self):
author = self.request.user
u = User.objects.get(username=author)
return Howl.objects.filter(author=u)
models.py
class Howl(models.Model):
author = models.ForeignKey(User, null=True)
content = models.CharField(max_length=150)
Here is where I'm stuck.
user-profile.html
{% extends 'howl/base.html' %}
{% block content %}
<h1>User: {{user_howl.author}}</h1>
{% for user_howl in user_howls %}
<ul>
<li>{{user_howl.content}}</li>
</ul>
{% endfor %}
{% endblock %}
The content is displayed just fine, but the heading just says "User: ", how do I give it a context without using a for loop?
I've tried:
{% for author in user_howls.author %}
<h1>User: {{author}}</h1>
{% endfor %}
and
{% if user_howls.author %}
<h1>User: {{user_howl.author}}</h1>
{% endif %}
Still the same outcome, displaying "User: "
user_howls is a queryset so it won't have an author attribute, you need to get the author of the iterated object
{% for howl in user_howls %}
<h1>User: {{ howl.author}}</h1>
{% endfor %}
More to the point though, it doesn't make sense to start from a Howl list, when you are just returning the results for the user_profile, nor does it make sense to use a ListView. so instead, start from the user and then look up its howls
user_obj.howl_set.all()
Since your queryset is based on the posts belonging to the current user, you can shortcut all of this and just show the user directly:
User: {{ user }}

Categories

Resources