Django Template Query Set and filters - python

In my view, I have a model that returns all instances of a model that has a foreign key to user. This view renders a profile page where the model.user is checked against the request.user, if it matches, it prints out information on that model on the profile page.
This is what I have in my views.:
#login_required(login_url='loginpage_company')
#allowed_users_company(allowed_roles=['company'])
def profile_company(request):
print(request.user)
companies = Company.objects.all()
responses = Response.objects.all()
context = {
'companies': companies,
#'company_reviews': company_reviews,
#'total_reviews': total_reviews,
'responses': responses,
'info': "No company claimed yet",
'infor': 'Not Available',
}
return render(request, 'companyusers/profile_company.html', context)
for my models I have the following.
class Company(models.Model):
Online_Merchant = 'merch'
Education = 'edu'
Transportation = 'trans'
Hospitalism = 'hosp'
Healthcare = 'health'
Construction = 'const'
Blog = 'blog'
Finance = 'fin'
Media = 'media'
Government_Agency = 'agency'
Other = 'other'
Manufacturing = 'manufacturing'
sector = [
(Online_Merchant, 'Online Merchant'),
(Education, 'Education'),
(Transportation, 'Transportation'),
(Hospitalism, 'Hospitalism'),
(Healthcare, 'Healthcare'),
(Construction, 'Construction'),
(Blog, 'Blog'),
(Finance, 'Finance'),
(Media, 'Media'),
(Manufacturing, 'Manufacturing'),
(Government_Agency, 'Government Agency'),
(Other, 'Other')
]
Free = 'Free'
Premium = 'Premium'
package = [
(Free, 'Free'),
(Premium, 'Premium')
]
Abuja = 'Abuja'
Abia = 'Abia'
Adamawa = 'Adamawa'
Akwa_Ibom = 'Akwa Ibom'
Anambra = 'Anambra'
Bauchi = 'Bauchi'
Bayelsa = 'Bayelsa'
Benue = 'Benue'
Borno = 'Borno'
Cross_River = 'Cross River'
Delta = 'Delta'
Ebonyi = 'Ebonyi'
Edo = 'Edo'
Ekiti = 'Ekiti'
Enugu = 'Enugu'
Gombe = 'Gombe'
Imo = 'Imo'
Jigawa = 'Jigawa'
Kaduna = 'Kaduna'
Kano = 'Kano'
Katsina = 'Katsina'
Kebbi = 'Kebbi'
Kogi = 'Kogi'
Kwara = 'Kwara'
Lagos = 'Lagos'
Nasarawa = 'Nasarawa'
Niger = 'Niger'
Ogun = 'Ogun'
Ondo = 'Ondo'
Osun = 'Osun'
Oyo = 'Ibadan'
Plateau = 'Plateau'
Rivers = 'Rivers'
Sokoto = 'Sokoto'
Taraba = 'Taraba'
Yobe = 'Yobe'
Zamfara = 'Zamfara'
state = [
(Abuja, 'Abuja'),
(Abia, 'Abia'),
(Adamawa, 'Adamawa'),
(Akwa_Ibom, 'Akwa Ibom'),
(Anambra, 'Anambra'),
(Bauchi, 'Bauchi'),
(Bayelsa, 'Bayelsa'),
(Benue, 'Benue'),
(Borno, 'Borno'),
(Cross_River, 'Cross River'),
(Delta, 'Delta'),
(Ebonyi, 'Ebonyi'),
(Edo, 'Edo'),
(Ekiti, 'Ekiti'),
(Enugu, 'Enugu'),
(Gombe, 'Gombe'),
(Imo, 'Imo'),
(Jigawa, 'Jigawa'),
(Kaduna, 'Kaduna'),
(Kano, 'Kano'),
(Katsina, 'Katsina'),
(Kebbi, 'Kebbi'),
(Kogi, 'Kogi'),
(Kwara, 'Kwara'),
(Lagos, 'Lagos'),
(Nasarawa, 'Nasarawa'),
(Niger, 'Niger'),
(Ogun, 'Ogun'),
(Ondo, 'Ondo'),
(Osun, 'Osun'),
(Oyo, 'Ibadan'),
(Plateau, 'Plateau'),
(Rivers, 'Rivers'),
(Sokoto, 'Sokoto'),
(Taraba, 'Taraba'),
(Yobe, 'Yobe'),
(Zamfara, 'Zamfara')
]
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='Company User')
company_sector = models.CharField(max_length=30, choices=sector, default=Online_Merchant)
company_name = models.CharField(max_length=100)
company_description = models.TextField()
company_logo = models.ImageField(upload_to='company_logos', blank=True, null=True)
company_state = models.CharField(max_length=30, choices=state, default=Lagos)
company_address = models.TextField(max_length=2000)
average_rating = models.IntegerField(default=0)
total_views = models.IntegerField(default=0)
company_website = models.CharField(max_length=500, blank=True, null=True)
company_email = models.EmailField(max_length=500, blank=True, null=True)
company_phone = models.CharField(max_length=500)
package_chosen = models.CharField(max_length=8, choices=package, default=Free)
featured = models.BooleanField(default=False)
advert = models.BooleanField(default=False)
premium = models.BooleanField(default=False)
def __str__(self):
return self.company_name
This is what I have in the template:
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% include "nav_bar.html" %}
{% block greeting %}
<li class="nav-item" >
<a class="nav-link font-weight-bold" href="{% url 'contact' %}"><i class="fas fa-envelope" style="font-size:20px; padding-right: 4px; color:#2196F3"></i>Contact Us</a>
</li>
{% endblock greeting %}
{% block section %}
<section class="mt-2 bg-white mx-2">
<div class="container-fluid border-0 text-justify">
<div class="row">
<span class="font-weight-bold px-2 py-1 mx-auto text-danger">...Created with<span class="h3"> ♥</span>... Because we understand that behind every review, there is a hearty experience...</span>
</div>
<div class="row mx-2">
<div class="col-md-5 mb-2">
<div class="card" style="width: 23rem;">
<img src="{{request.user.userprofilecompany.profile_photo.url}}" class="card-img-top" alt="profile picture">
<div class="card-body">
<h5 class="card-title">Company Name: {{request.user.userprofilecompany.company_name}}</h5>
<p class="card-text">Username: {{request.user.username}} </br><span class="font-weight-sm">this is publicly visible</span></p>
<p class="card-text">Fullname: {{request.user.last_name}}, {{request.user.first_name}}</p>
<p class="card-text">Designation: {{request.user.userprofilecompany.designation}}</p>
<p class="card-text">Email: {{request.user.email}}</p>
<p class="card-text">Phone: {{request.user.userprofilecompany.phone}}</p>
<p class="card-text">Location: {{request.user.userprofilecompany.location}}</p>
<p class="card-text">Package: {{request.user.userprofilecompany.package}} Upgrade</p>
<p class="card-text"></p>
Go to Settings</br>
<p class="card-text"></p>
Logout</br>
</div>
</div>
</div>
{% for company in companies %}
{% if company.user == request.user %}
<div class="col-md mb-2">
<div class="row">
<div class="col-md mb-2">
<div class="card text-center mb-3">
<div class="card-header text-white bg-info">
<h5 class="card-title">Total Reviews</h5>
</div>
<div class="card-body">
<h3 class="card-title"></h3>
</div>
<div class="card-body">
<h3 class="card-title"></h3>
</div>
<div class="card-body">
<h3 class="card-title">{{ company.review_set.all.count }}</h3>
</div>
<div class="card-body">
<h3 class="card-title"></h3>
</div>
<button class="btn btn-info font-weight-bold btn-sm" id="tm-reviews">View Reviews and Responses</button>
</div>
</div>
<div class="col-md mb-2">
<div class="card mb-3" >
<div class="card-header text-center text-white bg-info">
<h5 class="card-title ">Statistics</h5>
</div>
<div class="py-2 font-weight-bold px-2">
<p class="card-text">Average Rating: | <i id="tm-average_rating">{{company.average_rating}}</i><i>/5</i> </p>
<p class="card-text">Remarks: | <i id="tm-remarks" class=""></i></p>
<p class="card-text">Total Likes: | like count number</p>
<p class="card-text">Total Dislikes: | dislike count number</p>
<p class="card-text">Average Rating: | 4/5 </p>
<p class="card-text">Remarks: | Satisfactory</p>
<p class="card-text">Total Views: | 10</p>
<p class="card-text"><h6 class=" font-weight-bold">Claimed Company: <span class= "text-primary"><a class="text-decoration-none" href="{% url 'detail' company.id %}" target="_blank"> {{company.company_name}} </a> </span> </h5></p>
</div>
<button class="btn btn-info font-weight-bold btn-sm" id="tm-reviews">Click to Get Noticed</button>
</div>
</div>
</div>
<div class="row" id="tm-display-reviews">
<div class="col-md mb-2">
<div style="font-size: small;" class="card text-center mb-3">
<div class="card-header text-white bg-info">
<h5 class="card-title">Details</h5>
</div>
<div class="card-body">
{% for review in company.review_set.all %}
<div class=" py-2">
<p class="card-text ">Name: {{review.user | capfirst }} Rating: {{review.rating}}/5 | Date added: <span class="text-danger"> {{ review.date_added }}</span></p>
<p class="card-text"> Review: {{review.review_text}} </p>
<!-- check to see if there is a reponse under this review to know whether
to show the button -->
{% for response in review.response_set.all %}
{% empty %}
<p class="card-text"><button id="tm-respond" class="btn btn-outline-primary font-weight-bold btn-sm">respond to this review</button></p>
{% endfor %}
{% for response in responses%}
{% if response.review == review %}
<p class="card-text bg-light font-italic">{{response.review.company | capfirst }} responded: {{response}} on: {{response.date_added}}</p>
<hr>
{% endif %}
{% endfor %}
{% endfor %}
</div>
</div>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
<div class="col-md mb-2">
<!-- The problem is here. It seems to rund the code over and over again-->
{% for company in companies %}
{% if company.user != request.user%}
<div class="row">
<div class="col-md mb-2">
<div class="card text-center mb-3">
<div class="card-header text-white bg-info">
<h5 class="card-title">Total Reviews</h5>
</div>
<div class="card-body">
<p class="card-text"> You have not claimed a company yet.</p>
<p class="card-text"> You need to claim a company to view its statistis here.</p>
<p class="card-text"> You need to have your company listed to claim it.</p>
<p class="card-text"> If your company is already listed on our site, kindly email us on:</p>
<p class="card-text"> info#crediblereviews.ng</p>
</div>
</div>
</div>
<div class="col-md mb-2">
<div class="card mb-3" >
<div class="card-header text-center text-white bg-info">
<h5 class="card-title ">Statistics</h5>
</div>
<div class="py-2 font-weight-bold px-2">
<p class="card-text">Average Rating: | <i id="tm-average_rating">{{infor}}</i> </p>
<p class="card-text">Remarks: | <i id="tm-remarks" class="">{{infor}}</i></p>
<p class="card-text">Total Likes: | {{infor}}</p>
<p class="card-text">Total Dislikes: | {{infor}}</p>
<p class="card-text">Average Rating: | {{infor}} </p>
<p class="card-text">Remarks: | {{infor}}</p>
<p class="card-text">Total Views: | {{infor}}</p>
<p class="card-text"><h6 class=" text-warning font-weight-bold">{{info}}: <span style="font-size: small;" class= "text-info"> Email us to claim a company </span> </h5></p>
</div>
<button class="btn btn-info font-weight-bold btn-sm" id="tm-reviews">Click to Get Noticed</button>
</div>
</div>
</div>
{% endif %}
{% endfor %}
<!---->
</div>
</div>
</div>
</section>
{% endblock section %}
{% block article %}
{% endblock article %}
The problem is the last loop it seems to print the code as many times as there are instances of the model that doesnt match the condition. This is not what I want. I want to be able to check if request.user is not equal to company.user and print the last division. Thanks so much for the help...

