Why I can not display two listviews in one template? - django

I am working on a Django project where admin can upload a hero banner to the site and can also upload a notification on the home page of the site.
So I made listviews for listing the two HeroListView and NotificationListView for that.
But the second one is not appearing in the page.
Please tell me how to solve this issue.
This is the models.py file
from django.db import models
class Hero(models.Model):
image = models.ImageField(upload_to="heros/")
class Notification(models.Model):
notification = models.CharField(max_length=200)
This is the views.py file.
from django.views.generic import ListView
from .models import Hero, Notification
class HeroListView(ListView):
model = Hero
template_name = "home.html"
context_object_name = "hero_list"
class NoticficationListView(ListView):
model = Notification
template_name = "home.html"
context_object_name = "notification_list"
this is the app/urls.py file
from django.urls import path
from .views import HeroListView, NoticficationListView
urlpatterns = [
path("", HeroListView.as_view(), name="home"),
path("", NoticficationListView.as_view(), name="home"),
]
this is the project/urls.py file
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("heros.urls")),
path("", include("products.urls")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
{% extends '_base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
{% load static %}
<div class="container mt-4">
<div id="carouselExampleControls" class="carousel carousel-dark slide" data-bs-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active">
<img src="{% static 'images/hero2.jpg' %}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% for hero in hero_list %}
<div class="carousel-item">
<img src="{{ hero.image.url }}" class="d-block w-100" alt="..." style="max-height: 400px;">
</div>
{% endfor %}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
<div class="div">
{% for note in notification.list %}
<p>{{ note.notification }}</p>
{% endfor %}
</div>
</div>
{% endblock content %}
please tell me how to solve this issue.

You can do it this way
class HeroListView(ListView):
model = Hero
template_name = "home.html"
def get_context_data(self):
context = super(HeroListView, self).get_context_data()
context['hero_list'] = Hero.objects.all()
context['notification_list'] = Notification.objects.all()
return context
You can't access two or multiple views at the same time, so in your case, you can remove NoticficationListView and use only HeroListView to render both hero_list and notification_list

Related

Django, how can I show variables in other model class?

I'm learning Django and I'm trying to understand its logic. There are 2 models I created. I am designing a job listing page. The first model is "Business". I publish the classes inside this model in my html page and for loop. {% job %} {% endfor %}. But inside my second model in this loop I want to show company_logo class inside "Company" model but I am failing.
Methods I tried to learn;
1- I created a second loop inside the job loop, company loop, and published it failed.
2- I assigned a variable named company_list to the Job class on the views page and made it equal to = Company.objects.all() but it still fails.
Here are my codes.
models.py
from django.db import models
from ckeditor.fields import RichTextField
from djmoney.models.fields import MoneyField
JobTypes = (
('Full-Time', 'Full-Time'), ('Part-Time', 'Part-Time'),
('Internship', 'Internship'), ('Temporary', 'Temporary'), ('Government', 'Government')
)
class Job(models.Model):
job_title = models.CharField( max_length=100, null=True)
job_description = RichTextField()
job_application_url = models.URLField(unique=True)
job_type = models.CharField(max_length=15, choices=JobTypes, default='Full-Time')
#job_category
job_location = models.CharField( max_length=100)
job_salary = MoneyField(max_digits=14, decimal_places=4, default_currency='USD')
created_date = models.DateTimeField(auto_now_add=True)
featured_listing = models.BooleanField( default=False)
company = models.ForeignKey(
"Company", on_delete=models.CASCADE)
def __str__(self):
return f"{self.company}: {self.job_title}"
class Company(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
company_name = models.CharField(max_length=100, unique=True)
company_url = models.URLField(unique=True)
company_logo = models.ImageField(
upload_to='company_logos/')
def __str__(self):
return f"{self.company_name}"
views.py
from django.utils import timezone
from django.shortcuts import render
from .models import Company, Job
def index(request):
jobs = Job.objects.all().order_by('-created_date')[:3]
company_list = Company.objects.all()
context = {
'jobs': jobs,
'company_list':company_list,
}
return render(request, 'index.html', context)
"{% static 'company.company_logo.url' %}" on this page this code is not working. For example, in the coming days I will create a user model and I will have this problem again while publishing the "user.user_name" variable, which will be an example, in my html page. What is the logic here?
index.html
{% extends '_base.html' %}
{% load static %}
{% block content %}
<div class="container">
<!-- Recent Jobs -->
<div class="eleven columns">
<div class="padding-right">
<h3 class="margin-bottom-25">Recent Jobs</h3>
<ul class="job-list">
{% for job in jobs %}
<li class="highlighted"><a href="job-page.html">
<img src="{{ job.company.company_logo.url}}" alt="Logo" class="company-logo">
<div class="job-list-content">
<h4>{{ job.job_title }} <span class="full-time">{{ job.job_type }}</span></h4>
<div class="job-icons">
<span><i class="fa fa-briefcase"></i>{{ job.company }}</span>
<span><i class="fa fa-map-marker"></i> {{ job.job_location }}</span>
{% if job.job_salary %}
<span><i class="fa fa-money"></i> {{job.job_salary}}</span>
{% else %}
<span><i class="fa fa-money"></i>Salary undisclosed</span>
{% endif %}
</div>
</div>
</a>
<div class="clearfix"></div>
</li>
{% endfor %}
</ul>
<i class="fa fa-plus-circle"></i> Show More Jobs
<div class="margin-bottom-55"></div>
</div>
</div>
<!-- Job Spotlight -->
<div class="five columns">
<h3 class="margin-bottom-5">Featured</h3>
<!-- Navigation -->
<div class="showbiz-navigation">
<div id="showbiz_left_1" class="sb-navigation-left"><i class="fa fa-angle-left"></i></div>
<div id="showbiz_right_1" class="sb-navigation-right"><i class="fa fa-angle-right"></i></div>
</div>
<div class="clearfix"></div>
<!-- Showbiz Container -->
<div id="job-spotlight" class="showbiz-container">
<div class="showbiz" data-left="#showbiz_left_1" data-right="#showbiz_right_1" data-play="#showbiz_play_1" >
<div class="overflowholder">
<ul>
{% for job in jobs %}
{% if job.featured_listing %}
<li>
<div class="job-spotlight">
<h4>{{job.job_title}} <span class="freelance">{{job.job_type}}</span></h4>
<span><i class="fa fa-briefcase"></i>{{job.company}}</span>
<span><i class="fa fa-map-marker"></i> {{job.job_location}}</span>
<span><i class="fa fa-money"></i> {{job.job_salary}} / hour</span>
<p>{{ job.job_description | safe | truncatechars:150 }}</p>
Apply For This Job
</div>
</li>
{% endif %}
{% endfor %}
</ul>
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
index.html problem:
urls.py
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
from django.urls import path
from . import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('', views.index,name="index"),
#path("jobs/", JobListView.as_view(), name="jobs")
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
the syntax is not
{% static 'company.company_logo.url' %} or **{% static 'company.company_logo.url' %}**
use this instead
{{ company.company_logo.url }}
also if you want to make relations between Job and Company, you can make it like so
inside Job model add this new field
company = models.ForeignKey('Company', on_delete=models.CASCADE)
So that one company can have multiple jobs
Then inside the job for loop in HTML just add this to display company_logo
{% for job in jobs %}
*..........remaining code..........*
<img src="{{ job.company.company_logo.url }}" alt="">
*..........remaining code..........*
{% endfor %}

Django: active Home link

This is my first project with django, I wanted my static site html/css/js to turn it into a dynamic website. However, in navMenu I want to have 'home' link only if the user is not on the index page.
Here is my attempt:
<style>
#hm{
display:none;
}
.activate{
display:block;
}
</style>
<div id="navMenu" class='py px'>
<ul>
{% url 'home' as home_view %}
<li id = 'hm' {% if request.get_full_path != home_view%} class = 'activate' {% endif%}>Home</li>
<li class='brd'>Alumni</li>
<li class='brd'>Staff</li>
<li class='brd'>Services</li>
<li class='brd'>About</li>
<li><a id='btnSearch' href="#"><i class="fa fa-search searchUpdate"></i></a></li>
</ul>
</div>
the urls:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from pages.views import home_view
from events.views import events
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_view, name = 'home'),
path('events/', events, name = 'events')
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
Any help is appreciated!
You could try adding a content block with and adding it only to the templates that you want to have the url on
If you dont know how to do that then it goes like this
<div id="navMenu" class='py px'>
{% block urls %}{% endblock urls %}
</div>
Then, for all of the pages that you want the url to be on, make a new template with:
{% block urls %}
<ul>
{% url 'home' as home_view %}
<li id = 'hm' {% if request.get_full_path != home_view%} class = 'activate' {% endif%}>Home</li>
<li class='brd'>Alumni</li>
<li class='brd'>Staff</li>
<li class='brd'>Services</li>
<li class='brd'>About</li>
<li><a id='btnSearch' href="#"><i class="fa fa-search searchUpdate"></i></a></li>
</ul>
{% endblock urls %}

Page not found (404) Request Method:

please help me. I don't know why can't see the detail of product when i click a product. both first list work good just when i need to see detail of product in second list(filtered list) an 404 error shows.
thanks
here is my code below:
my urls:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
]
views:
from django.shortcuts import render, get_object_or_404, get_list_or_404
from django.views import generic
from .models import Category, Product
class HomeView(generic.ListView):
model = Category
template_name = 'home.html'
class ProductListView(generic.ListView):
template_name = 'product_list.html'
def get_queryset(self):
self.category = get_object_or_404(Category, title=self.kwargs['category'])
return Product.objects.filter(category=self.category)
class ProductDetailView(generic.DetailView):
model = Product
template_name = 'product_detail.html'
product_list.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Welcome | Global Market
{% endblock %}
{% block content %}
{% for product in product_list %}
<a href="{% url 'shop:product-detail' product.pk %}">
<div class="card bg-light mb-3" style="max-width: 18rem;">
<div class="card-header">{{ product.title }}</div>
<img class="card-img-top" src="{{ product.image.url }}" alt="{{ product.title }}">
<div class="card-body">
<p class="card-text">{{ product.description }}</p>
</div>
</div>
</a>
{% endfor %}
{% endblock %}
product_detail.html
{% extends 'base.html' %}
{% load static %}
{% block title %}
Welcome | Global Market
{% endblock %}
{% block content %}
<h1>thid</h1>
{{ product.name }}
{% endblock %}
Even if the you visit /categories/1, it will use the ProductListView, since the str path converter also accepts a sequence of digits. You can swap the paths, so:
from django.urls import path
from . import views
app_name = 'shop'
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('categories/<int:pk>/', views.ProductDetailView.as_view(), name='product-detail'),
path('categories/<category>/', views.ProductListView.as_view(), name='product-list'),
]
Then for /categories/1, it will match with <int:pk> as 1, and thus fire the ProductDetailView.

