how can i insert html code from database into django template? - python

i tried to insert it via dtl variables but there were html tags on the page
models.py
html code in desciption field
class Vacancy(models.Model):
title = models.CharField(max_length=100)
specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE, related_name="vacancies")
company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="vacancies")
skills = models.TextField()
description = models.TextField()
salary_min = models.FloatField()
salary_max = models.FloatField()
published_at = models.DateTimeField()
html
<img src="/media/company_images/{{ vacancy.company.logo }}" width="130" height="80" alt="">
<div class="d-flex align-items-baseline align-content-baseline">
<h1 class="h2 mt-4 font-weight-bold" >{{ vacancy.title }}</h1>
<p class="m-0 pl-3">{{ vacancy.salary_min }}р – {{ vacancy.salary_max }}р</p>
</div>
<p class="mt-2">{{ vacancy.skills }}</p>
<p class="text-muted mb-4">Primal Assault (15-30 человек), Рязань или удаленно</p>
<div style="line-height: 1.8;">
{{ vacancy.description }}
</div>

If you want to render HTML from your database you can use the safe filter in your jinja HTML.
{{ YOUR_HTML_CONTENT_FROM_DATABASE | safe }}
You can also use the autoescape as defined here.

Related

Transferring user input from one page to another

I am making a website that allows students to find upcoming study sessions for their courses. I am doing this in Django and HTML. A student uploads their courses to the site and they are shown on the courses page as buttons (ex. CS 101 - Intro to CS). When a student clicks on one of their courses (button), it is supposed to bring them to a page that shows available study sessions for that course. I am stuck because I do not know how to properly filter the available study sessions on the next page based on which course is clicked. Is there a way to store the info of the course as a variable so when the button is clicked I can use that variable to filter the results? EDIT: I have made these changes and now I am getting a ValueError too many values to unpack expected 2. I am almost certain it is happening in my views.
Here is the page that shows a user's courses:
<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
<div class="row">
{% if courses_list %}
{% for course in courses_list %}
<a type="button" class="btn btn-outline-secondary" href="{% url 'study:course-session'%}" >{{ course.subject }} {{ course.number}}-{{course.name}} </a>
<br><br><br>
{% endfor %}
{% else %}
<p class="text-center">You have not added any courses yet!</p>
{% endif %}
</div>
</div>
And here is the page that I am trying to filter the list of study sessions (which have a field course that is a ForeignKey to the Courses model):
<h1><center>Upcoming Study Sessions</center></h1>
<div>
<a class="btn btn-success" style="position:absolute; margin-right:2px; top:15%; right:0;" href="{% url 'study:courses' %}" role="button" >Back to My Courses</a>
</div>
<br><br>
<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
<div class="row">
<button type="button" class="btn btn-outline-secondary" >Date/Time: {{ session.date }} <br> Location: {{ session.location }} </button>
<br><br><br>
</div>
</div>
View for the template:
def CourseSessionView(request, course_pk):
course_wanted = Course.objects.get(id=course_pk)
try:
return Study.objects.filter(course=course_wanted)
except:
return messages.error(request, 'There are no upcoming study sessions at this time for the requested course.')
Model for course and session:
class Course(models.Model):
SUBJECT_CHOICES = [
('AAS', 'AAS')
]
subject = models.CharField(
max_length=4, choices=SUBJECT_CHOICES, default='')
number = models.PositiveSmallIntegerField(
validators=[MaxValueValidator(9999)], default=0)
name = models.CharField(max_length=100, default='')
roster = models.ManyToManyField(
Student, blank=True, related_name="courses")
# Use [Student object].courses.all() to see all of a student's courses
def __str__(self):
return f"{self.subject} {self.number} - {self.name}"
class Study(models.Model):
organizer = models.ForeignKey(Student, on_delete=models.CASCADE)
date = models.DateTimeField()
# Use [Student object].studies.all() to see all of a student's study sessions
attendees = models.ManyToManyField(Student, related_name="studies")
location = models.CharField(max_length=30)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
def __str__(self):
return f"{self.date} - {self.location}"
Url:
path('<int:course_pk>/sessions/',
views.CourseSessionView, name='course-session')
Note: The function based views' name doesn't require to be in PascalCase as in your case, it should be in snake_case.
The page that show the user's courses, there you need to pk of courses:
<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
<div class="row">
{% if courses_list %}
{% for course in courses_list %}
<a type="button" class="btn btn-outline-secondary" href="{% url 'study:course-session' course.pk %}" >{{ course.subject }} {{ course.number}}-{{course.name}} </a>
<br><br><br>
{% endfor %}
{% else %}
<p class="text-center">You have not added any courses yet!</p>
{% endif %}
</div>
</div>
Your view for the template, i am defining it in snake_case, since its recommended way.
def course_session(request, course_pk):
course_wanted = Course.objects.get(id=course_pk)
study_courses=''
try:
study_courses= Study.objects.filter(course=course_wanted)
except:
messages.error(request, 'There are no upcoming study sessions at this time for the requested course.')
else:
return render(request,'anyfolder/anyfile.html',{'study_courses':study_courses})
return render(request,'anyfolder/anyfile.html') #then it will show only your error message.
Your url in urls.py be like:
path('any_route_name/<int:course_pk>/', views.course_session, name='course_session')
Note: Never forget to pass / at the end of your url or route_name.
Then, in your any template file you can access it and run loop:
{% for study in study_courses %}
{{study.organizer}},{{study.date}}
{% endfor %}
Then, you can access all its properties, and take benefit of ManyToOne relation.
This is going to be a very general type of answer since you are not providing your models or your views, but I think the idea would be the following.
First, in your template you can pass a parameter for the course number in the url:
your_template.html
<a class="btn btn-outline-secondary"
href="{% url 'study:course-session' course.pk %}">
{{ course.subject }} {{ course.number}}-{{course.name}}
</a>
Then in your view you can access that value, and from it get the course:
views.py
def the_view_name(request, course_pk):
# Here you now have access to the course's primary key, pk, so you can get the
# course and filter the study sessions by that course, etc...
You will need to modify the urls.py so the view can accept this new parameter:
urls.py
path('the_view_name/<int:course_pk>', views.the_view_name, name='the_view_name'),
EDIT
Make the following changes:
First to your views.py:
def CourseSessionView(request, course_pk):
try:
course_wanted = Course.objects.get(id=course_pk)
except:
return messages.error(request, 'course not found')
study_sessions = Study.objects.filter(course=course_wanted)
if study_sessions.count() < 1:
return messages.error(request, 'There are no upcoming study sessions at this time for the requested course')
context = {
'study_sessions': study_sessions,
}
return render(request, 'study/your_template_file.html', context)
Then in your html
<h1><center>Upcoming Study Sessions</center></h1>
<div>
<a class="btn btn-success" style="position:absolute; margin-right:2px; top:15%; right:0;" href="{% url 'study:courses' %}" role="button" >Back to My Courses</a>
</div>
<br><br>
<div class="container h-100" style="top:50%; bottom:50%; width:100%;">
{% for session in study_sessions %}
<div class="row">
<button type="button" class="btn btn-outline-secondary" >Date/Time: {{ session.date }} <br> Location: {{ session.location }} </button>
<br><br><br>
</div>
{% endfor %}
</div>