It is a misuse of Django framework to do data filtering in the templates. As it is a simple filtering (or data routing) you can simply filter the unwanted campaigns out by using campaigns.filter(user=request.user) instead of campaigns while creating your context.

Thank you Ali for your help. but selecting where user=request.user would raise an exception saying: reference before assignment. I tried the try and except block for this no way.
I finally used javascript to solve the issue. In the model for my users, I inserted a boolean field. Javascript will now check for this field to know whether to hide or show the division. It works just fine the way I want it.

Related

Django e-commerce checkout page does not want to display products in the HTML page

basket/models.py
from decimal import Decimal
from django.db import models, migrations
from django.conf import settings
from datetime import datetime
from marketplace.models import prodProduct
from member.models import Person
class Basket(models.Model):
class Meta:
db_table = 'basket'
productqty = models.IntegerField(default=0)
productid = models.ForeignKey(prodProduct, on_delete=models.CASCADE)
Person_fk = models.ForeignKey(Person, on_delete=models.CASCADE)
def save(self):
super().save()
def get_subtotal_price(self, fk1):
product = prodProduct.objects.get(pk=fk1)
basket = Basket.objects.all()
return sum(Decimal(product['productPrice']) * basket['productqty'])
def get_total_price(self, fk1):
product = prodProduct.objects.get(pk=fk1)
basket = Basket.objects.all()
subtotal = sum(Decimal(product['productPrice']) * basket['productqty'])
if subtotal == 0:
shipping = Decimal(0.00)
else:
shipping = Decimal(3.00)
total = subtotal + Decimal(shipping)
return total
marketplace/models.py
class prodProduct(models.Model):
class Meta:
db_table = 'prodProduct'
productid = models.AutoField(primary_key=True)
productName = models.CharField(max_length=255, blank=True)
productDesc = models.CharField(max_length=1500,blank=True)
productCategory = models.CharField(max_length=255, blank=True)
productPrice = models.DecimalField(max_digits=4, decimal_places=2)
productStock = models.IntegerField(default=0)
productPhoto = models.ImageField(upload_to ='images/', null=True)
productRating = models.IntegerField(default=0)
timePosted = models.DateTimeField(default=datetime.now, blank=True)
Person_fk = models.ForeignKey(Person, on_delete=models.CASCADE)
def save(self):
super().save()
return self.productid
def deleteProduct(self):
super().delete()
basket/summary.html
{% block content %}
<div class="container">
<div class="col-12">
<h1 class="h2">Your Basket</h1>
</div>
<div class="col-12">
<p>Manage your <b>items</b> in your basket</p>
</div>
<hr />
</div>
<div class="container">
<div class="row g-3">
{% if allBasket.count == 0 %}
<div class="col-12">Your basket is empty Shop</div>
{% else %}
<div class="col-12 bg-light p-3 d-flex justify-content-between">
<div class="dropdown">
<button class="btn btn-success fw-bold" type="button" id="dropdownLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Shipping options
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down-fill" viewBox="0 0 16 16">
<path d="M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z"/>
</svg>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownLink">
<a class="dropdown-item" href="#">Next day delivery</a>
<a class="dropdown-item" href="#">Premium delivery</a>
</div>
</div>
<div class="text-end">
<div class="">Sub Total: <span class="fw-bold">RM</span>
<div id="subtotal" class="d-inline-flex fw-bold">{{subtotal}}</div>
</div>
<div id="">Shipping <span class="small">(Next day delivery)</span>: <span class="fw-bold">RM5.00</span></div>
<div class="pt-2">Total to pay: <span class="fw-bold">RM</span><span id="total"
class="fw-bold h5">{{totalprice}}</span></div>
</div>
</div>
<div class="col-md-5 col-lg-4 order-md-last p-0 order-3">
{% for product in product %}
<div class="d-grid gap-2 ">
<a role="button" href="{% url 'basket' product.productid %}" class="btn btn-success fw-bold" type="button">Checkout</a>
</div>
{% endfor %}
</div>
<div class="col-md-7 col-lg-8 p-0">
{% for all_basket in all_basket %}
{% for item in product %}
{% if all_basket.productid_id == product.productid and all_basket.Person_fk_id.Email == request.session.Email %}
<div class="card mb-3 border-0 product-item">
<div class="row g-0">
<div class="col-md-2 d-none d-md-block">
<img class="img-fluid mx-auto d-block" alt="Responsive image" src="{{ item.productPhoto }}" />
</div>
<div class="col-md-10 ps-md-3">
<div class="card-body p-1">
<p class="card-text pb-3">{{ product.productName }}</p>
<label for="select">Qty</label>
<select id="productqty" style="width:50px;height:31px;">
<option value="" selected disabled hidden>1</option>
<option value="">1</option>
<option value="">2</option>
<option value="">3</option>
<option value="">4</option>
</select>
<a type="button" id="update-button" data-index="{{item.productid}}"
class="update-button text-decoration-none small ps-3">Update</a>
<a type="button" id="delete-button" data-index="{{item.productid}}"
class="delete-button text-decoration-none small">Delete</a>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
Here is the screenshot of what is displayed currently
Goal
I want to be able to display the products, subtotal price and total price after shipping that are in the basket but currently it does not want to display any of that.
basket/summary.html
<div class="text-end">
<div class="">Sub Total: <span class="fw-bold">RM</span>
<div id="subtotal" class="d-inline-flex fw-bold">{{subtotal}}</div>
</div>
<div id="">Shipping <span class="small">(Next day delivery)</span>: <span class="fw-bold">RM5.00</span></div>
<div class="pt-2">Total to pay: <span class="fw-bold">RM</span><span id="total"
class="fw-bold h5">{{totalprice}}</span></div>
</div>
</div>
This part displays perfectly but the other codes does not display anything at all. Can someone help me debug the code, I've been on this for quite a while now. Thanks!

