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 ↓
return render(request, 'availablesupplies.html', context)
Related
I was wondering if someone could help me out here, I'm struggling to group my IF statements together in such a way to achieve my results. I'm pretty new to python/django so any advice would be greatly appreciated.
I'm trying to make a 'Like' and a 'Dislike' button for my webpage. I have it all set up and I can have each individual element working but I can't seem to group them. What I'm trying to say is this, this will allow me to 'like' my post:
class PostLike(View):
def post(self, request, slug, *args, **kwargs):
post = get_object_or_404(Post, slug=slug)
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
else:
post.likes.add(request.user)
return HttpResponseRedirect(reverse('image_details', args=[slug]))
This will allow me to 'dislike' my post:
class PostDislike(View):
def post(self, request, slug, *args, **kwargs):
post = get_object_or_404(Post, slug=slug)
if post.dislikes.filter(id=request.user.id).exists():
post.dislikes.remove(request.user)
else:
post.dislikes.add(request.user)
return HttpResponseRedirect(reverse('image_details', args=[slug]))
As you can see, my code is basically duplicated and they both work well individually, what I'm trying to do is combine them into one function where if I have already 'liked' my page, I can click the 'dislike' button to dislike my page and remove my 'like'
Many thanks in advance!
models.py:
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True)
featured_image = CloudinaryField('image', default='placeholder')
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
created_on = models.DateTimeField(auto_now_add=True)
status = models.IntegerField(choices=STATUS, default=0)
likes = models.ManyToManyField(User, related_name='image_likes', blank=True)
dislikes = models.ManyToManyField(User, related_name='image_dislikes', blank=True)
class Meta:
ordering = ["-created_on"]
def __str__(self):
return self.title
def number_of_likes(self):
return self.likes.count()
def number_of_dislikes(self):
return self.dislikes.count()
image_details.html (where it is rendered):
<form action="{% url 'post_like' post.slug %}" method="POST">
{% csrf_token %}
{% if liked %}
<span class="text-secondary like-buttons"><strong>{{ post.number_of_likes }} = </strong>
<button type="submit" name="post_id" class="btn like-buttons" value="{{post.slug}}">
<ion-icon name="heart-outline"></ion-icon>
</button>
</span>
<span class="text-secondary like-buttons"><strong>{{ post.number_of_dislikes }} = </strong>
<button type="submit" name="post_id" class="btn like-buttons" value="{{post.slug}}">
<ion-icon name="heart-dislike-outline"></ion-icon>
</button>
</span>
{% else %}
<span class="text-secondary like-buttons"><strong>{{ post.number_of_likes }} = </strong>
<button type="submit" name="post_id" class="btn like-buttons" value="{{post.slug}}">
<ion-icon name="heart-outline"></ion-icon>
</button>
</span>
<span class="text-secondary like-buttons"><strong>{{ post.number_of_dislikes }} = </strong>
<button type="submit" name="post_id" class="btn like-buttons" value="{{post.slug}}">
<ion-icon name="heart-dislike-outline"></ion-icon>
</button>
</span>
</form>
Again, thanks for the answers so far!
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.
So ive been learning django and i am practicing to make an ecommerce website from Programming with Mosh. I faced a problem at the part where I cannot display my products at the website. I cannot figure out what I did wrong so I changed reference and used dennis ivy's ecommerce website tutorial. And now, I am facing the same problem. I compared his code with mine and its just the same but I really dont know what im doing wrong.
This is his code:
https://i.stack.imgur.com/Ossxm.png
And this is the result he get:
https://i.stack.imgur.com/On1ri.png
(he used for loop and it accessed everything from his products model
This is my code:
{% extends 'store/main.html' %}
{% load static %}
{% block content %}
<div class="row">
{% for product in products %}
<div class="col-lg-4">
<img class='thumbnail' src="{% static 'images/2+placeholder.png' %}" alt="">
<div class="box-element product">
<h6><strong>{{product.name}}</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>{{product.price}}</strong>
</h4>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
And this is the result i get:
https://i.stack.imgur.com/WsPgT.png
This is my views:
from django.shortcuts import render
from .models import *
def store(request):
products = Product.objects.all()
context = {'product': products}
return render(request, 'store/store.html', context)
def cart(request):
context = {}
return render(request, 'store/cart.html', context)
def checkout(request):
context = {}
return render(request, 'store/checkout.html', context)
This is my models(up to Product):
from django.db import models
from django.contrib.auth.models import User
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True,
blank=True)
name = models.CharField(max_length=100, null=True)
email = models.CharField(max_length=100, null=True)
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100, null=True)
price = models.FloatField()
def __str__(self):
return self.name
Can someone please enlighten my stupid little tiny brain? Im so drained about this, Im stuck.
Your context name for products is set for product in your view so change this.
def store(request):
products = Product.objects.all()
context = {'products': products}
I'm trying to modify a page that essentially keeps tracks of when users enter/leave an area. Currently all the logic works fine, but I would like to add the functionality to ask a user to enter their own "estimate" of the time they entered/left in the case they forgot to do so, since these instances get flagged upon submission. I'm fairly new to Django/Python, and I have a very basic understanding of how this all works, so I apologize in advance if my suggestions on handling this are a bit off.
These is a summarized version of what the models look like:
models.py
class EmployeeWorkAreaLog(TimeStampedModel, SoftDeleteModel, models.Model):
employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, blank=False)
work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area")
station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True)
edited_timestamp = models.DateTimeField(null=True, blank=True)
time_exceptions = models.CharField(max_length=2, blank=True)
time_in = models.DateTimeField(help_text="Time in", null=True, blank=True)
time_out = models.DateTimeField(blank=True, help_text="Time out", null=True)
def __str__(self):
return self.employee_number
I figured that the easiest way to do this is by adding it to the logic in views.py, to prevent updating a wrong record, in such a way that, right after an entry gets flagged, the user is prompted to enter the date/time they estimate they entered an area.
To keep code readable, I'm only showing the case where entries get flagged. If someone tries to enter any area, the forgets to exit, and then attempts to enter an area again, the record without an exit gets immediately flagged (the time_exceptions='N' is the flag).
views.py
class EnterExitArea(CreateView):
model = EmployeeWorkAreaLog
template_name = "operations/enter_exit_area.html"
form_class = WarehouseForm
def form_valid(self, form):
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in self.request.POST:
form.save()
EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(work_area=area) & Q(time_out__isnull=True) & Q(time_in__isnull=True)) & (Q(station_number=station) | Q(station_number__isnull=True))).update(time_in=datetime.now())
# If employee has an entry without an exit and attempts to enter a new area, mark as an exception 'N'
if EmployeeWorkAreaLog.objects.filter(Q(employee_number=emp_num) & Q(time_out__isnull=True) & Q(time_exceptions="")).count() > 1:
first = EmployeeWorkAreaLog.objects.filter(employee_number=emp_num, time_out__isnull=True).order_by('-time_in').first()
EmployeeWorkAreaLog.objects.filter((Q(employee_number=emp_num) & Q(time_out__isnull=True))).exclude(pk=first.pk).update(time_exceptions='N')
# Here would be the rendering of the page, maybe as a popup? and then saving the entered field using edited = form.cleaned_data['edited_timestamp'] and then saving it using .update()
return HttpResponseRedirect(self.request.path_info)
I was trying to do this in a way that instead of redirecting to the same page, it would render something similar to the page below, which just requests for the time, and after the user submits, it saves it into the records' "edited_timestamp" field.
update_edited_timestamp.html
<div>
<form id="warehouseForm" action="" method="POST" class="form-horizontal">
<label>Enter estimated time:</label>
<input value="html()" type="datetime-local" name="edited_timestamp">
</form>
</div>
Adding my main html page where this all takes place just in case
enter_exit_area.html
{% extends "operations/base.html" %}
{% block main %}
<form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
{% csrf_token %}
<div>
<div>
<div style="color: red">{{ form.employee_number.errors.as_text }}</div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<div style="color: red">{{ form.work_area.errors.as_text }}</div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<div style="color: red">{{ form.station_number.errors.as_text }}</div>
<div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% endblock main %}
I am trying to create a template with Django that loops through Posts and for each Post loops through all Pictures.
I already looked at some answers to other Questions but I can not find my error.
Models:
class Post(models.Model):
Post_Title = models.CharField(max_length=200)
Post_pub_date = models.DateField('date published')
Post_Author = models.CharField(max_length=100)
Post_Text = models.TextField()
def __str__(self):
return self.Post_Title
class Picture(models.Model):
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
Picture = models.ImageField()
Picture_Name = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.Picture_Name
Views:
class PostView(generic.ListView):
template_name = 'myblog/index.html'
context_object_name = 'Post_List'
def get_queryset(self):
"""
Returns Posts
"""
return Post.objects.order_by('-Post_pub_date')
Template:
{% for Post in Post_List %}
<h1 class="mb-4">{{Post.Post_Title}}</h1>
<span class="category">{{Post.Post_Author}}</span>
<span class="mr-2">{{Post.Post_pub_date}}</span>
<div class="post-content-body"><p>{{Post.Post_Text}}</p>
{% for Picture in Post.Picture_set.all %}
<div class="col-md-12 mb-4 element-animate">
<h2>{{Picture.Picture_Name}}</h2>
<img class="col-md-12 mb-4 element-animate" src="{{ MEDIA_URL }}{Picture.Picture}}">
</div>
{% endfor %}
</div>
{% endfor %}
The Post_Title, Post_Author, Post_pub_date and Post_Text are displayed fine. Just the nested For loop is not producing any Picture_Name or Picture as if the Picture_set.all is empty.
As mentioned above I tried to find my error in different Posts like this but could not find it.
Thanks for your help.
Following relationship backward, you need to write related model name from a small letter, even if model name starts from large letter:
{% for Picture in Post.picture_set.all %}
This is how it works in Django shell and i suppose in templates it is the same.
The issue isn't the nested for loop it's the view.It only returns a query for your Post, you don't pass any Photos to your template.