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})
Related
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>
I am having a problem in categorize Posts. I have categories in Post Model, Please help me solve this issue!
MODELS.PY
html= "html"
css= "css"
python= "python"
javascript = "javascript"
Lang=(
(html,"HTML"),
(css,"CSS"),
(python,"PYTHON"),
(javascript,"JAVASCRIPT")
)
Broilerplate = "Broilerplate"
Simple_Tags = "Simple Tags"
Elements = "Elements"
Webpages = "Webpages"
Category = (
(Broilerplate,"BROILERPLATE"),
(Simple_Tags,"Simple tags"),
(Elements,"Elements"),
(Webpages,"Webpages")
)
class Post(models.Model):
title = models.CharField(max_length=75)
subtitle = models.CharField(max_length=150)
language_1 = models.CharField(max_length=100, choices=Lang, default=html)
content_1= models.TextField(blank=True)
language_2 = models.CharField(max_length=100, choices=Lang,blank=True)
content_2= models.TextField(blank=True)
language_3 = models.CharField(max_length=100, choices=Lang,blank=True)
content_3= models.TextField(blank=True)
language_4 = models.CharField(max_length=100, choices=Lang,blank=True)
content_4= models.TextField(blank=True)
language_5 = models.CharField(max_length=100, choices=Lang,blank=True)
content_5= models.TextField(blank=True)
category= models.CharField(max_length=100, choices=Category, default=Broilerplate)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
# def update(self):
# updated_at = timezone.now()
# self.save(updated_at)
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
VIEWS.PY
def search_by_category(request, category):
if request.post.objects.filter(pk=request.post.id).first().category == 'Broilerplate':
nor = request.post.objects.filter(pk=request.post.id).first().category
print(nor)
posts = Post.objects.filter(category='Broilerplate')
category = posts.first().category
print(category)
context = {'posts': posts, 'title': category , 'category': category}
return render(request, 'category.html', context)
else:
context = {'title': category , 'category': category}
return render(request, 'category.html', context)
URLS.PY
urlpatterns = [
path('html/',PostListView.as_view(), name='CodeWriter_Homepage'),
path('python/',views.CodeWriter_homepage_python, name='CodeWriter_Homepage_python'),
path('search/', views.search, name='search'),
path('categroize-by/<str:category>/', views.search_by_category, name='search_by_category'),
path('post-details/<int:pk>/',PostDetailView.as_view(), name='Post_details_page'),
path('post-update/<int:pk>/',PostUpdateView.as_view(), name='Post_update_page'),
path('post-delete/<int:pk>/',PostDeleteView.as_view(), name='Post_delete_page'),
path('user/<str:username>/', UserPostListView.as_view(), name='user-post'),
path('new-post/',PostCreateView.as_view(), name='New-post_page')
]
CATEGORY.html
How can I get the data of the post category in views.py?That will help me very much!
{% block main_post_body %}
<main class="post-body normal" >
<p class="post-heading"> Post for <b>{{ category }}</b> :</p>
{% comment %} <h1 class="mb-3">Search results for <b>{{category}}</b>: </h1> {% endcomment %}
{% comment %} {% if posts|length < 1 %}
<h3>No search results found</h3>
<p>Your search results for <b>{{ query }}</b> is not found.</p>
{% endif %} {% endcomment %}
{% for post in posts %}
<div class="row">
<div class="col span-8-of-12 card">
<div class="row">
<!-- <div class="triangle"></div>
<div class="person-info-card">
<div class="row">
<div class="col"><img src="{% static 'resoures/css/img/Me.jpg' %}" alt=""></div>
<div class="col">
<p>Ketan Vishwakarma</p>
<p class="post-no">126 Posts | 1k Followers</p>
</div>
</div>
</div> -->
<div class="col span-1-of-12">
<div class="person-img" id="person-info-card-toggle">
<img src="{{ post.author.profile.image.url }}" alt="" />
</div>
</div>
<div class="col span-7-of-12">
<h3>{{ post.title }} </h3>
<h4>{{ post.subtitle }}</h4>
</div>
<div class="col span-1-of-12">
<span class="ion-md-heart-empty"></span>
</div>
<div class="col span-1-of-12">
<span class="ion-md-add-circle-outline"></span>
</div>
<div class="col span-1-of-12 share">
<span class="ion-md-share"></span>
<ul class="dropdown-list-share">
<li><span class="ion-md-copy"> Copy</span></li>
<li><span class="ion-logo-whatsapp"> Share on Whatsapp</span></li>
<li><span class="ion-logo-facebook"> Share on facebook</span></li>
<li><span class="ion-md-more"> More</span></li>
</ul>
</div>
<div class="col span-1-of-12">
<span class="ion-md-menu"></span>
<ul class="dropdown-list">
<li>Doesn't work</li>
<li>Report</li>
<li>Report</li>
</ul>
</div>
</div>
<div class="tabs">
<ul class="tabs-list">
<li class="active">{{ post.language_1 }}</li>
{% if post.content_2 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_2 }}</li>
{% endif %}
{% if post.content_3 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_3 }}</li>
{% endif %}
{% if post.content_4 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_4 }}</li>
{% endif %}
{% if post.content_5 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_5 }}</li>
{% endif %}
<ul class="categories">
<abbr title="Categiores">
<a href="">
<span class="ion-md-code-working"></span>
{{ post.category }}
</a>
</abbr>
<!-- <li>Broilerplate</li> -->
</ul>
</ul>
<div id="tab1" class="tab active">
<p>
<pre><code class="language-{{ post.language_1 }}">
{{ post.content_1 }}
</code></pre>
</p>
</div>
<div id="tab2" class="tab">
<p>
<pre><code class="language-{{ post.language_2 }}">
{{ post.content_2 }}
</code></pre>
</p>
</div>
<div id="tab3" class="tab">
<p>
<pre><code class="language-{{ post.language_3 }}">
{{ post.content_3 }}
</code></pre>
</p>
</div>
<div id="tab4" class="tab">
<p>
<pre><code class="language-{{ post.language_4 }}">
{{ post.content_4 }}
</code></pre>
</p>
</div>
<div id="tab5" class="tab">
<p>
<pre><code class="language-{{ post.language_5 }}">
{{ post.content_5 }}
</code></pre>
</p>
</div>
</div>
<span class="ion-md-arrow-round-down"> Read More</span>
<h6>{{ post.date_posted|date:"F d, Y" }}</h6>
</div>
<div class="col span-4-of-12 main-card ">
<div class="card-small">
<h1>Result: </h1>
<div class="result-box">
<iframe src="" frameborder="0">just for fun</iframe>
</div>
<h6>{{ post.date_posted|date:"F d, Y" }}</</h6>
</div>
</div>
</div>
{% endfor %}
</main>
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock main_post_body %}
NoteI have registered the Post model in admin.py
Tell me the solution to this problem I cannot get the solution I have been trying it for so long and am stuck on this.
I am using bootstrap tabs navigation bar and I want to retrieve the id of the tag and pass it to my view but my main issue though is I am not using them in my urls.py. Here is my urls.py file.
from django.urls import path
from .views import (
index, add_task, update_task,
delete_task, update_categories,
delete_all_task
)
urlpatterns = [
path('', index, name="home"),
path('add-task/', add_task, name="add-task"),
path('update-task/<int:pk>/', update_task, name="update-task"),
path('delete-task/<int:pk>/', delete_task, name="delete-task"),
path('update-category/', update_categories, name="update-category"),
path('delete_all_tasks/', delete_all_task, name="delete_all_tasks"),
]
And here is the views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.forms import modelformset_factory
from .models import Tasks, Category
from .forms import AddTaskForm, UpdateTaskForm, UpdateCategoryForm
def get_task_minid(categories):
id_list = []
for task in categories:
id_list.append(task.id)
min_id = min(id_list)
return min_id
def index(request):
tasks = Tasks.objects.all()
categories = Category.objects.all()
if len(categories) > 1:
min_id = get_task_minid(categories)
if request.method == "POST":
category = request.POST.get('category')
cat = Category.objects.create(name=category)
cat.save()
return redirect('home')
context = {
'tasks': tasks,
'categories': categories,
'min_id': min_id,
}
return render(request, 'Todo/index.html', context)
and here is the index.HTML
<div class="" id="Todo-tasks">
<div class="card card-primary card-outline">
<div class="card-body">
<div class="row">
<div class="col-5 col-sm-3">
<div class="card-header">
<span>All Categories</span>
</div>
<div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab" role="tablist" aria-orientation="vertical">
{% for cat in categories %}
{% if cat.id == min_id %}
<a class="nav-link active" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="true">{{cat}}</a>
{% else %}
<a class="nav-link" id="vert-tabs-{{cat}}-tab" data-toggle="pill" href="#vert-tabs-{{cat}}"
role="tab" aria-controls="vert-tabs-{{cat}}" aria-selected="false">{{cat}}</a>
{% endif %}
{% endfor %}
<div class="card-footer mt-3">
<form action="" method="POST">
{% csrf_token %}
<input type="text" name="category" placeholder="Add category" class="new-input cat" aria-label="Add new category" />
<button type="submit" class="new">+</button>
</form>
</div>
Manage Categories
</div>
</div>
<div class="col-7 col-sm-9">
<div class="tab-content" id="vert-tabs-tabContent">
{% for cat in categories %}
{% if cat.id == min_id %}
<div class="tab-pane text-left fade show active" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
<div class="card-header d-flex justify-content-between justify-content-center">
{{ cat }}
<div class="form-group">
<form action="" class="p-0 justify-content-end" method="post">
<input type="text" name="search" class="form-input pl-3" placeholder="Search for tasks..."/>
</form>
</div>
</div>
{% for task in cat.tasks.all %}
<li class="align-content-center"><a>{{task.text}}
<small class="badge bg-success">{{task.due_date|timeuntil|upto:','}}</small>
<span class=""></i></span>
<span class=""></i></span>
</a>
</li>
{% empty %}
<h3 class="alert alert-info m-5"><i class="fas fa-alert-outline"></i> Please add new tasks to categories</h3>
{% endfor %}
</ul>
</div>
{% else %}
<div class="tab-pane text-left fade show" id="vert-tabs-{{cat}}" role="tabpanel" aria-labelledby="vert-tabs-{{ cat }}-tab">
<ul class="list-unstyled border pb-4">
Now, how I am thinking of a way to get the h ref in the like(h ref="vert-tabs-{{cat}}" I want to get the value of the cat variable anytime I switch to a different sort of view or tab content.
Any help would be so appreciated even JavaScript or j query.
Thank you in advance...
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.
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 %}