Django modelformset_factory id is required field

I'm trying to create a table of records to update with a single click. I keep getting the error [{'id': ['This field is required.']}] I can't seem to figure it out. I have tried to put {{ form.label_tag }} in somewhere to see if that would help, but it doesn't. I can't figure out how to be sure id gets passed back in for the edit.
forms.py
class ReleaseAssignForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ReleaseAssignForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
class Meta:
model = Releases
fields = [
'id',
'rel_title',
'rel_summary',
'rel_english_title',
'rel_english_summary',
'rel_country',
'rel_risk_category',
'rel_ops_category',
'rel_assoc_indicator',
'rel_industry',
'rel_risk_assigned',
'rel_ops_assigned',
'rel_indu_assigned',
'rel_indi_assigned',
]
views.py
def preview_releases(request):
today = datetime.date.today()
count = 0
releases = Releases.published.filter(rel_date=today)
ReleaseAssignFormSet = modelformset_factory(Releases, ReleaseAssignForm, fields = '__all__', extra=0)
if request.method == "POST":
formset = ReleaseAssignFormSet(request.POST, queryset=releases)
if formset.is_valid():
posts = formset.save(commit=False)
for post in posts:
post.save()
return redirect('preview_releases')
else:
print(formset.errors)
print("Form Invalid")
else:
formset = ReleaseAssignFormSet(queryset=releases)
count = formset.total_form_count()
context = {
'count': count,
'formset': formset,
}
return render(request, 'management/preview-releases.html', context)
template.html
<form action="" method="POST">
{% csrf_token %}
{{ formset.management_form }}
{% if formset %}
{% for form in formset.forms %}
<div class="row py-5" style="border-bottom: 1px black solid;font-size: 14px;">
<div class="row px-5 pb-2" style="border-bottom: 1px lightgray dotted;font-size: 14px;">
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Risk Category</span><br>
{{ form.rel_risk_category }}
</div>
<div class="col px-5 pb-2" style="border-right: 1px darkgray dotted;">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_risk_assigned }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Ops Category</span><br>
{{ form.rel_ops_category }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_ops_assigned }}
</div>
</div>
<div class="row px-5 pt-2 pb-5">
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Associated Indicator</span><br>
{{ form.rel_assoc_indicator }}
</div>
<div class="col px-5 pb-2" style="border-right: 1px darkgray dotted;">
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_indi_assigned }}
</div>
<div class="col px-5 pb-2">
<span style="font-size: 12px;color: darkred;">Industry</span><br>
{{ form.rel_industry }}
</div>
<div class="col px-5 pb-2" >
<span style="font-size: 12px;color: darkred;">Assigned</span><br>
{{ form.rel_indu_assigned }}
</div>
</div>
<div class="row">
<div class="col px-5">
<h3>{{ form.instance.rel_title }}</h3>
<p>{{ form.label_tag }}</p>
<p>{{ form.instance.rel_summary }}</p>
</div>
<div class="col px-5" style="border-left: 1px lightgray dashed;">
<a target="_blank" href="{% url 'clean_release' form.instance.id %}"><h3>{{ form.instance.rel_title }}</h3></a>
<p>{{ form.instance.rel_country }}</p>
{% autoescape off %}
<p>{{ form.instance.rel_summary }}</p>
{% endautoescape %}
</div>
<div class="col px-5" style="border-left: 1px lightgray dashed;">
<a target="_blank" href="{% url 'clean_release' form.instance.id %}"><h3>{{ form.instance.rel_english_title }}</h3></a>
<p>{{ form.instance.rel_country }}</p>
{% autoescape off %}
<p>{{ form.instance.rel_english_summary }}</p>
{% endautoescape %}
</div>
</div>
</div>
{% endfor %}
{% else %}
No resources found.
{% endif %}
<div class="text-end py-5">
<button type="submit" class="btn btn-primary">Submit Changes</button>
</div>
</div>
</form>

