Passing dictionary index as variable to url in Django template - django

I am trying to pass a string stored in a dictionary to url to be used as a variable. I want it to be passed to the function the url is pointing to. I tried putting it in {{ post.username }} but it won't accept it. Currently, I have it in quotes as "post.username" but it accepts is as the literal string and not the string stored in the dictionary. Any help would be appreciated.
Template
{% for post in posts %}
<div class="row">
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<div class="card" style="width: 40rem;">
<div class="card-header bg-white">
{{ post.user_name }}
<div class="text-black-50 mt-2">{{ post.created_date }} ago</div>
</div>
<img class="card-img-top" src="{{ post.picture }}" alt="Post Image" style="width: 100%; height: 30vw; object-fit: cover">
<div class="card-body">
<p class="card-text">{{ post.description }}</p>
Comments | {{ post.comments }}
</div>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
URL
path('user_view/<account_id>', views.user_view, name='user_view')
I tried path('user_view/<str:account_id>' but no luck
View
def user_view(request, account_id):
user = User.objects.get(username=account_id)
user_prop = UserProperty.objects.get(user_id=user)
account_info = [user_prop.profile_photo, account_id, user_prop.bio]
print(account_info)
return render(request, 'users/user_view.html', {'account_info': account_info})
When I click on the anchor on the website, it gives me this address : http://localhost:8000/user_view/post.username

try:
<img class="rounded-circle" src="{{ post.user_image }}" style="width:30px; height: 30px;"> {{ post.user_name }}
In your urls:
path('user_view/<str:account_id>/'

Related

Dictionary not passing to the template django

I'm trying to read a cookie and pass the data into the template but it returns a string /cart on the template.
view.py
def cart(request):
# exception no cookie named 'cart'
try:
cart = json.loads(request.COOKIES['cart'])
except:
cart = {}
context = {
'data': [],
'cart': cart,
}
for item in cart:
product_detail = ProductImage.objects.select_related(
'product'
).filter(product=item[0], place='Main Product Image')
context['data'].append(product_detail)
return render(request, 'store/cart.html', context)
I've checked whether the cart variable contains data and it does contain a dictionary. Following is the context variable,
{'data': [<QuerySet [<ProductImage: Product 1-22>]>], 'cart': {'1': {'unit_price': '980.00', 'quantity': 3}}}
when I tried to print the cart in the template using {{ cart }} it returns /cart but the data key contains all the data and can be displayed in the template.
template
{{ cart }} <!-- for testing -->
{% for item in data %}
{% if forloop.counter|divisibleby:2 %}
<div class="row border-bottom pb-3 pt-1 cart-item">
{% else %}
<div class="row border-bottom pb-3 pt-1 cart-item" style="background-color: #F8F8F8">
{% endif %}
<div class="col-sm-1 d-md-flex justify-content-center align-items-center remove-btn">
<button type="button" class="btn bg-transparent"
data-action="delete" data-product="{{ item.0.product.id }}_{{ item.0.product.get_sale_price|floatformat:2 }}">
<i class="fa fa-trash" aria-hidden="true"></i>
</button>
</div>
<div class="col-sm">
<img class="img-fluid img-thumbnail" src="{{ item.0.image.url }}" alt="" />
</div>
<div class="col-sm">
<a href="product/{{ item.0.product.id }}" class="cart-product-link">
<h5> {{ item.0.product.name }}</h5>
<p class="module fades">
{{ item.0.product.desc }}
</p>
</a>
</div>
<!-- quantity -->
<div class="col col-sm input-group my-auto text-center">
<div class="quantity ml-5">
<input type="number" class="update-quantity" data-action="q_add" min="1" max="20" step="1"
value="{{ cart|get_quantity:item.0.product.id }}" style="width: 50px"
data-product="{{ item.0.product.id }}_{{ item.0.product.get_sale_price|floatformat:2 }}">
</div>
</div>
<!-- cost -->
<div class="col col-sm mt-lg-5 text-center cost-container">
<span class="cost">{{ cart|get_cost:item.0.product.id }}</span>
</div>
</div>
{% endfor %}
So hoping to know what's going on here thanks in advance.
Update(wierd scenario)
The same thing happened again in a different file and I tried to do the solution bellow mentioned. Unfortunately, it didn't work. After hours of trying, I decided to rename the key of the dict {'cart': cart,...} to {'crt':cart} and it worked.
If you want to pass a context dict variable in the template. All you need to do is :
return render(request, 'store/cart.html', {'context' : context})
By this we are passing the context to html template. And the you can retrieve the context data by :
{{context.cart}}

Django - NoReverseMatch at /project/3/evillio

I'm working on a portfolio project and i face a strange problem when trying to list a project, ( class-based-views-DetailView). More specifically when trying to list a project for example /project/3/evillio i got following error Reverse for 'project-detail' with arguments '('', '')' not found. 1 pattern(s) tried: ['project/(?P<pk>[0-9]+)/(?P<slug>[-a-zA-Z0-9_]+)$'] but when i add a new project, i'm able to list /project/3/evillio with no problem, however i got the same error on the next project /project/4/urban.
For example i add 2 projects in project table (using Postgres) then going to list details of each project. Click on project1 and works fine. Then click on project 2 and i got error above. Then i add a third project in project table and going to list details of each project. Click on project1 works fine, click on project2 works fine, click on project3 and i got the same error as on project2 before adding project3.
I hope is more clear.
urls.py
path('project/<int:pk>/<slug:slug>', WorkProjectsDetailView.as_view(), name='project-detail'),
views.py
class IndexView(ListView):
model = Project
template_name = 'pages/index.html'
context_object_name = 'projects'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['slider_projects'] =
Project.objects.all().filter(slider_project=True)
return context
class WorkProjectsView(ListView):
model = Project
template_name = 'work/work.html'
queryset = Project.objects.all()
context_object_name = 'projects'
ordering = ['-date_created']
def get_context_data(self, *, object_list=None, **kwargs):
context = super(WorkProjectsView, self).get_context_data(**kwargs)
context['categories'] = Category.objects.all()
return context
class WorkProjectsDetailView(DetailView):
model = Project
template_name = 'work/project-detail.html'
context_object_name = 'single_project'
def get_context_data(self, **kwargs):
context = super(WorkProjectsDetailView, self).get_context_data(**kwargs)
context['next'] = Project.objects.filter(id__gt=self.kwargs['pk']).order_by('pk').first()
return context
work.html
<div class="projects-list gallery">
{% if projects %}
{% for project in projects %}
<div class="item brand">
<a href="{% url 'project-detail' pk=project.pk slug=project.slug %}" class="effect-ajax" data-dsn-ajax="work"
data-dsn-grid="move-up">
<img class="has-top-bottom" src="{{ project.featured_image.url }}" alt="" />
<div class="item-border"></div>
<div class="item-info">
<h5 class="cat">{{ project.category }}</h5>
<h4>{{ project.title }}</h4>
<span><span>View Project</span></span>
</div>
</a>
</div>
{% endfor %}
{% else %}
<div class="col-lg-8">
<p>No Projects Available</p>
</div>
{% endif %}
</div>
index.html
{% for project in slider_projects %}
<div class="work-item slick-slide">
<img class="has-top-bottom" src="{{ project.featured_image.url }}" alt="">
<div class="item-border"></div>
<div class="item-info">
<a href="{% url 'project-detail' pk=project.pk slug=project.slug %}" data-dsn-grid="move-up" class="effect-ajax">
<h5 class="cat">{{ project.category}}</h5>
<h4>{{ project.title }}</h4>
<span><span>View Project</span></span>
</a>
</div>
</div>
{% endfor %}
project-detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<main class="main-root">
<div id="dsn-scrollbar">
<header>
<div class="headefr-fexid" data-dsn-header="project">
<div class="bg w-100" id="dsn-hero-parallax-img" data-dsn-ajax="img">
<div class="bg-image cover-bg" data-overlay="4"
data-image-src="{{ single_project.hero_image.url }}"></div>
</div>
<div class="scroll" data-dsn-animate="ajax">
<span class="background"></span>
<span class="triangle"></span>
</div>
<div class="project-title" id="dsn-hero-parallax-title" style="margin-top: 100px;">
<div class="title-text-header">
<div class="cat">
<span>{{ single_project.category}}</span>
</div>
<span class="title-text-header-inner">
<span data-dsn-animate="ajax">{{ single_project.title }}</span>
</span>
</div>
<div class="sub-text-header" data-dsn-animate="ajax">
<h5>Published</h5>
<span>- {{ single_project.date_created }}</span>
</div>
</div>
<div class="project-page__inner">
<div class="h-100">
<div class="row justify-content-center align-items-end h-100">
<div id="descover-holder" class="col-lg-12 project-meta__content">
<div class="link">
<a target="_blank"
href="https://www.behance.net/gallery/57437111/Under-Armour-Cal?tracking_source=search%7CPhotography">View
Website</a>
</div>
</div>
</div>
</div>
</div>
</div>
</header>
<div class="wrapper">
<div class="root-project">
<div class="container intro-project section-margin">
<div class="intro-text">
<div class="title-cover" data-dsn-grid="move-section" data-dsn-opacity="0.1"
data-dsn-duration="170%" data-dsn-move="0%">
Nile
</div>
<div class="inner">
<h2 data-dsn-animate="text">A whole new brand</h2>
<p data-dsn-animate="up">Striking and powerful Aston Martin Vantage captivates you at
the first sight. We couldn’t resist the temptation to create a series of beautiful
images for this car.</p>
<a class="bottom-link" data-dsn-animate="up"
href="https://www.behance.net/gallery/66646747/Nile" target="_blank">
<span></span>
<span></span>
<div class="content">
<div class="inner">
<p>VISIT SITE</p>
</div>
</div>
</a>
</div>
</div>
</div>
<div class="container section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up">
<img src="{{ single_project.photo_1.url }}" alt="">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>
<div class="container-fluid section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up" data-dsn-triggerhook="0">
<img src="{{ single_project.photo_2.url }}" alt="" data-dsn-y="30%" data-dsn-scale="1.08">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>
<div class="container intro-project section-p section-margin">
<div class="intro-text text-center">
<div class="title-cover" data-dsn-grid="move-section" data-dsn-opacity="0.1"
data-dsn-duration="170%" data-dsn-move="0%">
Nile
</div>
<div class="inner">
<h2 data-dsn-animate="text">
The Brief team has been sincerely committed to
designing great communication around our projects. Our customers love
their
creative work - and so do we!
</h2>
</div>
</div>
</div>
<!--Video-->
<div class=" " data-dsn="video" data-overlay="4" data-dsn-ajax="img">
<video class="image-bg cover-bg dsn-video" controls loop muted>
<source src="{{ single_project.video.url }}" type="video/mp4">
</video>
</div>
<!--<div class="container section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up">
<img src="{{ single_project.photo_3.url }}" alt="">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>-->
<div class="container-fluid section-margin">
<div class="img-box-small dsn-parallax-full" data-dsn-grid="move-up" data-dsn-triggerhook="0">
<img src="{{ single_project.photo_4.url }}" alt="" data-dsn-y="30%" data-dsn-scale="1.08">
<div class="cap">
<span>Web Design</span>
</div>
</div>
</div>
</div>
<div class="next-project" data-dsn-footer="project">
<div id="dsn-next-parallax-img" class="bg">
<div class="bg-image cover-bg" data-overlay="2"
data-image-src="{{ next.featured_image.url }}"></div>
</div>
<div id="dsn-next-parallax-title" class="project-title">
<a href="{% url 'project-detail' next.pk next.slug %}" class="effect-ajax" data-dsn-ajax="next-project">
<div class="title-text-header">
<div class="title-text-header-inner">
<span>{{ next.title }}</span>
</div>
</div>
<div class="sub-text-header">
<h5>Next Project</h5>
</div>
</a>
</div>
</div>
Any help appreciated.
The error you're receiving is because of this line toward the bottom of project-detail.html:
<a href="{% url 'project-detail' next.pk next.slug %}" class="effect-ajax" data-dsn-ajax="next-project">
if there is no next (context["next"]), then django can't figure out the url, and you get the error you're seeing.
Wrap the last segment for the link to "next" with {% if next %}:
{% if next %}
<div class="next-project" data-dsn-footer="project">
<div id="dsn-next-parallax-img" class="bg">
<div class="bg-image cover-bg" data-overlay="2"
data-image-src="{{ next.featured_image.url }}"></div>
</div>
<div id="dsn-next-parallax-title" class="project-title">
<a href="{% url 'project-detail' next.pk next.slug %}" class="effect-ajax" data-dsn-ajax="next-project">
<div class="title-text-header">
<div class="title-text-header-inner">
<span>{{ next.title }}</span>
</div>
</div>
<div class="sub-text-header">
<h5>Next Project</h5>
</div>
</a>
</div>
</div>
{% endif %}

Django - How to apply onlivechange on CharField / IntegerField

I want to hide the field form.name_of_parent_if_minor if the age (CharField) < 18 else show. I am not getting where to write jQuery or JS code or add separate js file. For this do I need to the html definition and add tag for age (CharField) or we can perform action on this as well.
I am new to the Django so if you find any mistakes in my code then any help would be appreciated for guidance.
forms.py
class StudentDetailsForm(forms.ModelForm):
class Meta:
model = StudentDetails
views.py
class StudentCreateView(LoginRequiredMixin, CreateView):
template_name = 'student/student_details_form.html'
model = StudentDetails
form_class = StudentDetailsForm
success_url = "/"
html
{% extends 'student/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div id="idParentAccordian" class="content-section">
<form method="POST">
{% csrf_token %}
<div class="card mt-3">
<div class="card-header">
<a class="collapsed card-link" style="display: block;" data-toggle="collapse"
href="#idPersonalInformation">Personal Information</a>
</div>
<div id="idPersonalInformation" class="collapse show" data-parent="#idParentAccordian">
<div class="card-body">
<div class="row">
<div class="col-6">
{{ form.joining_date|as_crispy_field }}
</div>
<div class="col-6">
{{ form.class|as_crispy_field }}
</div>
</div>
{{ form.student_name|as_crispy_field }}
{{ form.father_name|as_crispy_field }}
{{ form.mother_name|as_crispy_field }}
{{ form.gender|as_crispy_field }}
<div class="row">
<div class="col-6">
{{ form.date_of_birth|as_crispy_field }}
</div>
<div class="col-6">
{{ form.age|as_crispy_field }}
</div>
</div>
<div>
{{ form.name_of_parent_if_minor|as_crispy_field }}
</div>
</div>
</div>
</div>
<div class="form-group mt-3">
<button class="btn btn-outline-info" type="submit">Save</button>
<a class="btn btn-outline-secondary" href="javascript:history.go(-1)">Cancel</a>
</div>
</form>
</div>
{% endblock content %}
the easiest way but not the cleanest is to add JS script in your html
the recommanded way is to add static folder to your app and load static files in your html template using {% load static %}

django slice filter breaks template for tinymce safe content

I have contents which were published using tinymce editor. Now, I want to show my content, that's why I have to use safe filter. But, whenever I'm trying to use slice or truncate filter, the template breaks.
this is my HTML code.
{% extends 'blog/frontend/layouts/base.html' %}
{% block content %}
<div class="card border-primary">
{% for post in posts %}
<div class="card my-2 mx-1">
<div class="card-body">
<h5 class="card-title">{{ post.title }}</h5>
<hr>
<img src="{{ post.image.url }}" alt="Card image" width="85%" class="mx-auto d-block">
<p class="card-text mt-1">
{{ post.content|truncatewords:50|safe}}
</p>
<hr>
<div class="d-flex">
<div class="px-2 py-0 my-auto">
<h6><i class="fas fa-user-edit"></i> {{ post.author.username }}</h6>
</div>
<div class="px-2 py-0 my-auto">
<h6>Date posted: <span class="text-info">{{ post.date_posted|date:"d M, Y" }}</span></h6>
</div>
<div class="ml-auto px-2 my-auto ">
Read more
</div>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
These are the image, first one without sliceor turncate filter, 2nd and 3rd one are with them.
Sorry, it was a stupid question to ask. Just in case anyone else is facing this kind of problem, use truncatechars_html or truncatewords_html just like this: {{ post.content|truncatewords_html:30|safe }} or {{ post.content|truncatechars_html:30|safe }}

How to Shuffle Posts from Entire Database in Django?

The views.py file has the following code:
def index(request):
post = Product.objects.all()
context = {
"post":post
}
return render(request, "index.html", context)
And my template has the following code:
<div class="features_items"><!--products --- features_items-->
<h2 class="title text-center">Your Product Feed</h2>
{% for p in post|slice:":50" %}
<div class="col-sm-4", id="items">
<div class="product-image-wrapper">
<div class="single-products">
<div class="productinfo text-center shadow p-3 mb-5 bg-white rounded" style="
border-style: solid;
border-width:0.1px;
color: #E0E0E0;">
<img src="{{ p.product_image }}" alt="" />
<h6 style="color: #666663"> {{ p.product_price }} ৳ </h6>
<p>{{ p.product_name|truncatewords:5 }}</p>
<span class="glyphicon glyphicon-heart-empty"></span> Like
<span class="glyphicon glyphicon-eye-open"></span> Detail
</div>
</div>
<div class="choose">
<ul class="nav nav-pills nav-justified">
{# <li><span class="glyphicon glyphicon-heart"></span> Like</li>#}
{# <li><span class="glyphicon glyphicon-thumbs-down"></span> Unlike</li>#}
</ul>
</div>
</div>
</div>
{% endfor %}
</div>
I want to show products coming from database are random (shuffled), not ordered by their ID. What change should I bring to my code?
Simply do this:
post = Product.objects.all().order_by("?")