How to Shuffle Posts from Entire Database in Django? - 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("?")

Related

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

is there is a solution for urls issues

I am building a web app using django and I get an error, I couldn't figure out what is the problem behind it.
I have three models( Category, SubCategory, Article) in my url I want something like that (localhost:8000/categories/Id_category/Id_subcategory)
the url (localhost:8000/categories/Id_category) worked perfectly but (localhost:8000/categories/Id_category/Id_subcategory) didn't work I get this error enter image description here
So here is my code that I tried to make it:
#views.py
def categorie(request):
Catégorie_list=Catégorie.objects.all()
context = {
'Catégorie_list':Catégorie_list,
}
return render(request,'articles/Category.html',context)
def souscategorie(request,categoryID):
SousCatégorie_list=SousCatégorie.objects.order_by('désignation').filter(Catégorie_identifiant_id=categoryID)
name_category=Catégorie.objects.get(id=categoryID)
articles=Article.objects.select_related('Sous_Catégorie__Catégorie_identifiant').filter(Sous_Catégorie__Catégorie_identifiant_id=categoryID)
context = {
'SousCatégorie_list':SousCatégorie_list,
'name_category': name_category,
'articles':articles
}
return render(request,'articles/SubCategory.html',context)
def articl(request,categoryID,articleID):
return render(request,'articles/article.html')
#articles/urls.py
urlpatterns=[
path('',views.categorie, name='Category'),
path('<int:categoryID>/',views.souscategorie, name='SubCategory'),
path('<int:categoryID>/<int:articleID>/',views.articl, name='article'),
path('search',views.search, name='search'),
]
#my template Category.html
{% if Catégorie_list %}
{% for category in Catégorie_list %}
<div class="col-md-6 col-lg-4 mb-4">
<div class="card listing-preview">
<a href="{% url 'SubCategory' category.id %}">
<img class="card-img-top" src="{{ category.photo_main.url }}" alt="{{ category.désignation }}"> </a>
<div class="card-body">
<div class="listing-heading text-center">
<a href="{% url 'SubCategory' category.id %}" style="text-decoration: none;">
<h4 class="text-primary" >{{ category.désignation }}</h4>
</a>
</div>
<hr>
<div class="listing-heading text-center">
<a class="text-primary" >{{ category.Description }}</a>
</div>
<hr>
Voir la catégorie
</div>
</div>
</div>
{% endfor %}
{% else %}
<div class="col-md-12">
<p>Aucune catégorie disponible</p>
</div>
{% endif %}
#my template Subcategory.html
<div class="row">
{% if articles %}
{% for article in articles %}
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img class="card-img-top" src="{{ article.photo_main.url }}" alt="">
<div class="card-body">
<h4 class="card-title">
{{ article.désignation }}
</h4>
<h5>{{ article.Sous_Catégorie }}</h5>
<p class="card-text">{{ article.Description }}</p>
</div>
<div class="card-footer">
<h6 class="text-muted">Ajouter au panier</h6>
</div>
</div>
</div>
{% endfor %}
{% else %}
<a class="list-group-item"> Aucune sous catégorie disponible</a>
{% endif %}
</div>

How do I make sure markdown doesn't appear when listing posts in a blog?

