How to show data from django models whose boolean field is true? - python

verified = models.BooleanField(default=False)
I want to show only that objects in frontend whose verified field is true in Django models.

There are many ways
you can handle this on your views
in views.py
modelList = modelname.objects.filter(verified=True)
also you can handle it on HTML
in views.py
modelList = modelname.objects.all()
in html
{% for models in modelList %}
{% if models.verified == True %}
# Your Code
{% endif %}
{% endfor %}

You filter the items with:
MyModel.objects.filter(verified=True)
with MyModel the model that contains the verified field.

you have to ways to achive that that either it with your views or html
first views
you can filter your model to return only object which is verfied like this
name = modelname.objects.filter(verified=True)
second way
or you can pass in html while you are requesting all object of that field in views
in views
name = modelname.objects.all()
then in html while fetching data
{% for name in models %}
{% if name.verified == True %}
then pass the object which are verified
{% else %}
pass another data
{% endif %}
{% endfor %}
i hope now you got my point tell me if you got any error while implementing any of these code

Related

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 %}

how do i access the values in a session dynamically using django?

(Django , Python) I have created a list of book objects and it is being passed as context in my views.py along with the current session. On my template, i was to check if the books in that list are stored in the session, and if they are i want to access some info relating to that book within that session. how do i access the books in the session dynamically? is there a way?
i know i can access them by using "request.session.name" (where "name" is the same of the space in the session it is stored)
There are several book titles saved in the session, the way they are saved are as follows (in a function under views.py)
request.session["random book title"] = "random dollar price"
i want to access that "random dollar price" dynamically in a template.
this is the block of code in the template
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session.??? }}
{% endif %}
{% endfor %}
Thank you in advance!
You can make a custom template tag to look up by attribute like here
Performing a getattr() style lookup in a django template:
# app/templatetags/getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
Now change your template to
{% load getattribute %}
{% for book in book_list %}
{% if book.title in request.session %}
{{ request.session|getattribute:book.title }}
{% endif %}
{% endfor %}
This is a basic custom template tag example:
Django - Simple custom template tag example
and docs:
https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/
From what I remember from my django days should work
You can put session data in a dictionary and send this data to target template when you want to render it in view function.
def some_function(request):
context={
'data':sessionData #put session data here
}
return render(request,"pass/to/template.html",context)
Now you can access 'data' in your template.html
I think you should just send a list of book names from your view instead of a queryset so when you are crosschecking with session you use the title directly instead.
{% for book in book_list %}
{% if book in request.session %}
{{ request.session.book }}
{% endif %}
{% endfor %}

How to use MultipleChoiceField in django-widget-tweaks?

I have form with MultipleChoiceField field which has dynamic list for choices. With the help of this form users can select data and add them to database.
Sometimes dynamic list can be empty []. So I want to show message in template when its empty but next code didnt show me message. I use django-widget_tweaks application in my template. Where is my mistake?
forms.py:
class RequirementForm(forms.ModelForm):
symbol = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
class Meta:
model = Requirement
fields = ('symbol',)
requirement_add.html:
{% load widget_tweaks %}
<form method="post" action="{% url 'project:requirement_add' project_code=project.code %}">
{% for field in form %}
{% render_field field class="form-control" %}
{% empty %}
<p>Form is empty!</p>
{% endfor %}
</form>
The {% empty %} clause will display the text only when the given array is empty or it doesn't exist. In this case the form will always have fields even if the choices are empty.
You should try checking directly with the choices and show the form only when its not empty.

Backward relationship in Django templates

I am trying to display data from different models in my template and I have no idea why it doesn't work properly.
Models.py:
class Company(models.Model):
name = models.CharField(max_length=100)
class Location(models.Model):
company = models.ForeignKey('Company',
related_name='locations')
Views.py:
def sth(request):
loc_list = Location.objects.all()
return render(request, 'blabla/index.html', {'loc_list': loc_list})
Template:
{% for loc in loc_list %}
{% for entry in loc.company_set.all %}
{{entry.name}}
{% endfor %}
{% endfor %}
Why the name of the company is not showing?
You foreign key relationship is the wrong way around... the way you have currently defined them, a Location can have only one Company associated with it, but in your template you are trying to fetch a list of Companys.
For your template logic to work, your models would have to be defined as follows:
class Company(models.Model):
name = models.CharField(max_length=100)
location = models.ForeignKey('Location')
class Location(models.Model):
# You probably need some other fields in here.
Then this would work:
{% for loc in loc_list %}
{% for entry in loc.company_set.all %}
{{entry.name}}
{% endfor %}
{% endfor %}
Only use "_set" when accessing backwards relationships. There is no
loc.company_set.all
because each location only has one company (that is what a ForeignKey is. You can access the location's company by doing loc.company). If you want location to have multiple companies, either see solarissmoke's answer (where you put the ForeignKey attribute on Company and not on Location), or use a ManyToManyField relationship (this will allow companies to have multiple locations and each location to have multiple companies).
Then you can access all the companies of a given location by doing this in the template:
{% for loc in loc_list %}
{% for entry in loc.company.all %}
{{entry.name}}
{% endfor %}
{% endfor %}
You can also access all the locations for a given company by using the related_name (company.locations).
Short answer:
{% for loc in loc_list %}
{{loc.company.name}}
{% endfor %}

Django template not receiving variables

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.

Categories

Resources