Comparing fields from two models using foreign key.(for displaying correct product under correct category) using django

I have two models Category and Product. Here is models.py
class Category(models.Model):
type=models.CharField(max_length=30)
def __str__(self):
return self.type
class Product(models.Model):
category = models.ForeignKey(Category, on_delete = models.CASCADE)
productid=models.CharField(max_length=30)
name=models.CharField(max_length=30)
disimage=models.ImageField(upload_to='pics')
def __str__(self):
return self.productid
In my template I have two for loops the outer one that iterates category model and the other that iterates through products and i want to display the product only if the category.type is equal to the product category (for example if there is a type=Shirt in category then I want display a product under it only if it has type=Shirt )
Here is my HTML
{% for i in types %}
<div class="container">
<div class="row product-btn d-flex justify-content-end align-items-end">
<!-- Section Tittle -->
<div class="col-xl-4 col-lg-5 col-md-5">
<div class="section-tittle mb-30" id="{{i.type}}">
<h2>{{i.type}}</h2>
</div>
</div>
</div>
<div class="tab-content" id="nav-tabContent">
<!-- card one -->
<div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
<div class="row">
{% for product in prods %}
{% if i.type == product.category %}
<div class="col-xl-4 col-lg-4 col-md-6">
<div class="single-product mb-60">
<div class="product-img">
<img src="{{product.disimage.url}}" alt="">
</div>
<div class="product-caption">
<h4>{{product.name}}</h4>
<div class="price">
<ul>
<li>RS {{product.currentprice}}</li>
<li class="discount">RS {{product.originalprice}}</li>
<div>
View
Add to Cart
</div>
</ul>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
</div>
</div>
</div>
</div>
</div>
{% endfor %}
I am trying to do this using {% if i.type == product.category %} but i am not succeeding. Any help on how to work this out will be appreciated.
you should use the following
{% if i.type == product.category.type %}

