Put a button in the creation of a model - django

I would like to make sure that in addition to the title, color and description, I would like to make sure that when I create a model it makes me choose which url to render it when Ia person clicks the button. It's possible?
models.py
from django.db import models
from colorfield.fields import ColorField
class Aziende(models.Model):
immagine = models.ImageField()
nome = models.CharField(max_length=250)
prezzo = models.FloatField()
descrizione = models.CharField(max_length=250)
nome_color = ColorField(default='#FF0000')
def __str__(self):
return self.nome
class Meta:
verbose_name_plural = "Aziende"
home.html
[...]
<div class="container">
<div class="row">
{% for Aziende in Borsa %}
<div class="col"><br>
<div class="container text-center">
<div class="card" style="width: 18rem;">
<img src="{{ Aziende.immagine.url }}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="title" style="color: {{Aziende.nome_color}}" >{{Aziende.nome}}</h5>
<p class="card-text">{{Aziende.descrizione}}</p>
<p class="card-text fst-italic text-primary">Valore Attuale: €{{Aziende.prezzo}}</p>
Più info
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
[...]
urls.py (1)
[..]
urlpatterns = [
path('admin/', admin.site.urls),
path('Borsa/', include('Borsa.urls')),
path('accounts/', include('django.contrib.auth.urls')),
path('', TemplateView.as_view(template_name='home.html'), name='home'),
]+static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT)
urls.py (2)
[...]
urlpatterns = [
path('', views.Borsa),
path('Investimenti', views.Investimenti, name='Investimenti'),
]
Thanks in advance!

You can do this way
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Home
admin
Borsa
Link 3
</div>
</div>

Related

Why I can not display two listviews in one template?

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

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 %}

My view isn't rendering any result in the template - django

I'm working on a Django project and i'm quite the beginner so i'm really sorry if this is a basic question, my view isn't showing any result in the template,
here's my view:
def all_products(request):
products = Product.objects.all()
context = {'products': products}
return render(request, 'users/home.html', context)
this is the model:
class Product(models.Model):
title = models.CharField(max_length=255)
id = models.AutoField(primary_key=True)
price = models.FloatField(null=True)
picture = models.ImageField(null=True)
category =models.ForeignKey(Category,related_name='products',on_delete=models.SET_NULL,null=True)
developer = models.ForeignKey(Developer, on_delete=models.SET_NULL, null=True)
and finally this is the part of html needed:
<div class="row justify-content-center" >
{% for product in products %}
<div class="col-auto mb-3">
<div class="card mx-0" style="width: 12rem; height:21rem; background-color: black;">
<img class="card-img-top img-fluid" style="width: 12rem; height:16rem;" src="{{ product.picture.url}}" alt="Card image cap">
<div class="card-block">
<h5 class="card-title mt-1 mb-0" style="color:white; font-size: 18px; font-family: 'Segoe UI';"><b>{{product.title}}</b></h5><a href="#">
<p class="card-text text-muted mb-1" style="color:white;">{{product.developer.title}}</p>
<p class="item-price card-text text-muted"><strike >$25.00</strike> <b style="color:white;"> {{product.price}} </b></p>
</div>
</div>
</div>
{% endfor %}
</div>
I also do have some product objects in my database, so where could the problem be?
Try:
<center>
<div class="row justify-content-center" >
{% for product in products %}
<div class="col-auto mb-3">
<div class="card mx-0" style="width: 12rem; height:21rem; background-color: black;">
<img class="card-img-top img-fluid" style="width: 12rem; height:16rem;" src="{{ product.picture.url }}" alt="Card image cap">
<div class="card-block">
<h5 class="card-title mt-1 mb-0" style="color:white; font-size: 18px; font-family: 'Segoe UI';"><b>{{ product.title }}</b></h5><a href="#">
<p class="card-text text-muted mb-1" style="color:red;">{{ product.developer.name }}</p> # Here I putted 'name' but probably you'll put 'title'; depends on model Developer!
<p class="item-price card-text text-muted"><strike>$ 25.00</strike> <b style="color:red;"> ${{ product.price }} </b></p>
</div>
</div>
</div>
<br>
<br>
<br>
<br>
{% endfor %}
</div>
</center>
In the urls.py of the project:
"""teste URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('core.urls')),
]
In the urls.py of the app:
from django.urls import path
from .views import *
urlpatterns = [
path('products/', all_products, name='products')
]
And to show the image I had to install dj_static and put in wsgi.py:
import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling, MediaCling
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test.settings')
application = Cling(MediaCling(get_wsgi_application()))

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 my models aren't carrying over from file to file

I am getting my menu items to display on the ListView page, but when I click on the link, none of the data displays properly.
Here is my menu-carousel.html
{% for item in object_list %}
<li>
<div class="impx-menu-page-item">
<div class="impx-menu-page-content">
<h4>{{ item.title }}</h4>
<div class="impx-menu-page-price">
<h5>${{ item.price }}</h5>
</div>
<p>{{ item.description }}</p>
</div>
</div>
</li>
{% endfor %}
And that works, now here is the broken part, when I got to /menu/1 or /menu/'whatever number'
<div class="container">
<div class="row">
<h3>{{ item.title }}</h3>
</div>
<div class="row">
<div class = "col-sm-12 col-md-4">
<img src="{{ item.image.url }}" height="300px" width="300px" class = "img img-responsive thumbnail"/>
</div>
<div class = "col-sm-12 col-md-4">
<h6>Price: ${{ item.price }}</h6>
<h6>Materials: {{ item.description }}</h6>
</div>
<div class = "col-sm-12 col-md-4">
<p>{{ item.description|safe|linebreaks }}</p><br /><br />
<hr />
<h5></h5>
</div>
<br><br>
</div>
</div>
This is what displays in my browser
<div class="container">
<div class="row">
<h3></h3>
</div>
<div class="row">
<div class = "col-sm-12 col-md-4">
<img src="" height="300px" width="300px" class = "img img-responsive thumbnail"/>
</div>
<div class = "col-sm-12 col-md-4">
<h6>Price: $</h6>
<h6>Materials: </h6>
</div>
<div class = "col-sm-12 col-md-4">
<p><p></p></p><br /><br />
<hr />
<h5></h5>
</div>
<br><br>
</div>
</div>
Here is my urls.py
from django.conf.urls import url, include
from django.views.generic import ListView, DetailView
from django.contrib import admin
from . import views
from home.models import Menu
urlpatterns = [
url(r'^$', views.home, name="home"),
url(r'^menu/$', ListView.as_view(
queryset=Menu.objects.all().order_by("-title")[:25],
template_name="menu-carousel.html")),
url(r'^menu/(?P<pk>\d+)/$', DetailView.as_view(
model = Menu,
template_name="menu-item.html")),
]
and here is my models.py
from django.db import models
from django.conf import settings
class Menu(models.Model):
title = models.CharField(max_length = 140)
price = models.IntegerField()
description = models.TextField()
image = models.ImageField(upload_to = 'media/' )
menu = models.CharField(max_length = 10)
def __str__(self):
return self.title
I suppose you've used the wrong context object name in DetailView template. More details by link:
https://docs.djangoproject.com/es/1.9/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.get_context_object_name
Try to display menu item id with {{menu.id}} instead of {{item.id}}. Also you can use django debug template to see all context objects.