Django crispy forms: Controls do not fill entire layout horizontally - django

I'm learning how to use Crispy Forms, following Vitor Freitas' tutorial.
However, when pasting his exact code in a form and in a template, the text boxes do not fill horizontally the space as intended.
The code (copied from Vitor's site):
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column
STATES = (
('', 'Choose...'),
('MG', 'Minas Gerais'),
('SP', 'Sao Paulo'),
('RJ', 'Rio de Janeiro')
)
class AddressForm(forms.Form):
email = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Email'}))
password = forms.CharField(widget=forms.PasswordInput())
address_1 = forms.CharField(
label='Address',
widget=forms.TextInput(attrs={'placeholder': '1234 Main St'})
)
address_2 = forms.CharField(
widget=forms.TextInput(attrs={'placeholder': 'Apartment, studio, or floor'})
)
city = forms.CharField()
state = forms.ChoiceField(choices=STATES)
zip_code = forms.CharField(label='Zip')
check_me_out = forms.BooleanField(required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.layout = Layout(
Row(
Column('email', css_class='form-group col-md-6 mb-0'),
Column('password', css_class='form-group col-md-6 mb-0'),
css_class='form-row'
),
'address_1',
'address_2',
Row(
Column('city', css_class='form-group col-md-6 mb-0'),
Column('state', css_class='form-group col-md-4 mb-0'),
Column('zip_code', css_class='form-group col-md-2 mb-0'),
css_class='form-row'
),
'check_me_out',
Submit('submit', 'Sign in')
)
Intended layout:
Actual result in my experiment:
The HTML code:
base.html
<!DOCTYPE html>
{% load static %}
<html lang='sp'>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
<title>
{% block title %}
Page title
{% endblock title %}
</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{% url 'home'%}">
<img src="{% static 'img/blc_logo.jpg'%}"
alt="Logo"
height="40em"/>
My awesome page
</a>
<button class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#mainMenu"
aria-controls="mainMenu"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="mainMenu">
{% if user.is_authenticated %}
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
href="#" id="userMenu"
data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
{{ user.username }}
</a>
<div class="dropdown-menu dropdown-menu-right"
aria-labelledby="userMenu">
{% if user.is_type_one %}
<a class="dropdown-item"
href="{% url 'type_one:home' %}">
My panel
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">
My account
</a>
{% elif user.is_type_two %}
<!-- TODO: create type_two menu -->
{% endif %}
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="{% url 'logout' %}">
Log out
</a>
</div>
</li>
</ul>
{% else %}
<form class="form-inline ml-auto">
<a class="btn btn-secondary"
href="{% url 'login' %}">
Log in
</a>
<a class="btn btn-primary"
href="{% url 'users:signup' %}">
Sign up
</a>
</form>
{% endif %}
</div>
</div>
</nav>
<div class="container">
<ol class="breadcrumb my-4">
{% block breadcrumb %}
{% endblock breadcrumb %}
</ol>
{% block content %}
{% endblock content %}
</div>
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<script src="https://unpkg.com/#popperjs/core#2"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
test_form.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
{% crispy form_test %}
{% endblock content %}
So... I don't know what I'm missing. Can you point me in the right direction?

The tutorial sets a setting CRISPY_TEMPLATE_PACK = 'bootstrap4'. Maybe you use a different bootstrap version, or forgot to set this setting?

Related

Python django, when creating an registering form how to get this .get method working?

I started to watch Corey Schafer's django website tutorial and everything was going great until now. unlike in the video after registering site doesn't sends me to home page. It does nothing. All I suspect is the get method because it is not the color it supposed to be in VSC. Any ideas why :(
and also .method functions seems to be not working it is white in VSC
user_views.py:
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect, render
def register(request):
if request.method =='POST':
form = UserCreationForm(request.POST)
if form.is_valid():
username=form.cleaned_data.get('username')
messages.success(request,f'Account Created for {username}')
return redirect("blog-home")
else:
form=UserCreationForm()
return render(request,'users/register.html',{'form':form})
here is the urls:
from django.contrib import admin
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path("", include('Blog.urls')),
path("register/",user_views.register,name="register")
]
Blog.urls:
from django.urls import path
from . import views
urlpatterns= [
path("",views.Home,name="blog-home"),
path("about/",views.About, name="blog-about"),
]
templates:
{% extends "Blog/base.html" %}
{% block content %}
<div class='content-section'>
<form method='POST'>
{% csrf_token %}
<fieldset class="form_group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form.as_p }}
</fieldset>
<div class="form-group">
<button class="btn btn-outlline-info" type="submit">
Sign Up
</button>
</div>
</form>
<div class="boder-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#"> Sign In </a>
</small>
</div>
</div>
{% endblock content %
base template:
{% load static %}
<!DOCTYPE html >
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="{% static 'Blog/main.css' %}">
{% if title %}
<title> {{title}} </title>
{% else %}
<title> Django Project </title>
{% endif %}
</head>
<body>
<header class="site-header">
<nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top">
<div class="container">
<a class="navbar-brand mr-4" href="{%url 'blog-home'%}">Django Blog</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarToggle">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{%url 'blog-home'%}">Home</a>
<a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a>
</div>
<!-- Navbar Right Side -->
<div class="navbar-nav">
<a class="nav-item nav-link" href="#">Login</a>
<a class="nav-item nav-link" href="{%url 'register' %}">Register</a>
</div>
</div>
</div>
</nav>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-md-8">
{% if messages %}
{% for message in messages %}
<div class="Alert alert-{{ message.tags}}">
{{message}} </div>
{% endfor %}
{% endif %}
{% block content %}{% endblock %}
</div>
<div class="col-md-4">
<div class="content-section">
<h3>Our Sidebar</h3>
<p class='text-muted'>You can put any information here you'd like.
<ul class="list-group">
<li class="list-group-item list-group-item-light">Latest Posts</li>
<li class="list-group-item list-group-item-light">Announcements</li>
<li class="list-group-item list-group-item-light">Calendars</li>
<li class="list-group-item list-group-item-light">etc</li>
</ul>
</p>
</div>
</div>
</div>
</main>
People who had a problem with PATH variables before listen me carefully this might save you a lot of time, Although I still don't know why and how. There is a django_settings module which is not present anywhere or maybe I couldn't find the exact folder but however this module can be set to your projects setting module that fixes the problem:
set DJANGO_SETTINGS_MODULE=mysite.settings
django-admin runserver
from the terminal, this sets your path of settings I guess

403 Forbidden CSRF cookie not set even when it is in the form

When I attempt to log in to my django website, I always get a 403 Forbidden CSRF cookie not set error. When viewed via developer tools, the CSRF token was in the form response, but there were no cookies. I have django.middleware.csrf.CsrfViewMiddleware in my middleware, and I am using the standard django.contrib.auth.views.LoginView.
Here is my template:
{% extends 'base/formbase.html' %}
{% block title %}Login{% endblock title %}
{% block menuid %}menu-login{% endblock menuid %}
{% block submitname %}Login{% endblock submitname %}
{% block extra %}
<div class="alert alert-danger">
Forgot Your Password?
</div>
<div class="alert alert-secondary">
Don't have an account? Sign Up!
</div>
{% endblock extra %}
base/formbase.html:
{% extends 'base/base.html' %}
{% load crispy_forms_tags %}
{% block body %}
<div class="row justify-content-center">
<div class="col-6">
<div class="card">
<div class="card-body">
{% block form %}
<h2>{% block title %}{% endblock title %}</h2>
<form method="post" novalidate>
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">{% block submitname %}{% endblock submitname %}
</button>
</form>
{% endblock form %}
</div>
{% block extra %}{% endblock extra %}
</div>
</div>
</div>
{% endblock body %}
base/base.html:
<!DOCTYPE html>
{% load base_extra %}
<html lang="en">
<head>
{% settings gamename "GAME_NAME" %}
<meta charset="UTF-8">
<title>{{ gamename }} - {% block title %}{% endblock title %}</title>
{% block head %}{% endblock head %}
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
{% settings debug "DEBUG" %}
{% if debug %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/latest/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://unpkg.com/#popperjs/core/dist/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/latest/js/bootstrap.js"></script>
{% else %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script src="https://unpkg.com/#popperjs/core/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/latest/js/bootstrap.min.js"></script>
{% endif %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="{% url 'index' %}">{{ gamename }}</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item" id="menu-home">
<a class="nav-link" href="{% url 'index' %}">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item" id="menu-gamelist">
<a class="nav-link" href="{% url 'game:game_list' %}">Game List</a>
</li>
<li class="nav-item" id="menu-leaderboard">
<a class="nav-link" href="{% url 'user_list' %}">Leaderboard</a>
</li>
{% if request.user.is_staff %}
<li class="nav-item" id="menu-admin">
<a class="nav-link" href="{% url 'admin:index' %}">Admin</a>
</li>
{% endif %}
</ul>
<!--
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
-->
<ul class="navbar-nav ml-auto">
{% if request.user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
{{ request.user }}
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{% url 'user' user.pk %}">Profile</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{% url 'logout' %}">Log out</a>
</div>
</li>
<li class="nav-item">
<div class="nav-link">${{ request.user.gameinfo.money }}</div>
</li>
{% else %}
<li class="nav-item" id="menu-signup">
<a class="nav-link" href="{% url 'signup' %}">Sign Up</a>
</li>
<li class="nav-item" id="menu-login">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
{% endif %}
</ul>
</div>
</nav>
<div class="mx-3 mt-2">
<script>
try {
document.getElementById("{% block menuid %} {% endblock menuid %}").classList.add("active");
}
catch {}
</script>
{% block body %}
{% endblock body %}
</div>
</body>
</html>
Adding the #csrf_protect decorator does not solve the problem.
This may occur if you have CSRF_COOKIE_SECURE = True explanation in the docs Or if you have CSRF_COOKIE_HTTPONLY = True explanation or if you wish to just disable the csrf token you can add the #csrf_exempt decorator to the view

I want to get the vote button with proper functionality but I'm unable to do that

I want vote button that works properly, when user clicks that button it should increase the number of votes there itself.
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from . models import Question, Choice
from django.urls import reverse
# Create your views here.
def base(request):
return render(request, 'base.html')
def home(request):
return render(request, 'home.html')
def quest(request):
question_list=Question.objects.all()
context={'question_list': question_list}
return render(request, 'quest.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.base, name='base'),
path('home', views.home, name='home'),
path('quest', views.quest, name='quest'),
]
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<title>Voting World</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{% url 'home' %}">Home</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav ml-auto">
<a class="nav-item nav-link active" href="#">About us</a>
<a class="nav-item nav-link active" href="#"><i class="fas fa-user"></i> Login</a>
<a class="nav-item nav-link active" href="#"><i class="fas fa-sign-in-alt"></i> Signup</a>
</div>
</div>
</nav>
<div class="container">
{% block body %}
{% endblock %}
</div>
</body>
</html>
quest.html
{% extends 'base.html' %}
{% block body %}
{% if question_list %}
<ul style="list-style: none;">
{% for question in question_list %}
<div class="row mt-3 text-danger">
<li><h3>{{ question.title }}</h3><p style="color: #072e6e">{{ question.pub_date }}</p></li>
</div>
<div class="row mt-3">
<div class="col-md-5">
<li><img src="{{ question.image1.url }}"></li>
</div>
<div class="col-md-2">
<h1 style="font-size: 180px; margin-left: -95px;">v/s</h1>
</div>
<div class="col-md-5">
<li><img src="{{ question.image2.url }}"></li>
</div>
</div>
<div class="row">
<div class="col-md-5">
<button class="btn btn-success">Vote</button>
</div>
<div class="col-md-5">
<button class="btn btn-success">Vote</button>
</div>
</div>
{% endfor %}
</ul>
{% else %}
<p>No Polls Available!!..</p>
{% endif %}
{% endblock %}
models.py
from django.db import models
# Create your models here.
class Question(models.Model):
title = models.CharField(max_length=100)
image1 = models.ImageField(upload_to='pics')
image2 = models.ImageField(upload_to='pics')
pub_date = models.DateTimeField()
def __str__(self):
return self.title
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
vote1 = models.IntegerField(default=0)
vote2 = models.IntegerField(default=0)
i expected the output when user click the vote, it should increase the value of vote by 1, i.e. vote+1....but I'm not getting how to do that.

Py 3.6 // Django 2.1.4 : Accessing User Profile mysteriously changes the status of user.is_authenticated to True

I have been having this problem for 2 weeks now I can't seem to solve it.
I have a social website where user's can upload their resumes for recruiters to see.
And when I access some user's profile, the Navbar acts as if I am logged in, which I am not.
I tried fixing this issue by using get_queryset() ,it worked but I couldn't manage to display user's profile data.
so I stuck with get().
Here's a visual explanation:
As you can see the navbar says Home/Login/Signin
Now if I access John Doe's Profile, the navbar will switch to Home/Profile/Logout:
Here's my code;
views.py:
class HomeProfile(ListView):
"Di splays all active users in db"
template_name = 'profile/home_profile.html'
queryset = MyModel.objects.filter(is_active=True)
class Get_Profile(DetailView):
"fetches user's profile"
def get(self, request, pk):
user = MyModel.objects.get(pk=pk)
return render(request, 'profile/profile.html', {'user':user})
urls.py
urlpatterns = [
path('homepage/profiles/', user_view.HomeProfile.as_view(), name='homepage'),
path('homepage/profile/<int:pk>/', user_view.Get_Profile.as_view(), name='user-profile'),
]
base_test.html
<nav class="navbar navbar-expand-sm navbar-dark bg-dark sticky-top">
<a class="navbar-brand" href="{% url 'home' %}">Navbar</a>
<button class="navbar-toggler d-lg-none" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavId">
<ul class="navbar-nav ml-auto mt-2 mt-lg-0">
<li class="nav-item active">
<a class="nav-link" href="{% url 'homepage' %}">Home<span class="sr-only">(current)</span></a>
</li>
{% if not user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'signup' %}">Sign Up</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="#">Profile</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Log Out</a>
</li>
{% endif %}
</ul>
</div>
</nav>
home_profile.html
<!-- this is the home template that displays all active users -->
{% extends 'base_test.html' %}
{% block title %} My Site | Profiles {% endblock title %}
{% block content %}
<div class="card-columns text-center padding">
{% for user in mymodel_list %}
<div class="card">
<img class="rounded-circle" src="{{user.profile.image.url}}" width=150 height=150>
<div class="card-body">
<h5 class="card-title">Full name : {{user.get_full_name}}</h5>
<p class="crad-text">Occupation/job : {{user.profile.occupation}}</p>
<a type="button" href="{% url 'user-profile' user.pk %}" style="color:whitesmoke;" class="btn btn-primary btn-sm">Profile</a>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
{% block footer %}
{% endblock footer %}
profile.html
<!-- user profile template -->
{% extends 'base_test.html' %}
{% load custom_tags %}
{% block title %} My Site | {{user.get_full_name}} {% endblock title %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-lg-8 order-lg-2 padding">
<div class="tab-content">
<div class="tab-pane active" id="profile">
<div class="row">
<div class="col-lg-12">
<h6><strong>About</strong></h6>
<p>
{{user.profile.bio}}
</p>
<hr>
</div>
<div class="col-lg-12">
<h6><strong>Skills</strong></h6>
{% for skill in user.profile.skills|split:',' %}
<span class="badge badge-primary">{{skill}}</span>
{% endfor %}
<hr>
<h6><strong>Hobbies</strong></h6>
<p>
{% for hobbie in user.profile.hobbies|split:',' %}
<span class="badge badge-success">{{hobbie}}</span>
{% endfor %}
</p>
<hr>
</div>
<!-- removes the social part -->
</div>
</div>
</div>
</div>
<div class="col-lg-4 order-lg-1 padding">
<h1 class="mb-3 text-center">{{user.get_full_name}}</h1>
<hr>
<img src="{{user.profile.image.url}}" class="mx-auto img-fluid rounded-circle d-block" alt="avatar" width=150><br>
<div class="text-center">
<h4>{{user.profile.school}}</h4>
<p><strong>Hometown :</strong> {{ user.profile.hometown}}</p>
<p><strong>Current City:</strong> {{user.profile.location}}<p>
<p><strong>Occupation/Job:</strong> {{user.profile.occupation}}<p><br>
<hr>
<button type="button" class="btn btn-outline-success btn-md">View CV</button>
</div>
</div>
</div>
</div>
{% endblock content %}
{% block footer %}
{% endblock footer %}
I don't know What is causing this strange behaviour!!
Actually, you are mixing up with request.user and your user object for resume. You should change the context variable name from user to something else. for example:
class Get_Profile(DetailView):
"fetches user's profile"
def get(self, request, pk):
user = MyModel.objects.get(pk=pk)
return render(request, 'profile/profile.html', {'profile':user}) # <-- Here
You've used the same variable name, user, for the user whose profile you are viewing as for the one who is actually using the site. You need to pick another name.
(Also, unrelated, but you don't need to - and shouldn't - define the get method in your detail view.)

Display Image in Django

I've been unable to make this work although I realise there are similar questions. Hoping someone can point me in the right direction.
I have a django app which allows uploads of images with it. Right now my model looks like this.
The image is not displaying for some reason when it is called from the code. The reasons I can imagine are in the view.py file, or how I am calling it in the template file.
Appreciate your help in advance,
MODELS
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
image = models.ImageField(blank=True, null=True, upload_to="locations/%Y/%m/%D")
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
VIEWS
def index(request):
# Query the databse for a list of ALL categories currently stored.
# Order the categories by no likes in descending order .
# Retrieve the top 5 only - or all if less than 5.
# Place the list in context_dict dictionary
# that will be passed to the template engine.
category_list = Category.objects.order_by('-likes')[:5]
page_list = Page.objects.order_by('-views')[:5]
context_dict = {'categories': category_list, 'pages': page_list}
# Render the response and send it back!
return render(request, 'Spaces/index.html', context_dict)
def show_category(request, category_name_slug):
# Create a context dictionary which we can pass
# to the template rendering engine.
context_dict = {}
try:
# Can we find a category name slug with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
# So the .get() method returns one model instance or raises an exception.
category = Category.objects.get(slug=category_name_slug)
# Retrieve all of the associated pages.
# Note that filter() returns a list of page objects or an empty list
pages = Page.objects.filter(category=category)
# Adds our results list to the template context under name pages.
context_dict['pages'] = pages
# We also add the category object from
# the database to the context dictionary.
# We'll use this in the template to verify that the category exists.
context_dict['category'] = category
# We get here if we didn't find the specified category.
# Don't do anything -
# the template will display the "no category" message for us.
except Category.DoesNotExist:
context_dict['category'] = None
context_dict['pages'] = None
# Go render the response and return it to the client.
return render(request, 'Spaces/category.html', context_dict)
TEMPLATES
{% load staticfiles %}
{% load i18n %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Side Spacer</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<link href="style.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-md navbar-light bg-light sticky-top">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img src="#"></a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active"><a class="nav-link" href="#">Home</a></li>
<li class="nav-item"><a class="nav-link" href="#">Spaces</a></li>
<li class="nav-item"><a class="nav-link" href="/Spaces/about/">How it works</a></li>
<li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>
{% if user.is_authenticated %}
<li class="nav-item"><a class="nav-link" href="{% url 'logout' %}">Log out {{user.username}}</a></li>
{% else %}
<li class="nav-item"><a class="nav-link" href="{% url 'signup' %}">Sign Up</a></li>
<li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Login</a></li>
{% endif %}
</ul>
</div>
</div>
</nav>
<!--- Image Slider -->
<div id="slides" class="carousel slide" data-ride="carousel">
<ul class="carousel-indicators">
<li data-target="#slides" data-slide-to="0"class="active"></li>
</ul>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="carousel-caption">
<h3 class="display-2">Need a workspace on the go?</h3>
<h3>Great locations and flexible pricing!</h3>
<button type="button" class="btn btn-outline-light btn-lg" href="{% url 'signup' %}">Join Now!</button>
</div>
</div>
</div>
</div>
<!--- Jumbotron -->
<hr class="my-4">
<div class="container-fluid">
<div class="row jumbotron">
<div class="col-xs-12 col-sm-12 col-md-9 col-lg-9 col-xl-10">
<p class="lead">For mobile professionals, startups, and business that need the extra deskpace!<br> Productive workspaces are available to help you get things done!<br> Our plans start at $99/month! </p>
</div>
<div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-2">
<button type="button" class="btn btn-outline-secondary btn-lg">Our Services</button>
</div>
</div>
</div>
<div class="container">
<!-- Example row of columns -->
<div class ="row">
<div class ="col">
<h2>Most Viewed Spaces</h2>
{% if categories %}
<ul>
{% for category in categories %}
<li>
{% if item != None %}
<img src="{% get_media_prefix %}{{ category.image }}" width="500px" />
{% endif %}
{{ category.name }}
</li>
{% endfor %}
</ul>
{% else %}
<strong>There are no Spaces present.</strong>
{% endif %}
</div>
<div class ="col">
<h2>Most Viewed Events</h2>
<p>
{% if pages %}
<ul>
{% for page in pages %}
<li>{{ page.title }}</span></li>
{% endfor %}
</ul>
{% else %}
<strong>There are no Events present.</strong>
{% endif %}
</p>
</div>
<div>
{% if user.is_authenticated %}
<div>
<p><a class="btn btn-success" href="/Spaces/add_category/" role="button">Add New Space »</a></p>
<p><a class="btn btn-success" href="/Spaces/add_page/" role="button">Create New Event »</a></p>
</div>
{% endif %}
</div> <!-- /container -->
<hr>
<div class="container-fluid padding">
<div class="row text-center">
<div class="col-md-4">
<hr class="light">
<img src="#">
<hr class="light">
<p>555-555-55555</p>
<p>email#someonesmail.com</p>
<p>100 Street name</p>
<p>City, State, 0000</p>
</div>
<div class="col-md-4">
<hr class="light">
<h5>Our hours</h5>
<hr class="light">
<p>Monday: 9AM - 5PM</p>
<p>Saturday: 10AM - 4PM</p>
<p>Sunday: Closed</p>
</div>
<div class="col-md-4">
<hr class="light">
<h5>Service Area</h5>
<hr class="light">
<p>City, State, 0000</p>
<p>City, State, 0000</p>
<p>City, State, 0000</p>
</div>
<div class="col-12">
<hr class="light">
<h5>© nameofthebusiness </h5>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
<script src="../../assets/js/vendor/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
You have to add get_media_prefix before the image. I use {{ category.image.url }} to serve media from AWS S3, but I think here you would just use {{ category.image }}. Play with it a little bit and see.
<img src="{% get_media_prefix %}{{ category.image }}" width="500px" />
You should give proper path for the image. for me below code works properly.
in settings:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
to display image
<img src="/media/{{category.image}}" width="500px" />
Found the problem.
{% if item != None %}
<img src="{% get_media_prefix %}{{ category.image }}" width="500px" />
{% endif %}
Changed too
{% if category.image %}
<img src="{{ category.image.url }}" />
{% endif %}
Problem solved