Django can't display the image saved in the database

I wrote two templates in Django "index.html" and "detail.html". In both templates, I display png, in the template "index" the graphics are displayed correctly, and in the template "detail" has the status "src (unknown)".
detail.html (details.html should display only one graphic)
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Course Detail</h1>
<p class="lead text-muted"> {{ films.summary}}.</p>
<img class = "card-img" src="{{film.image.url}}" > </img>
<p>
Back
</p>
</div>
</section>
index.html
<div class="row">
{% for film in films.all %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<a href="{% url 'detail' film.id %}">
<img class = "card-img" src="{{film.image.url}}" > </img>
</a>
<div class="card-body">
<p class="card-text"> {{film.summary}} </p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Films
# Create your views here.
def index(request):
films = Films.objects.all()
return render(request, 'films/index.html',{'films':films})
def detail(request, films_id):
films_detail = get_object_or_404(Films,pk=films_id)
return render(request, 'films/detail.html',{'films':films_detail})
urls.py
from django.urls import path
from .import views
urlpatterns = [
path('', views.index, name="index"),
path('<int:films_id>', views.detail, name="detail"),
]
Before going to display any image you should make your url.py inform about it, So the right way to do this is by creating following MEDIA_ROOT and MEDIA_URL in setting.py
Managing Media
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
After that import this in url.py from setting and add it to urlpatterns
Adding URL
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
After adding this Django will Definitely Recognize your URL
The real problem in your code is that you are passing films(as Dictionary) from views.py but assessing it in templates as film
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from .models import Films
def index(request):
films = Films.objects.all()
return render(request, 'films/index.html',{'films':films})
def detail(request, films_id):
films_detail = get_object_or_404(Films,pk=films_id)
return render(request, 'films/detail.html',{'films':films_detail})
index.html
` <div class="row">
{% for film in films.all %}
<div class="col-md-4">
<div class="card mb-4 shadow-sm">
<a href="{% url 'detail' films.id %}">
<img class = "card-img" src="{{films.image.url}}" > </img>
</a>
<div class="card-body">
<p class="card-text"> {{films.summary}} </p>
</div>
</div>
</div>
{% endfor %}
</div>
</div>`
detail.html
<section class="jumbotron text-center">
<div class="container">
<h1 class="jumbotron-heading">Course Detail</h1>
<p class="lead text-muted"> {{ films.summary}}.</p>
<img class = "card-img" src="{{film.image.url}}" > </img>
<p>
Back
</p>
</div>
</section>

django create form with materialize modal

As far as I tried, I cannot get the form data or send it to the django view function through the materialize css modal. I'm just a novice in js, ajax and related.
The "CreateView" action for my form is running outside, but it is required to be inside a modal and still get the benefits of using django form validation, security, and so on. I'm using Django version 1.11.
The project has two applications: main that loads the main page, and library that performs actions on book objects. A book has only a title, and so there's a form defined like:
library/forms.py:
from django import forms
from .models import Book
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = [
'title',
]
the project urls definition, mysite/urls.py :
from django.conf.urls import url, include
from django.contrib import admin
from main import views as main_views
urlpatterns = [
url(r'^$', main_views.home, name='home'),
url(r'^books/', include('library.urls')),
url(r'^admin/', admin.site.urls),
]
Home view, main/views.py:
from django.shortcuts import render
def home(request):
return render(request, 'main/home.html')
main/templates/main/home.html:
<html>
<head>
<title>A library</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
{% block body %}
<div class="container">
<!--a class="waves-effect waves-light btn modal-trigger" href="#modal1">Create Book</a-->
<a class="waves-effect waves-light btn modal-trigger" data-target="add_book_modal" href="{% url 'books:create' %}">
Create Book
</a>
<div class="divider"></div>
<div class="section">
<h5>Section 1</h5>
<p>Stuff</p>
</div>
</div>
{% endblock %}
{% include 'library/book_form.html' %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script>
$( document ).ready(function() {
$('.modal').modal();
});
</script>
</body>
</html>
The library's urls, library/urls.py:
from django.conf.urls import url
from .views import BookCreateView
app_name='books'
urlpatterns = [
url(r'^create/$', BookCreateView.as_view(), name='create'),
]
library/views.py:
from django.shortcuts import render
from django.views.generic import CreateView
from django.urls import reverse_lazy
from .models import Book
from .forms import BookForm
class BookCreateView(CreateView):
form_class = BookForm
template_name = 'library/book_form.html'
success_url = reverse_lazy('home')
library/templates/library/book_form.html:
<div id="add_book_modal" class="modal">
<div class="modal-content">
{% block body %}
<main>
<h5>Add book information</h5>
{% if form.errors.non_field_errors %}
{{ form.errors.non_field_errors }}
{% endif %}
<form method="POST">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
<!--Form content-->
{{form.as_p}}
<!--Form button-->
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
</button>
</form>
</main>
{% endblock %}
</div>
</div>
Any help will be appreciated.
Changing a href link and setting the place of html code where the content will be rendered
main/templates/main/home.html:
...
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Create Book</a>
...
<!-- Modal Structure -->
<div id="modal1" class="modal">
<div class="modal-content">
<!--Form content goes in here.-->
</div>
</div>
{% endblock %}
<!-- django include tag removed -->
Jquery to render the form in the modal through django's routes
main/templates/main/home.html:
<script>
$( document ).ready(function() {
$('.modal').modal();
$('.modal-content').load("{% url 'books:create' %}");
});
</script>
Finally, book form specifying the way back.
_library/templates/library/book_form.html_:
<h5>Add book information</h5>
{% if form.errors.non_field_errors %}
{{ form.errors.non_field_errors }}
{% endif %}
<form method="POST" action="{% url 'books:create' %}">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.source.errors }}
{{ form.source }}
<!--Form content-->
{{form.as_p}}
<!--Form button-->
<button class="btn waves-effect waves-light" type="submit" name="action">Submit form
</button>
</form>