I'm building a blog using Django and I just integrated markdown. How do I make sure that the truncated part of the body of a post (which is telling a little of what you'll see when that particular post is opened) doesn't display markdown?
I created a template filter markdown:
from django.utils.safestring import mark_safe
from django import template
import markdown
register = template.Library()
#register.filter(name='markdown')
def markdown_format(text):
return mark_safe(markdown.markdown(text))
Here's the usage in the post_list.html template
{% extends "base.html" %}
{% load blog_tags static disqus_tags %}
{% disqus_dev %}
{% block content %}
<div class="jumbotron">
<h1 class="heading-font">Shelter At Your Crossroads</h1>
<p class="lead">...some random ass text that could serve as motto or something</p>
</div>
<div class="container">
<div class="row">
<div class="col-lg-8">
{% if tag %}
<h2 class="mb-4">Posts tagged with "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<div class="card mb-5">
<img class="card-img-top img-fluid" src="{{ post.image.url }}" alt="{{ post.title }}">
<div class="card-body">
<h2 class="card-title">{{ post.title }}</h2>
<p class="card-text">{{ post.body|markdown|truncatewords_html:50 }}</p>
<i class="fa fa-book" aria-hidden="true"></i> Read More
<i class="fa fa-share-alt" aria-hidden="true"></i> Share Post
<div class="float-right">
<i class="fa fa-tags"></i>
{% for tag in post.tags.all %}
<a href="{% url 'post_list_by_tag' tag.slug %}">
<span class="badge badge-pill badge-info">{{ tag.name }}</span>
</a>
{% endfor %}
</div>
</div>
<div class="card-footer text-center text-muted">
Posted on {{ post.publish.date }} by {{ post.author.get_full_name }}
</div>
</div>
{% endfor %}
</div>
<div class="col-lg-4">
<div class="card border-dark mb-3">
<div class="card-header">Post Count</div>
<div class="card-body text-dark">
<h4 class="card-title text-center">Total Number of Posts</h4>
<p class="card-text text-center display-3">{% total_posts %}</p>
</div>
</div>
<div class="card border-dark mb-3">
<div class="card-header">Latest Posts</div>
<div class="card-body text-dark">
<h4 class="card-title text-center">Most Recent Posts</h4>
<p class="card-text">{% show_latest_posts 3 %}</p>
</div>
</div>
<div class="card border-dark mb-3">
<div class="card-header">Latest Comments</div>
<div class="card-body text-dark">
<h4 class="card-title text-center">Most Recent Comments</h4>
<p class="card-text">{% disqus_recent_comments shortname 5 50 1 %}</p>
</div>
</div>
</div>
</div>
{% include 'includes/pagination.html' with page=posts %}
</div>
{% endblock %}
The filter was used on line 22 - {{ post.body|markdown|truncatewords_html:50 }}
How do I make display just normal text?

Django multiple duplications

I'm using django notifications, but when unread notifications increasing, loading time and duplication times are also increasing. How can I optimize this code ?
{% for notification in request.user.notifications.unread %}
<li><div class="media">
<div class="media-left">
<div class="media-object">
<img data-src="holder.js/50x50?bg=cccccc" class="img-circle" alt="50x50" style="width: 50px; height: 50px;"
src="{{ BASE_DIR}}/media/profile_pictures/{{notification|getNotifUser}}/profile.jpg" data-holder-rendered="true">
</div>
</div>
<div class="media-body">
<strong class="notification-title">
<a id="{{ notification.target_object_id }}" class="{{ notification.pk }}">
{{ notification.actor_object_id|get_username}} {{notification.verb}} - request {{notification.target_object_id}}</a></strong>
<div class="notification-meta">
<small class="timestamp">{{ notification.timesince | getLocalTimeDifference}} əvvəl</small>
</div>
</div>
</div> </li>
{% endfor %}

django class page view not rendering template code