Django HTML for loop with filter

In my django project, I have an HTML that renders questions header, and inside the question headers I have question items. In my model, Question headers and items are two different entities. I need to show for every header, just the items related to that header. As it shows all items for all questions without any filters. Greatly appreciate any help!
Model:
class Question(models.Model):
question = models.CharField(max_length=240)
mission_section = models.ForeignKey('Mission_Section', on_delete=models.CASCADE)
type_question = models.ForeignKey('Type_Question', on_delete=models.CASCADE)
categories_question = models.ForeignKey('Categories_Question', on_delete=models.CASCADE, default=1)
order = models.IntegerField(default=1)
def __str__(self):
return self.question
class Question_Option(models.Model):
question = models.ForeignKey('Question', on_delete=models.CASCADE,default=1)
option = models.CharField(max_length=240)
correct = models.BooleanField()
order = models.IntegerField(default=1)
View:
class Questions(LoginRequiredMixin, FormView):
template_name = "questions.tmpl"
def get(self, request, pk):
context = {
'pk': pk,
'section': Mission_Section.objects.get(pk = pk ),
'questions_items': Question_Option.objects.filter(question__mission_section__pk=pk).order_by('order','pk'),
'questions': Question.objects.filter(mission_section__pk = pk ),
'question_types' : Type_Question.objects.all(),
'questions_categories': Categories_Question.objects.all()}
return render(self.request, self.template_name, context)
HTML
<input type="hidden" class="form-control" id="section" name="section" value="{{section.id}}" required>
<h1>{{ section.name }}</h1>
<div id="contentDiv">
<ol>
{% for question in questions %}
<div name="question" class="form-group" id="question-{{question.id}}" >
<form class='my-ajax-form' id="form-question-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<li><div class="input-group">
{% csrf_token %}
{{ form.as_p }}
<input type="text" value= "{{question.id}}" id="question" name="question-hidden" class="form-control">
<input type="text" value= "{{question.question}}" id="question_name_{{question.id}}" class="form-control" aria-label="Amount" onchange="UpdateQuestion({{question.id}})">
</div>
</form>
<br>
<!-- Options -->
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
<ol class="example list-group">
{% for qi in questions_items %}
<li class="list-group-item d-flex justify-content-between align-items-center" id={{qi.id}} name="opt-{{question.id}}-{{qi.id}}" onclick="setCorrect({{qi.id}},{{question.id}})" contenteditable="true">{{ qi.option }}
<span class="badge badge-warning badge-pill">-</span>
</li>
{% endfor %} </ol>
<div>
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</div>
</div></li>
{% endfor %} </ol>
using this answer I figured it out Double loop in Django template
What I need is:
<div id = "question_content_{{question.id}}" name="question-options" class="collapse">
{% csrf_token %}
{{ form.as_p }}
<form class='ajax-form-option' id="form-option-{{question.id}}" method='GET' action='.' data-url='{{ request.build_absolute_uri|safe }}'>
<ol class="example list-group">
{% for qi in question.question_option_set.all %}
<li class="list-group-item d-flex justify-content-between align-items-center" id=option-{{qi.id}} name="opt-{{question.id}}-{{qi.id}}">
<div contenteditable="true">{{ qi.option }}</div>
<div>
<button type="button" name='option-check' class="btn btn-light" value={{qi.id}} id="check-option-{{question.id}}-{{qi.id}}">
<i class="fas fa-check"></i>
</button>
<button type="button" class="btn btn-warning" id="delete-option-{{question.id}}-{{qi.id}}" onclick="deleteOption({{qi.id}})">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
</li>
{% endfor %} </ol>
<div onclick="CreateOption({{question.id}})">
<div class="d-flex justify-content-center">Add Option</div>
<div class="d-flex justify-content-center"> <br><i class="fa fa-plus-circle fa-1x" aria-hidden="true"></i></div>
</div>
</form>

