if statement in Django template not working - python

I can't find out why this is not working.
It always goes to {% else %} block.
The text in machine_model is something like "Lidl - Food Market" or "Kaufland - Buy Here" or something other without those two words.
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django import forms
from django.urls import reverse
class MyName(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class MyModel(models.Model):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class MySide(models.Model):
name = models.CharField(max_length=50, unique=True)
class MyMachine(models.Model):
date_delivery = models.DateTimeField(null=True)
machine_name = models.ForeignKey(MyName, on_delete=models.PROTECT)
machine_model = models.ForeignKey(MyModel, on_delete=models.PROTECT)
machine_serial = models.CharField(max_length=15, default='0')
use_side = models.ForeignKey(MySide, on_delete=models.PROTECT)
views.py
from django.views.generic import ListView
from .models import MyMachine
class MyMachineListView(ListView):
model = MyMachine
template_name = 'site/home.html'
context_object_name = 'machines'
ordering = ['date_delivery']
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
site_title = 'Home'
context["site_title"] = site_title
return context
home.html
{% extends "site/base.html" %}
{% load static %}
{% block content %}
{% for machine in machines %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<small class="text-muted">{{ machine.date_delivery|date:"d.F Y" }}
</small>
</div>
<h2><a class="article-title" href="">{{ machine.machine_name }} - {{ machine.machine_serial }}</a></h2>
{% if 'Lidl' in machines.machine_model %}
<p class="article-content">{{ machine.use_side }} - Lidl</p>
{% elif 'Kaufland' in machines.machine_model %}
<p class="article-content">{{ machine.use_side }} - Kaufland</p>
{% else %}
<p class="article-content">{{ machine.use_side }} - {{ machine.machine_model}}</p>
{% endif %}
</div>
</article>
{% endfor %}
{% endblock content %}
everything else is working fine. Thank You in advance!

I see two problems here.
One, you're referencing machines.machine_model, but machines is a queryset. I'm somewhat surprised referencing machine_model on it doesn't just fail with a rendering error. It should be machine.machine_model, since that's your loop variable.
That leads us to the second problem. machine.machine_model is a foreign key reference to another model, not a string. There's no string that's in a model instance (barring defining the membership function yourself). I haven't personally tested but I don't think Django stringifies on the fly (as it will when you reference {{ machine.machine_model }}). Try it with if ... in machine.machine_model.name.

Related

In views.py file ==> category_posts = Post.object.filter(category=cat) returns an empty query set. The 'Post' model has sample posts with categories

I am creating a blog application in django where i encountered this unusual issue. I am not being able to filter and display blog posts category wise. Please find my code below. Thanks in advance. I have spent two full days trying to figure this out and still
got nothing.
MODELS.py
This is the model which i have created for a blog post.
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
category = models.CharField(max_length=255, default="uncategorized")
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
#return reverse('article-detail', args=(str(self.id)))
return reverse('homepage')
VIEWS.py
This is the view that i have created for a category wise blog posts.
def CategoryView(request,cat):
category_posts = Post.objects.filter(category=cat)
return render(request,'categories.html',{'category_posts':category_posts})
URLS.py
The urls.py file.
path('category/<str:cat>/', CategoryView, name = 'category'),
CATEGORIES.html
This will be the final display page where the category_posts is displayed as an empty queryset. The for loop is unable to run because category_posts is an empty queryset. Single word categories are also empty(to rule out a slugify issue)
{% extends 'base.html' %}
{% load static %}
{% block content %}
<ul>
{% for post in category_posts %}
<li>
<div class="category">
{{ post.category }}
</div>
<a href="{% url 'article-detail' post.pk %}">
<h3><b>{{ post.title }} </b></h3>
<p class=card-date>
<big>{{ post.author }}</big>
<small>-{{ post.post_date }}</small>
</p>
<p class="excerpt-text">{{ post.body | slice:"100" |safe}}</p>
<div class="article-thumbnail">
<img src="{% static "images/bg.png" %}" alt="article-thumbnail" >
</div>
<div class="overlay">
</a>
</li>
{% endfor %}
{% endblock %}

I need help in django

I want to print First semester's Subjects in First Semester & Second semester's Subjects in Second Semester and so on. See this pic
cick in image here
Maybe there is some logic in views.py that Im not having on my mind rn.Can someone help me in this logic and how to render it in semester.html page
My code is here.
models.py
from django.db import models
from django.db.models.base import ModelState
# Create your models here.
class Course(models.Model):
faculty = models.CharField(max_length=100)
class Semester(models.Model):
sem = models.CharField(max_length=100)
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
def __str__(self):
return F"Semester {self.sem} at Faculty {self.faculty}"
class Subject(models.Model):
faculty = models.ForeignKey(Course, on_delete=models.CASCADE)
sem = models.ForeignKey(Semester, on_delete=models.CASCADE)
subject_name = models.CharField(max_length=100)
def __str__(self):
return str(self.id)
views.py
from django.shortcuts import render
from django.views import View
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django import forms
from django.utils.translation import gettext, gettext_lazy as _
from .forms import CustomerRegistrationForm
from .models import Course, Semester, Subject
# Create your views here.
def home(request):
return render(request, 'app/home.html')
def faculty(request):
course = Course.objects.all()
return render(request, 'app/faculty.html', {'course':course})
class SemesterView(View):
def get(self, request,id):
obj = Course.objects.get(id=id)
print(obj)
semobj = Semester.objects.filter(faculty=obj)
print(semobj)
subobj = Subject.objects.filter(faculty=obj)
print(subobj)
return render(request, 'app/semester.html', {'obj':obj, 'semobj':semobj, 'subobj':subobj})
semester.html
{% extends 'app/base.html' %}
{% load static %}
{% block semester %}
<div class="bsc-csit">
<div class="container">
<div class="row" style="margin-top:90px; padding-top:20px;">
{% for so in semobj %}
<div class="col-md-3">
<div class="bsccsit-box">
<h3 style="color: black">{{so.sem}}</h3>
<ul>
{% for suo in subobj %}
<li>1.{{suo.subject_name}}</li>
{% endfor %}
</ul>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
{% endblock semester %}
Try replacing the following in your template:
{% for subject in so.subject_set.all %}
<li>{{ forloop.counter }}. {{subject.subject_name}}</li>
{% endfor %}
You can get all Subject's from a specific semester via subject_set.all.
You can also use {{ forloop.counter }} to provide a enumerative number with the associated subject.

Django View Problem. Filtered Tickets Are Not Appearing

I'm currently working on a project in Django that is a "bug tracker" or "ticket tracker" as some might call it. The goal here is to create a post or "ticket" that details a bug in the website or software for a development team.
Each "ticket" has general information like name, summary, etc. but also has a "category" for the software languages or bug type(Think like categories for a blog). Every ticket also has a "priority", that is developed in a similar way as to the categories, based on the severity of the bug that a reporter encounters.
I have already developed a way to click on a category name and view a list of tickets within the same category. This is successful and it works great! Naturally, my next step in the process is to use that same method of implementing ticket priorities. My goal is to be able to click on a priority and see a filtered view of all "severe" tickets with that priority, just like how my categories are set up.
Here is my problem:
When I click on a priority (low, medium, high, & severe), it will take me to my ticket_priority.html template for that particular priority, but does not filter or show any ticket of that priority when there is in fact ticket with that priority. All I'm trying to do is to take that same methodology of building out "categories" but implementing them as "priorities" for the team to filter out based on the severity of the bug.
I think there is something wrong with my ticket_priority view, but I just don't know what the deal is and need extra eyes.
First here is my models:
from django.db import models
from django.utils.timezone import timezone
from datetime import datetime
# Create your models here.
#Priority
class Priority(models.Model):
name = models.CharField(max_length=20,null=True)
def __str__(self):
return self.name
#Category
class Category(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
#TICKET
class Ticket(models.Model):
#BugID
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100, blank=True, null=True)
reporter = models.CharField(max_length=100, blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_modified = models.DateTimeField(auto_now=True)
#BugOverview
summary = models.TextField(blank=True, null=True)
url = models.URLField(blank=True, null=True)
image = models.ImageField(upload_to='media/images/', blank=True, null=True)
#BugEnvironment
platform = models.CharField(max_length=20, blank=True, null=True)
operating_system = models.CharField(max_length=20, blank=True, null=True)
browser = models.CharField(max_length=20, blank=True, null=True)
categories = models.ManyToManyField('Category', related_name='posts')
#BugDetails
steps_to_reproduce = models.TextField(blank=True, null=True)
expected_result = models.CharField(max_length=100, blank=True, null=True)
actual_result = models.CharField(max_length=100, blank=True, null=True)
#BugTracking
priorities = models.ManyToManyField('Priority', related_name='posts')
assigned_to = models.CharField(max_length=100, blank=True, null=True)
completed = models.BooleanField(db_column='Completed', default=False)
datecompletion = models.DateTimeField(db_column='DateCompletion', blank=True, null=True)
def set_completion(self):
self.completed = True
self.datecompletion = datetime.now()
self.save()
def __str__(self):
return self.title
Next up is my views.py for ticket_category & ticket_priority:
# TICKET CATEGORY INDEX
#login_required(login_url='/accounts/login/')
def ticket_category(request, category):
tickets = Ticket.objects.filter(
categories__name__contains = category
)
context = {
"category": category,
"tickets": tickets
}
return render(request, 'ticket_category.html', context)
#################################################################3
# TICKET PRIORITY INDEX
#login_required(login_url='/accounts/login/')
def ticket_priority(request, priority):
tickets = Ticket.objects.filter(
priorities__name__contains = priority
)
context = {
"priority": priority,
"tickets": tickets
}
return render(request, 'ticket_priority.html', context)
And here is my ticket_category.html template:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<div class = "container">
<div class = "row">
<!-- Post Content Column -->
<div class="col-lg-8">
<h1> {{ category | title }} </h1>
{% for ticket in tickets %}
<div class="card">
{% for priority in ticket.priorities.all %}
<div class="card-header">
Ticket #{{ ticket.id}} |
<a href="{% url 'ticket_priority' priority.name %}">
{{ priority.name }}
</a>
</div>
{% endfor %}
<div class="card-body">
<h5 class="card-title">{{ ticket.title }}</h5>
<p class="card-text">{{ ticket.summary|truncatewords:20 }}</p>
<p class="card-text"> Categories:
{% for category in ticket.categories.all %}
<a href="{% url 'ticket_category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</p>
View Ticket
Edit Ticket
Ticket Completed
Delete Ticket
</div>
</div>
<br>
{% endfor %}
</div><!-- Column -->
{% include "sidebar.html" %}
</div> <!-- Row -->
</div><!-- Container-->
{% endblock %}
And here is my ticket_priority.html template:
{% extends "base.html" %}
{% load static %}
{% block page_content %}
<div class = "container">
<div class = "row">
<!-- Post Content Column -->
<div class="col-lg-8">
<h1> {{ priority | title }} </h1>
{% for ticket in tickets %}
<div class="card">
{% for priority in ticket.priorities.all %}
<div class="card-header">
Ticket #{{ ticket.id}} |
<a href="{% url 'ticket_priority' priority.name %}">
{{ priority.name }}
</a>
</div>
{% endfor %}
<div class="card-body">
<h5 class="card-title">{{ ticket.title }}</h5>
<p class="card-text">{{ ticket.summary|truncatewords:20 }}</p>
<p class="card-text"> Categories:
{% for category in ticket.categories.all %}
<a href="{% url 'ticket_category' category.name %}">
{{ category.name }}
</a>
{% endfor %}
</p>
View Ticket
Edit Ticket
Ticket Completed
Delete Ticket
</div>
</div>
<br>
{% endfor %}
</div><!-- Column -->
{% include "sidebar.html" %}
</div> <!-- Row -->
</div><!-- Container-->
{% endblock %}
When the ticket_priority.html template renders, everything appears (base.html, sidebar, priority title, etc) - but no tickets appear - the makes me think that its a problem with my view.
Been stuck on this for over a day. No errors are thrown, just no tickets appear for any priority. They DO appear for each category though. Any help or a point in the right direction would be great. Thank you!
I actually ended up figuring it out on my own and the answer was, naturally, pretty simple.
There wasn't a problem with my model or views, it was my urls. The order of your URL paths DOES matter - though I'm not sure how that works.
Before the fix, my "priority" was routing to my "category" and rendering that view instead.
path("<category>/", views.ticket_category, name="ticket_category"),
path("<priority>/", views.ticket_priority, name="ticket_priority"),
Basically my urls were out of order. I simply moved the priority url above category like so.
path("<priority>/", views.ticket_priority, name="ticket_priority"),
path("<category>/", views.ticket_category, name="ticket_category"),
Now when I click on a link that leads to the priority it displays everything in the particular priority group.
Still not sure what caused it to fix, but its works.

Include Object and Object's Foreign Keys in One Query Django

I have the following models:
class Document(models.Model):
name = models.CharField(max_length=30, null=True, blank=True)
reference = models.CharField(max_length=30, null=True, blank=True)
def __str__(self):
return self.Name
class Subdocument(models.Model)
document = models.ForeignKey(Document, null=True, default=None)
pdf = models.FileField(upload_to='media')
Ultimately I want to show both the name from Document and the pdf from Subdocument in the same <li> in my template within a for loop. So it could be something like:
{% for item in something %}
<li class="list-group-item">
{{ item.Name }} {{ item.pdf }}
</li>
{% endfor %}
My issue is because they are in separate models, I'm not sure how to get fields from both. So what query, or queries could I run in my view in order to make this possible? Any other approach is welcome, this is just to illustrate my end goal.
Thank you!
EDIT:
views.py
def doc_view(request):
something = Subdocument.objects.filter(document__isnull=False)
return render(request, 'my_template.html', context={'something': something})
Have you tried something like this,
# views.py
def my_view(request):
docs = Subdocument.objects.filter(document__isnull=False) # filtering out empty documents
return render(request, 'my_template.html', context={'docs': docs})
# my_template.html
{% for doc in docs %}
<li class="list-group-item">
{{ doc.document.name }} {{ doc.pdf.url }}
</li>
{% endfor %}
Try this
models.py
replace
name = models.CharField(max_length=30, null=True, blank=True)
to
name = models.CharField(max_length=30, null=True, blank=False)
template
{% for item in something %}
<li class="list-group-item">
{{ item.document.name }} {{ item.pdf }}
</li>
{% endfor %}

How do I retrieve the values of selected checkboxes and show it in the template?

What am I doing ?
I'm training on a simple application where one can order a pizza and select his toppings, once the form submitted it shows the submitted queries in the template file.
What is the problem?
I'm having a really hard time showing the checked checkboxes from the form on the template file.
Here are my files :
models.py
class PickedDatas(models.Model):
name = models.CharField(max_length=255, blank=True, null=True)
class Picked(models.Model):
name = models.CharField(max_length=255)
picked = models.ManyToManyField(PickedDatas, blank=True)
forms.py
class CustomChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return mark_safe('%s' % (obj.name))
class SomeForm(forms.ModelForm):
class Meta:
model = Picked
fields = ['name', 'picked']
picked = CustomChoiceField(queryset=PickedDatas.objects.all(), widget=forms.CheckboxSelectMultiple())
views.py
def some_view(request):
if request.method == 'POST':
form = SomeForm(request.POST)
if form.is_valid():
...
else:
form = SomeForm
return render(request, 'features.html', {'form':form, 'picked':Picked.objects.all()})
As for the template file, I'm using the for loop to show Picked models datas.
How can I achieve what I am trying to do ?
EDIT
here is the template file features.html
<h2>Enter your name and choose your pizza toppings</h2>
<form method='post'>
{% csrf_token %}
{{ form.as_p }}
<input type='submit' value='submit'>
</form>
{% for p in picked %}
<h2>Pizza For : <strong>{{ p.name }}</strong></h2>
<p>{{ p.picked }}</p>
{% endfor %}
it gives me this for {{ p.picked }} : pizza.PickedDatas.None
Picked.picked is a many to many field, so you need to loop through the options:
{% for picked in picked %}<!-- Note renamed variable to prevent clash with inner loop -->
<h2>Pizza For : <strong>{{ picked.name }}</strong></h2>
<p>{% for p in picked.picked.all %}{{ p }}{% endfor %}</p>
{% endfor %}

Categories

Resources