I am unable to access the user context data for my view in the associated template file.
views.py
def userprofile(request,username):
user=User.objects.filter(username=username)
if user:
user=user[0]
profile=Profile.objects.get(user=user)
post=getPost(user)
bio=profile.bio
conn=profile.connection
follower=profile.follower
following=profile.following
user_img=profile.userImage
print(user)
print(bio)
print(conn)
print(follower)
print(following)
print(user_img)
print(user)
data={
'user':user,
'bio':bio,
'conn':conn,
'follower':follower,
'following':following,
'userImg':user_img,
'posts':post
}
print(data)
return render(request,'userview/userProfile.html')
else:
return HttpResponse(" 404 No Such User exist")
My data is printed in the console after runserver, so can you tell me why it is not accessible in the template file below.
profile.html
{% extends 'base.html' %}
{% block title %}profile{% endblock title %}
<style>
.pst{
width: 350px;
height: 200px;
margin-bottom: 30px;
}
</style>
{% block body %}
<div class="container my-4">
<div class="media">
<img src="{{userImg.url}}"class="align-self-start mr-3 userImage" alt=".......">
<div class="media-body-info">
<h4 class="mt-4" >{{user.get_username}}</h4>
<p>Follower : {{follower}} Following : {{followin}} </p>
<p><b>{{bio}}</b></p>
</div>
</div>
<hr>
<!-- <h3> Username:{{user.get_username}}</h3>
<h3> FirstName:{{user.first_name}}</h3>
<h3> lastname:{{user.last_name}}</h3>
<h3> Email:{{user.email}}</h3> -->
<!-- <h3> country:{{user.country}}</h3> sss -->
<div class="row">
{% for i in posts %}
{% for j in i %}
<div class="col-md--4 ">
<img src="{{j.image.url}}" alt="" class="pst">
</div>
{% endfor %}
{% endfor %}
</div>
</div>
{% endblock body %}
You are not passing the context data to your template. You need to change your render call to return render(request,'userview/userProfile.html', data).
Also, make sure the path to your template file is correct.
I would take a look at Django Getting Started guide as your code could generally be tidied up a bit.
Related
I have made filters using django-filters. As a result I get a dropdown menu. Is it possible to add an autocomplete/search field to this dropdown?
I have already tried to add the Select2Widget widget as indicated in another post, but the only thing that changes is that it adds an empty field before the dotted line. But it won't let me write anything.
Maybe something is missing in the template???
Stackoverflow don't let me add images yet so I share the code I have.
filters.py
import django_filters
from django_select2.forms import Select2Widget
from .models import Consumo, Cliente
AÑO_CHOICES = (('2021', '2021'), ('2022', '2022'),)
class ConsumoFilter(django_filters.FilterSet):
año = django_filters.ChoiceFilter(choices=AÑO_CHOICES, label='Año', widget=Select2Widget(attrs={'style':'width: 20ch', 'class':'form-select form-select-sm'}))
name = django_filters.ModelChoiceFilter(queryset=Cliente.objects.all(), label='Clientes', widget=Select2Widget(attrs={'style':'width: 85ch','class': 'form-select form-select-sm'}))
class Meta:
model = Consumo
fields = ['name', 'año']
template
{% extends 'clientes/base.html' %}
{% load static %}
{% block title %}Title{% endblock %}
{% block head %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js" integrity="sha512-2ImtlRlf2VVmiGZsjm9bEyhjGW4dU7B6TNwh/hx/iSByxNENtj3WVE6o/9Lj4TJeVXPi4bnOIMXFIJJAeufa0A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" integrity="sha512-nMNlpuaDPrqlEls3IX/Q56H36qvBASwb3ipuo3MxeWbsQB1881ox0cRv7UPTgBlriqoynt35KjEwgGUeUXIPnw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
{% endblock %}
{% block content %}
<div class="card" style="margin-top: 20px; margin-bottom: 20px;">
<div class="card-body">
<h4 class="card-title">Consumos</h4>
<h6 class="card-subtitle mb-2 text-muted">Consumos por cliente</h6>
<hr>
<div class="container">
<div class="row">
<div class="col-lg-12">
<form method="get">
{{ consumo_filter.form }}
<br>
<button type="submit" class="btn btn-sm btn-primary">Buscar</button>
</form>
<hr>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block javascript %}
{% endblock %}
Ok, I found out.
You need to add a id="" attribute to attrs=
name = django_filters.ModelChoiceFilter(queryset=Cliente.objects.all(), label='Clientes', widget=Select2Widget(attrs={'style':'width: 85ch', 'id':'name', 'class': 'form-select'}))
Then in your template you call it with the Select2 JS code:
{% block javascript %}
<script>
$(document).ready(function() {
$('#name').select2();
});
</script>
{% endblock %}
My name is arslan chaudhry, currently i am working with django. In my django project i have made some filters to filter the product category wise.i have successfully display the category of products. But when i click on the category image i recived an empity page no error is dispalyed.
I think data are not passing from view.py to html template.How i can fix this?
the code is given below.
views.py
def collectionsview(request, slug):
if(Category.objects.filter(slug=slug, status=0)):
products=Product.objects.filter(category__slug=slug)
category_name=Category.objects.filter(slug=slug).first()
contex={products:"products",category_name:"category_name"}
print(products)
return render(request, "store/product/index.html", contex)
else:
return HttpResponse('This is not a valid product')
html template
{% extends 'store/layouts/main.html' %}
{% block title %}Home{% endblock title %}
{% block body %}
<div class="container mt-3">
<div class="row">
<div class="col-md-12">
<h4>{{category_name}}</h4>
<div class="row">
{% for item in products %}
<div class="col-md-2">
<div class="card">
<a href="#">
<div class="card-body ">
<div class="card-image">
<img src="{{item.imge.url}}" alt="" width="100%" height="100%">
<h4 class="text-center mt-1" style="font-size: medium; font-weight: 600;">{{item.name}}</h4>
</div>
<span>{{item.original_price}}</span>
<span>{{item.selling_price}}</span>
</div>
</a>
</div>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
{% endblock body %}
I am having trouble with sending flashed messages to a route that extends its layout from another template. This message shows up just fine if use the message in the layout.html which makes me believe that rendering login.html first will render layout.html and use the flashed message there and not pass it to my /login route. How are you able to call this message in an extended template? I am using the jijna with syntax taken from here to be able to have the message variable available within my mainblock. Flask's documentation does not specify this either.
app.py
#app.route("/login", methods=["POST", "GET"])
def login():
# Forget any previous user
if session.get("user_id"):
session.pop("user_id")
if request.method == "POST":
# Create connection cursor
cursor = mysql.connection.cursor()
# Query database for email
cursor.execute("SELECT id, email, password FROM users WHERE email = %s", [request.form.get("email")])
row = cursor.fetchone()
print(row)
if row is None:
print("WHY")
flash("Invaid user")
return redirect("login")
My layout.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hoook - {% block title %}{% endblock %}</title>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, width=device-width">
<link href="/static/favicon-16x16.png" rel="icon">
<link href="/static/style.css" rel="stylesheet">
<!-- Scripts -->
<script src="https://kit.fontawesome.com/542c2d099e.js" crossorigin="anonymous"></script>
<script src="/static/mainJS.js"></script>
</head>
<body>
<div class="page-wrapper">
<header>
<nav class="main-navbar">
{% if request.path == "/login" %}
<div class="navbar-container login-container">
{% else %}
<div class="navbar-container">
{% endif %}
<div>
{% if request.path == "/login" %}
<img src="/static/hoook_logo_blue.png" alt="Hoook Logo" height="50" width="150">
{% else %}
<img src="/static/hoook_logo.png" alt="Hoook Logo" height="50" width="150">
{% endif %}
</div>
{% if request.path != "/login" %}
<div>
{% if session["user_id"] %}
{# change nav bar for logged in users #}
{% else %}
{# work on this nav bar for unlogged in users #}
{% if request.path == "/signup" %}
<a class="navbar-link" href="/login">Sign in</a>
{% endif %}
{% endif %}
</div>
{% endif %}
</div>
</nav>
</header>
</div>
<main>
{% if request.path == "/login" %}
<div class="top-container signup-container">
{% else %}
<div class="top-container">
{% endif %}
{% with messages = get_flashed_messages() %}
{% block main %}{% endblock %}
{% endwith %}
</div>
</main>
<footer>
</footer>
</body>
</html>
My login.html
{% extends "layout.html" %}
{% block title %}
Login
{% endblock %}
{% block main %}
<div class="login-div">
<div>
<h1 class="color-control">Sign in to Hoook</h1>
</div>
<div class="login-input-bx">
<form action="/login" method="post" autocomplete="off">
<div class="form-control login-form-control">
<label class="login-label color-control" for="email">Email address</label>
<input class="login-input" type="text" name="email" id="email" required autofocus>
</div>
<div class="form-control login-form-control">
<label class="login-label color-control" for="password">Password</label>
<input class="login-input" type="password" name="password" id="password" required readonly onfocus="this.removeAttribute('readonly')">
</div>
<button class="btn btn-login" type="submit">Sign in</button>
</form>
</div>
{% if messages %}
{% for msg in messages %}
<div class="flashed-messages-div">
<p class="signup-para" id="login-flashed-messages">Error: {{ msg }}</p>
</div>
{% endfor %}
{% endif %}
<div class="signup-link-div">
<p class="color-control signup-login-font">New to Hoook? <a class="signup-link-anchor" href="/signup">Create an account</a>.</p>
</div>
</div>
{% endblock %}
Update
I guess I could do something like make_response instead as seen here. and just use:
response = make_response(render_template("login.html", message = "Invalid user"), 302)
return response
However I am curious if there is a way to pass the flashed message through instead.
I have had the same issue. Instead of:
return redirect("login")
try with:
return render_template("login.html")
The flashed message works that way for me.
Why is it giving me this strange error: Did you forget to register or load this tag? it was working fine but when i did some changes in this code it started this error... i was going through question related to this issue but could not find the solution....
<div class="container">
<div class="row">
<div class="pagination">
{% for item in post.object_list %}
<!-- {% for item in post %}-->
<div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;">
<img src="/media/{{item.thumbnail}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{item.title}}</h5>
<p class="card-text">{{item.intro}}</p>
<!-- href={% url 'bicep' %}-->
read more...
<!-- read more...-->
</div>
</div>
{% if forloop.counter|divisibleby:4 %}
</div>
{% endif %}
{% endfor %}
Django disregards HTML comments. That means django will run this code:
<!-- {% for item in post %}-->
This is what's causing the error because django is expecting an endfor closing tag for this loop.
Either remove this line from your code or use django's comment template tag to comment out the template related code:
{% comment %}
{% for item in post %}
{% endcomment %}
I'm trying to set up Django Pagination in Django 1.3, It doesn't seem to be working, as I have over 5 records returned and the links are messed up
View:
def directory(request, bought_in_control_panel_id):
listings = Directory.objects.all().exclude(visible=False).order_by('rank', 'company__name').filter(company__uuid__in=local_uuids)
paginator = Paginator(listings, 5) # Show 25 contacts per page
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
page_listings = paginator.page(page)
except (EmptyPage, InvalidPage):
page_listings = paginator.page(paginator.num_pages)
return share.output_page(request, 'directory/directory.html', {'listings': page_listings, 'bought_in_control_panel_id': bought_in_control_panel_id})
Template:
{% block main %}
<link href="/media/css/bootstrap.min.css" rel="stylesheet">
<div class="container-fluid">
<div class="dbx-group">
<div class="dbx-box">
<h3 class="dbx-handle"><div class="tools"></div> <img src="/media/img/32x32/addressbook.png" style="position:absolute; margin-top:-16px;"><div class="title">Online Suppliers listings {% jms_help_link user 'directory_listings' %}</div></h3>
<h3 class="dbx-handle"><div class="tools"></div> <a title="Change region" href="{% url change_flag bought_in_control_panel_id iso %}"><img src="/media/img/flags-iso/48/{{ iso|lower }}.png" alt="Change region" align="right" style="margin-top:-45px;"></a><div class="title"></div></h3>
<ul class="dbx-content" width=98%>
{% if listings %}
{% for listing in listings %}
{% if listing.visible %}
<div class="well well-small" onclick="window.location.href = '{% url view_directory listing.uuid bought_in_control_panel_id %}'" style="cursor:pointer;">
<div class="row-fluid">
<div class="span12">
<a style="display:block" href="{% url view_directory listing.uuid bought_in_control_panel_id %}">
<h4>{{ listing.company.name }}</h4>
</a>
<div class="row-fluid">
<div class="span10">
<blockquote>{{listing.description|truncatewords:30}}</blockquote>
<p>Click for more info and downloads</p>
</div>
<div class="span2">
<img src="{% url view_banner listing.uuid %}" alt="">
</div>
</div>
</div>
</div>
</div>
{% endif %}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if listings.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ listings.number }} of {{ listings.paginator.num_pages }}.
</span>
{% if listings.has_next %}
next
{% endif %}
</span>
</div>
{% else %}
<p align="center"><b>No listings!</b></p>
{% endif %}
<div style="clear:both;"></div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/media/js/bootstrap.min.js"></script>
{% endblock %}
share.output_page:
def output_page(request, htmlpage, dct={}):
t = loader.get_template(htmlpage)
c = RequestContext(request,dct)
return http.HttpResponse(t.render(c))
In Django 1.3 you need to use:
{% for listing in listings.object_list %}
It's changed in Django 1.4.