How do I access the data from inside a nested for loop

I want to do something like below in html where multiple "spots" are displayed, and within each spot the "links" associated to each specific spot is displayed.
How would I write the logic to display the specific links for each spot?
html
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
{% for link in links %}
<div>
<h3>{{ link.url }}</h3>
</div>
{% endfor %}
{% endfor %}
My models are as below. SpotLinks is the intermediate table for Links and Spots table.
models.py
class Spots(models.Model):
title = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
class Links(models.Model):
title = models.CharField(unique=True, max_length=155, blank=True)
url = models.CharField(max_length=75, blank=True)
class SpotLinks(models.Model):
link = models.ForeignKey('Links', models.DO_NOTHING)
spot = models.ForeignKey('Spots', models.DO_NOTHING)
class Articles(models.Model):
title = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
summary = models.TextField(blank=True, null=True)
class ArticleSpots(models.Model):
article = models.ForeignKey('Articles', models.DO_NOTHING)
spot = models.ForeignKey('Spots', models.DO_NOTHING)
I tried links = Links.objects.filter(spotlinks__spot=spots) in views.py but because spots has multiple spots in it it doesn't get filtered.
Will the logic be written in the views.py or as django templates in the html file?
Im new to web development so any direction would help. Thanks!
views.py
def article(request, slug):
article = get_object_or_404(Articles, slug=slug)
spots = Spots.objects.filter(articlespots__article=article).distinct()
links = Links.objects.filter(spotlinks__spot=spots)
context = {
'spots': spots,
'article': article,
'links': links}
return render(request, 'articletemplate.html', context)
To access the related objects, use the related manager.
In this case, the related manager is spot.spotlinks_set.
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
<!-- {% for link in links %} --> <!-- Replace this -->
{% for spotlink in spot.spotlinks_set.all %} <!-- with this -->
<div>
<!-- <h3>{{ link.url }}</h3> --> <!-- Replace this -->
<h3>{{ spotlink.link.url }}</h3> <!-- with this -->
</div>
{% endfor %}
{% endfor %}
Reference: https://docs.djangoproject.com/en/3.2/ref/models/relations/
You need to add one foreign field to Links model to reference spot, so Links model will be:
class Links(models.Model):
title = models.CharField(unique=True, max_length=155, blank=True)
url = models.CharField(max_length=75, blank=True)
spot = models.ForeignKey(Spots, on_delete=models.CASCADE, related_name="links")
thereby, you can get the links for each spots by:
from django.shortcuts import get_object_or_404
spot = get_object_or_404(Spots, title="choose the the title") # you can filter it in your preferred way
links = spot.links.all()
Then, in context; you don't need to send links at all, instead you can iterate in html in this way:
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
{% for link in spot.links %}
<div>
<h3>{{ link.url }}</h3>
</div>
{% endfor %}
{% endfor %}