How can i fix double for loop in django

lostList.html shows LostNotices and Dogs.
I want to match lostnotice and dog using foreign key in Dog model.
So i used for loop and if in the template.
But it doesn't work....
I am trying to fix this for 2 days but i couldn't.
It will be really big help for me. Thank you
{% for lostPost in lostPosts.all reversed %}
<h6>{{lostPost.id}}</h6>
{% for dog in dogs.all %}
<h6>{{dog.breed}}</h6><br>
<div class="col-lg-3 col-sm-6 col-md-6">
<div class="card">
<div class="card-body">
{% if dog.LostNoticeNum == lostPost.id %}
views.py
def lostList(request):
lostPosts = LostNotice.objects
dogs=Dog.objects
return render(request, '/lostList.html', {'lostPosts' : lostPosts,'dogs':dogs})
model.py
class LostNotice(models.Model):
Title=models.CharField(max_length=20,null=True)
State=models.IntegerField()
PubDate=models.DateTimeField()
MissingDate=models.DateTimeField()
Text=models.TextField()
Phone=models.CharField(max_length=20,null=True)
Author=models.ForeignKey(Member, on_delete = models.CASCADE,null=True)
Si=models.CharField(max_length=20,null=True)
Gu=models.CharField(max_length=20,null=True)
Dong=models.CharField(max_length=20,null=True)
class Dog(models.Model):
Name=models.CharField(max_length=20)
Breed=models.CharField(max_length=20)
Sex=models.CharField(max_length=20,null=True)
Color=models.CharField(max_length=20,null=True)
LostNoticeNum=models.ForeignKey(LostNotice, on_delete = models.CASCADE,null=True)
FindNoticeNum=models.ForeignKey(FindNotice, on_delete = models.CASCADE,null=True)
template:
<div class="" id="list">
<div class="container">
<div class="row mx-auto">
<div class="col-lg-12 col-sm-12 col-md-12 col-12 pr-1">
<div class="row mb-2 ml-2 mr-2">
{% for lostPost in lostPosts.all reversed %}
<h6>{{lostPost.id}}</h6>
{% for dog in dogs.all %}
<h6>{{dog.breed}}</h6><br>
<div class="col-lg-3 col-sm-6 col-md-6">
<div class="card">
<div class="card-body">
{% if dog.LostNoticeNum == lostPost.id %}
<h6>breed</h6>
<h6 class="card-title" style="text-align: center; color: gray">{{dog.Breed}}</h6>
{% else %}
<h6 class="card-title" style="text-align: center">{{lostPost.sex}}</h6>
{% endif %}
{{lostPost.photo}}
{% if lostPost.photo %}
<img class="card-img-top rounded-circle mx-auto pt-1" src="{{ lostPost.photo.url }}"
style="height: 200px">
{% else %}
<img class="card-img-top rounded-circle mx-auto pt-1"
src="https://image.flaticon.com/icons/svg/2138/2138440.svg" style="height: 200px">
<h4 class="card-title">{{lostPost.pet_name}}</h4>
<p class="card-text"> text: {{lostPost.Text}} <br> location: {{lostPost.Si}}<br>date :
{{lostPost.MissingDate}}</p>
more
{% endif %}
</div>
</div>
</div>
{% endfor %}
{% endfor %}
</div>
</div>
</div>
</div>
</div>
You can access the related dogs with .dog_set.all:
{% for lostPost in lostPosts reversed %}
<h6>{{lostPost.id}}</h6>
{% for dog in lostPost.dog_set.all %}
<h6>{{dog.breed}}</h6><br>
…
{% endfor %}
{% endfor %}
In the view, you pass a queryset with .prefetch_related:
def lostList(request):
lostPosts = LostNotice.objects.prefetch_related('dog')
dogs=Dog.objects
return render(request, '/lostList.html', {'lostPosts' : lostPosts})

Categories

Resources