I wanted to use class based views and went through the django documentation and I get noerror messages but wind up with an empty template. I had it working with the non-classed based views. How do I reformat the code so that it renders the template? The template consists of a title, some headings, a navigational menu, flags for selecting instructions in different languages,
followed by a form which shows a flag, policy name char field, and a check box control. I think the initial = {'key': 'value'} in the view forms incorrect but I don't know what to replace it with. Thanks in advance.
forms.py
from django import forms
from policytracker.models import Flag, Label_Links
class PolicyStartForm( forms.Form ):
flags = Flag.objects.all()
policy = Label_Links.objects.all().filter(iso_language='en')[0]
frm_policy1_name=[]
for flag in flags:
frm_policy1_name.append(forms.CharField(max_length=40))
policy_dict = { 'new_policy_link' :policy.nav_section_new_policy_link,
'new_policy_label' :policy.nav_section_new_policy_label,
'graphs_link':policy.nav_section_graphs_link,
'graphs_label' :policy.nav_section_graphs_label,
'account_link' :policy.nav_section_account_link,
'account_label' :policy.nav_section_account_label,
'policy_list_link':policy.nav_section_list_policies_link,
'policy_list_label':policy.nav_section_list_policies_label,
'login_link' :policy.nav_section_login_link,
'login_label' :policy.nav_section_login_label,
'new_policy1_heading' :policy.new_policy1_heading,
'new_policy1_title_label':policy.new_policy1_title_label,
'policy_needs_translation_label':policy.new_policy1_needs_trans_label,
'policy1_submit_label': policy.new_policy1_submit_button_label,
'policy1_tip_msg' :policy.new_policy1_tip_msg,
't_logged_in' :True,
'frm_policy_name' :frm_policy1_name,
't_flags' :flags }
</code>
<code>
views.py
# coding=utf-8
from django.shortcuts import render
from django.http import HttpResponseRedirect
from policytracker.forms import LoginForm, PolicyStartForm
from policytracker.models import Flag, Label_Links
from django.views import View
class PolicyStartView(View):
template_name = 'policystart.html'
initial = {'key': 'value'}
form_class = PolicyStartForm
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
</code>
<code>
policystart.html
{% extends "policy-base.html" %}
{% block navsection %}
<div class="container top">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<h1 class="text-center">{{ new_policy1_heading }}</h1>
</div>
</div>
{% if t_policy_details %}
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-left" id="week_start">2017-02-11</h4></div>
<div class="col-md-4 col-xs-4">
<h4 class="text-center" id="week_number">Week 1</h4></div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-4">
<h4 class="text-nowrap text-right" id="week_end">2016-09-18</h4></div>
</div>
{% endif %}
<div class="row">
<div class="col-md-12">
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header"><a class="navbar-brand hidden navbar-link" href="#"> Policies</a>
<button class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navcol-1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button>
</div>
<div class="collapse navbar-collapse" id="navcol-1">
<ul class="nav navbar-nav navbar-right">
<li class="hidden" role="presentation">{{ new_policy_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ graphs_label }}</li>
<li {% if not t_logged_in %} class="hidden" {% endif %} role="presentation">{{ account_label }}</li>
<li role="presentation">{{ policy_list_label }}</li>
{% if not t_logged_in %} <li role="presentation">{{ login_label }}</li> {% endif %}
</ul>
</div>
</div>
</nav>
</div>
</div>
{% include "pol-new1-lang.html" %}
</div>
<div class="container middle-container">
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-8">
<h4>{{ new_policy1_title_label }}</h4>
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<h4 class="text-center">{{ policy_needs_translation_label }}</h4>
</div>
</div>
<form method="POST">
{% csrf_token %}
{% load static %}
{% for f in t_flags %}
<div class="row flag">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-2"><img src="{% static f.flag_image_filename %}"></div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-9">
<input class="form-control" type="text" name="policytitle">
</div>
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-1">
<input class="form-control" type="checkbox" name="needstranslation">
</div>
</div>
{% endfor %}
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<button class="btn btn-default" type="submit">{{ policy1_submit_label }}</button>
</div>
</div>
</form>
<div class="row enter">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<p> </p>
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-8">
<p>{{ policy1_tip_msg }}</p>
</div>
</div>
</div>
{% endblock %}
</code>
You're using a load of variables in your template, but you aren't actually sending any of them to the context; the only thing your view passes is form. If you want to use things like new_policy1_heading, policy_needs_translation_label and t_flags you need to define them in your view and send them to the template from there.
Actually, it looks like you've completely misunderstood the jobs of forms and views. All the code you've currently put inside your form actually belongs in the view, and you should use policy_dict as the template context. It doesn't look like you need a form class at all.
Even there, though, you're doing much more work than you need to. There's no need to send all the specific fields of the policy object individually; just send policy and then in the template you can do {{ policy.policy_needs_translation_label }} etc.