Why will my django model data not display in html

Following this tutorial, I am creating a simple ecommerce website. I have data stored in a Django model, and I am calling it in my view, but it will not display in my html. Basically, I want it to create one of the boxes bellow for every donation in the donation model, but it will not work. Can someone please help me? I know this seems like an easy fix, I just can't wrap my head around it. My code is down bellow.
View:
def availablesupplies(request):
donations = Donation.objects.all()
context = {'donations':donations}
return render(request, 'availablesupplies.html')
Model:
class Donation(models.Model):
title = models.CharField(max_length=30)
phonenumber = models.CharField(max_length=12)
category = models.CharField(max_length=20)
quantity = models.IntegerField(blank=True, null=True,)
location = models.CharField(max_length=50, blank=True, null=True,)
description = models.TextField()
datedonated = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
blank=True,
null=True,
)
HTML:
<div class="row">
{% for donation in donations %}
<div class="col-lg-4">
<img class="thumbnail" src="{% static 'images/gooddeedplaceholderimage.png' %}">
<div class="box-element product">
<h6><strong>Product</strong></h6>
<hr>
<button class="btn btn-outline-secondary add-btn">Add to Cart</button>
<a class="btn btn-outline-success" href="#">View</a>
<h4 style="display: inline-block; float: right"><strong>$20</strong></h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
You need to pass the context object to the render engine:
def availablesupplies(request):
donations = Donation.objects.all()
context = {'donations':donations}
# pass the context &downarrow;
return render(request, 'availablesupplies.html', context)

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.

Nothing is shown in a tag

Nothing is shown in a tag.
I wrote in views.py
def top(request):
content = POST.objects.order_by('-created_at')[:5]
category_content = Category.objects.order_by('-created_at')[:5]
return render(request, 'top.html',{'content':content,'category_content':category_content})
in models.py
class Category(models.Model):
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
in top.html
<ul class="list-group">
<li class="list-group-item active text-center">category</li>
<div class="collapse">
{% for category in category_content %}
<a href="" class="list-group-item">
{{ category.name }}
</a>
{% endfor %}
</div>
</ul>
Now output is like
so category.name is not shown.My ideal output is
I really cannot understand why category.name is not shown.I print out print(category_content) in views.py's top method,so , ]> is shown.How should I fix this?What is wrong in my codes?
Categories are not visible, because you used collapse CSS class in the div, which means it's not displayed.
If you check Bootstrap 4 documentation on collapse, you'll see that it states
.collapse hides content

Categories

Resources