I am working on a blog project and I am getting the "Matching query does not exist "error. I have tried using try block thinking that the model class might not be returning any value. Hence, modified my views.py as below:-
from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.db.models import Q
from .forms import *
# Create your views here.
def home(request):
print("I am home")
try:
blog_data = BlogPost.objects.all()
print("blog_data", blog_data)
except BlogPost.DoesNotExist:
blog_data = None
print("blog_data", blog_data)
try:
last_element = BlogPost.objects.filter(id = len(blog_data))[0]
print("last_element", last_element)
except BlogPost.DoesNotExist:
last_element = None
print("last_element", last_element)
tags_list = BlogPost.objects.values_list("tags", flat = True).distinct()
#tags_list = BlogPost.objects.all().distinct()
context = {'blog_data':blog_data, "last_element":last_element, "tags_list":tags_list}
#last_element = list(BlogPost.objects.all().reverse()[0])
print("last_element",last_element, "blog_data",blog_data,"context",context)
return render(request, 'blog/home.html', context)
# def home(request):
# blog_data = BlogPost.objects.all()
# context = {'blog_data':blog_data}
# print('context', context)
# last_element = BlogPost.objects.all().reverse()[0]
# #last_element = BlogPost.objects.all().reverse()[0]
# return render(request, 'blog/home.html', context)
def new_post(request):
if request.method == 'POST':
form = BlogForm(data = request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('home')
else:
form = BlogForm()
return render(request, 'blog/blogform.html', {'form':form })
def login_user(request):
username = password = ''
state = "Please log in"
if request.POST:
username = request.POST.get('Username')
password = request.POST.get('Password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
state = "You're successfully logged in!"
return HttpResponseRedirect('/blog/home')
else:
state = "Your account is not active, please contact the site admin."
else:
state = "Your username and/or password were incorrect."
#return render_to_response('main/login.html',{'state':state, 'username': username})
return render(request, "blog/login.html", {'state':state, 'username': username, 'next_page':"home.html"})
#return HttpResponseRedirect("home.html")
def logout_user(request):
logout(request)
return render(request,'blog/home.html')
def register_user(request):
username = password = password_again = email = ''
state = ''
if request.method == 'POST':
username = request.POST.get('Username')
password = request.POST.get('Password')
password_again = request.POST.get('Password_again')
email = request.POST.get('Email')
print('email', email)
if password == password_again:
password = make_password(password, salt = None, hasher = 'default')
else:
state = "Password and password re-entered do not match, please try again..."
return HttpResponseRedirect('login')
print("at 63")
try:
user = User.objects.get(username = username)
print('user at 67', user)
except Exception as e:
print("Error is :", e)
user = None
print("user", user)
try:
emailID = User.objects.get(email = email)
print("emailID", emailID)
except Exception as e:
print("Error is :", e)
emailID = None
print("emailID exception", emailID)
if user is not None:
state = 'Username already exists, please try another one...'
else:
if emailID is None:
new_user = User(username = username, password = password, email = email)
##Adding new logic for securityQAs vvv
#new_SQA = SecurityQA(user_email = email, security_question = security_question, security_answer = security_answer)
##Adding new logic for securityQAs ^^^
new_user.save()
#new_SQA.save()
state = 'You are successfully registered.. Thanks'
return HttpResponseRedirect('login')
else:
state = "Email ID already registered, try a new one.."
print('state at else', state)
#return HttpResponseRedirect('login')
return render(request, "blog/register.html", {'state':state, 'username':username, 'next_page':'home.html'})
def forgot_password(request):
pass
def comment_posted(request):
return render(request, "blog/comment_posted.html")
def blog_search(request):
qset = Q()
keyword = ''
keyword = request.POST.get('keyword')
print("keyword", keyword)
for word in keyword.split():
qset |= (Q(title__contains = word)|Q(description__contains = word))
print('qset', qset)
result = BlogPost.objects.filter(qset)
context = {'result':result}
return render(request, 'blog/blog_search.html', context)
Also, find my models.py below
from django.db import models
from django.contrib.auth.models import User
#from django.core.files.storage import FileSystemStorage
#fs = FileSystemStorage(location='E:\django\myblog\\blog\uploaded images')
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length = 30)
posted_by = models.CharField(max_length = 30)
posted_on = models.DateTimeField(auto_now_add = True)
description = models.CharField(max_length = 200)
comment = models.CharField(max_length = 150)
tags = models.CharField(max_length=50, default = "notag")
image = models.ImageField(upload_to = 'uploaded_images', default = None, null = True, blank = True)
def __str__(self):
#return "{0} : {1}".format(self.title, self.description)
return self.title
template code as below (home.html). Here I am getting the error at line "{% get_comment_list for blog.blogpost last_element.id as comment_list %}"
{% load staticfiles %}
{%load comments%}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Sourav's blog</title>
<!-- Bootstrap Core CSS -->
{%block styling%}
<link href="{%static 'css/bootstrap.min.css'%}" rel="stylesheet">
<!-- Custom CSS -->
<link href="{%static 'css/blog-post.css'%}" rel="stylesheet">
{%endblock styling%}
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Ideate</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
New idea
</li>
<!-- <li>Login</li> -->
{{user.is_authenticated}}
{% if user.is_authenticated %}
<li>
Logout
</li>
{% else %}
<li>
Login
</li>
{% endif %}
<li>
Help
</li>
{% if user.is_authenticated %}
<li>
Hi {{user.username}}
</li>
{%else%}
{% endif %}
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Page Content -->
<div class="container">
<div class="row">
<!-- Blog Post Content Column -->
<div class="col-lg-8">
<!-- Blog Post -->
<!-- Title -->
<h1>Idea Blog</h1>
<!-- Author -->
<p class="lead">
by Sourav
</p>
<hr>
<!-- Date/Time -->
<p><span class="glyphicon glyphicon-time"></span>
Posted on
<!-- {%for i in blog_data%}
{{i.posted_on}}
{%endfor%}</p> -->
{{last_element.posted_on}}
<hr>
<!-- Preview Image -->
<img class="img-responsive" src="http://placehold.it/900x300" alt="">
<hr>
<!-- Post Content -->
<!-- <p>Below is the result</p> -->
<!-- <p>{{blog_data}}</p> -->
<p>
<!-- {%for i in blog_data%}
<h1>{{i.title}}</h1>
<p>{{i.description}}</p>
{%empty%}
<span>No data</span>
{%endfor%} -->
<!-- {{last_element}} -->
<h1>{{last_element.title}}</h1><span> posted by {{last_element.posted_by}}</span>
<p>Description : {{last_element.description}}</p>
{{last_element.image}}
<p>Tags : {{last_element.tags}}</p>
{% get_comment_count for blog.blogpost last_element.id as comment_count %}
<p>{{ comment_count }} comments have been posted.</p>
{% get_comment_list for blog.blogpost 1 as comment_list %}
{% for comment in comment_list %}
<p>Posted by: {{ comment.user_name }} on {{ comment.submit_date }}</p>
<p>Comment: {{ comment.comment }}</p>
{% endfor %}
{% get_comment_form for blog.blogpost last_element.id as form %}
<!-- A context variable called form is created with the necessary hidden
fields, timestamps and security hashes -->
<table>
<form action="{% comment_form_target %}" method="post">
{% csrf_token %}
{{ form }}
<tr>
<td colspan="1">
<input type="submit" name="submit" value="Post">
<input type="submit" name="preview" value="Preview">
<input type="hidden" name="next" value="{% url 'comment_posted' %}" />
</td>
</tr>
</form>
</table>
{% get_comment_list for blog.blogpost last_element.id as comment_list %}
{%for comment in comment_list%}
<li><b>{{comment.name}}</b> has posted comment on {{comment.submit_date}} </li>
<ul><li>{{comment.comment}}</li></ul>
<a name="c{{ comment.id }}"></a>
<a href="{% get_comment_permalink comment %}">
see comment details
</a>
{%endfor%}
</p>
</div>
<div class="col-md-4">
<!-- Blog Search Well -->
<form action = "{%url 'blog_search'%}" method = "POST">
<div class="well">
<h4>Blog Search</h4>
<div class="input-group">
{%csrf_token%}
<input type="text" class="form-control" name = "keyword", placeholder = "Enter search keyword">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
<!-- /.input-group -->
</div>
</form>
<!-- Blog Categories Well -->
<div class="well">
<h4>Tags</h4>
<div class="row">
<div class="col-lg-6">
<ul class="list-unstyled">
<!-- {%for a in tags_list%}
{{a}}
{%endfor%} -->
<!-- {%for a in tags_list%}
{{a}}
{%endfor%} -->
{%for a in tags_list%}
{{a}},
{%endfor%}
<!-- <li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li> -->
</ul>
</div>
<div class="col-lg-6">
<ul class="list-unstyled">
<li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li>
<li>Category Name
</li>
</ul>
</div>
</div>
<!-- /.row -->
</div>
<!-- Side Widget Well -->
<div class="well">
<h4>Side Widget Well</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Inventore, perspiciatis adipisci accusamus laudantium odit aliquam repellat tempore quos aspernatur vero.</p>
</div>
</div>
</div>
</div>
</div>
<!-- Blog Sidebar Widgets Column -->
<!-- /.row -->
<hr>
<!-- Footer -->
<footer>
<div class="row">
<div class="col-lg-12">
<p>Copyright © Your Website 2014</p>
</div>
</div>
<!-- /.row -->
</footer>
</div>
<!-- /.container -->
<!-- jQuery -->
{%block javascript%}
<script src="{%static 'js/jquery.js'%}"></script>
<!-- Bootstrap Core JavaScript -->
<script src="{%static 'js/bootstrap.min.js'%}"></script>
{%endblock javascript%}
</body>
</html>
When I am loading my homepage (home.html) I am not facing any issue, however, when I am trying to logout after logging in i am facing the error . My logout view is rendering home.html also. However, in this case it doesn't work. Please help me out of this. I am stuck.
My quick answer is that the logout view function is not providing the context variables that the home.html template needs. Try redirecting to the home view instead.
Related
I am currently developping an application on django and when i send a post request from a form, is_valid method return false, but form.is_bound return True.
my form.error -> mailThis field is required.prenomThis field is required.nomThis field is required.
my forms.py
from django import forms
class formadduser(forms.Form):
mail = forms.CharField(label='Mail', max_length=40)
# imput_username = forms.CharField(input='input_username', max_length=100)
prenom = forms.CharField(label='Prénom', max_length=25)
# input_password = forms.CharField(input='input_pathword', max_length=100)
nom = forms.CharField(label = 'Nom', max_length=25)
views.py where i'm trying to get the form inputs:
from re import S
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect, QueryDict
from .forms import formadduser
import pickle
import os
from .fonctions import tri
from .models import Users
# Create your views here.
def administrator(request) :
# test = request.POST[username]
# print(test)
# request.form['username'] je crois que c'est du flask
return render(request, 'admin.html')
def index(request):
if request.method == 'POST':
var = request.POST["username"]
print(var)
text = """<h1>{{var}}</h1>
<p>les crepes nananinanana</p>"""
return HttpResponse(text)
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = formadduser(request.POST)
print(form)
# check whether it's valid:
if form.is_valid():
print("debug")
print(form.cleaned_data["mail"])
var = Users(mail = form.cleaned_data["Mail"], prenom = form.cleaned_data["Prenom"], nom = form.cleaned_data["Nom"])
var.save()
# process the data in form.cleaned_data as required
# ...
# print(NameForm.username)
# redirect to a new URL:
# return HttpResponseRedirect('/thanks/')
# Username = form.cleaned_data
# text = """<h1>{{form.cleaned_data["username"]}}</h1>
# <p>les crepes nananinanana</p>"""
# return HttpResponse(text)
# print(form.cleaned_data["username"])
# u = USERS(Username = form.cleaned_data["username"], droits = form.cleaned_data["droits"])
# u.save()
# query = pickle.loads("zeubi")
# test = list(USERS.objects.values("Username"))
# test = USERS.objects.values("Username")
# test = USERS.objects.all()
# test = str(USERS.objects.values("droits"))
# res = tri(test)
# user_qs = USERS.objects.all()
# for user in user_qs:
# print(user['Username'])
# testv = QueryDict
# test.query = query
return render(request, 'admin.html')
# return render(request, 'admin.html', {'test' : test})
# return(locals())
# USERS.Username = form.cleaned_data["username"]
# return form.cleaned_data
else:
print("invalid form")
print(form.is_bound)
# print(form.errors)
# if a GET (or any other method) we'll create a blank form
else:
print("error")
form = formadduser()
return render(request, 'admin.html', {'form': form})
templates.py with 4 forms but my test is on formadduser:
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ADMIN</title>
{% load static %}
<script src="{% static 'global/jquery.js' %}"></script>
<script src="{% static 'administrator/admin.js' %}"></script>
<link rel="stylesheet" type="text/css" href="{% static 'administrator/admin.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'global/StyleGlobal.css' %}">
</head>
<body id="idbody" onclick="fout();foutform()">
<div class="bande">
<div onclick="testhb()" id="hb">
<div class="barre"></div>
<div class="barre"></div>
<div class="barre"></div>
<ul id="ulmenu">
<li class="menu"><a class="textdeco" href="http://10.75.101.201/Front/mat/mat.html">Materiel</a></li>
<li class="menu"><a class="textdeco" href="http://10.75.101.201/Front/offrecgr/offrecgr.html">Offres/CGR</a></li>
</ul>
</div>
<!-- </div> -->
<div class="logo">
<img src="{% static 'global/GHD.png' %}" alt="Logo">
<!-- -->
</div>
</div>
<div class="titre">
<h1 class="accueiltxt">ADMIN</h1>
</div>
<div class="gigacontainer" id="gigacontainer">
<div class="containerbutton">
<div class="button" id="buttonsuppuser" onclick = "buttonsuppuser()">
<p class="trashcan">🗑</p></div>
<div class="button" id="buttonadduser" onclick="buttonadduser()">+</div>
<div class="txtbutton">Users</div>
<div class="button" id="buttonsuppapp" onclick = "buttonsuppapp()">🗑</div>
<div class="button" id="buttonaddapp" onclick = "buttonaddapp()">+ </div>
<div class="txtbutton">Apps</div>
</div>
<form action="" method="post" class="form" id="formsuppuser">
{% csrf_token %}
<label for="suppuser">Username</label>
<input type="text" name="suppuser" id="suppuser">
<button>Supprimer</button>
</form>
<form name="formadduser" action="" method="post" class="form" id="formadduser">
{% csrf_token %}
<label for="addusermail">Mail</label>
<input required="required" type="text" name="addusermail" id="addusermail">
<label for="adduserprenom">Prénom</label>
<input required="required" type="text" name="adduserprenom" id="adduserprenom">
<label for="addusernom">Nom</label>
<input required="required" type="text" name="addusernom" id="addusernom">
<button type="submit">Ajouter</button>
</form>
<form action="" method="post" class="form" id="formsuppapp">
{% csrf_token %}
<label for="suppapp">Application</label>
<input type="text" name="suppapp" id="suppapp">
<button>Supprimer</button>
</form>
<form action="" method="post" class="form" id="formaddapp">
{% csrf_token %}
<label for="addapp">Application</label>
<input type="text" name="addapp" id="addapp">
<button>Ajouter</button>
</form>
</div>
</html>
You should have the errors in form.errors, without them, we cannot tell you anything.
It may also be that your form is not bound (request data have not be sent to the form). You can check this with form.is_bound.
If this return false, you did not send your data into your form:
form = MyForm(data=request.POST)
You can see how is_valid works in the django source.
As you can see, you can know whats wrong juste by checking form.is_bound or form.errors.
I have two options for my articles in my django website: "draft" and "published"
I wrote sth that helps me show only the articles that are on "published" status in admin page.
But the code doesn't work. when I click on the specified category for each article, even the draft ones show up. How can I fix it?
#################
#models.py
from django.db import models
from django.utils import timezone
# my managers
class ArticleManager(models.Manager):
def published(self):
return self.filter(status='Published')
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=300, verbose_name="Category Topic")
slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address")
status = models.BooleanField(default=True, verbose_name="Do you want to show?")
position = models.IntegerField(verbose_name="position")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['position']
def __str__(self):
return self.title
class Article(models.Model):
STATUS_CHOICES = (
('Draft', 'Draft'),
('Published', 'Published')
)
title = models.CharField(max_length=300)
slug = models.SlugField(max_length=100, unique=True)
category = models.ManyToManyField(Category, verbose_name="Category", related_name="articles")
description = models.TextField()
thumbnail = models.ImageField(upload_to="images")
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES)
class Meta:
ordering = ['-publish']
def __str__(self):
return self.title
def category_published(self):
return self.category.filter(status=True)
objects = ArticleManager()
############
#Views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse, Http404
from .models import Article, Category
# Create your views here.
def home(request):
context = {
"articles": Article.objects.published()
}
return render(request, 'website/home.html', context)
def detail(request, slug):
context = {
"article": get_object_or_404(Article.objects.published(), slug=slug)
}
return render(request, 'website/detail.html', context)
def article(request):
context = {
"articles": Article.objects.filter(status="Published"),
"category": Category.objects.filter(status=True)
}
return render(request, 'website/article.html', context)
def category(request, slug):
cat = get_object_or_404(Category, slug=slug, status=True)
context = {
"category": cat.articles.all()
}
return render(request, 'website/category.html', context)
###########
#Category.html page
{% extends 'website/base.html' %}
{% load static %}
{% block main %}
<main id="main">
<!-- ======= Breadcrumbs ======= -->
<section id="breadcrumbs" class="breadcrumbs">
<div class="container">
<div class="d-flex justify-content-between align-items-center">
<h2>Blog</h2>
<ol>
<li>Home</li>
<li>Blog</li>
</ol>
</div>
</div>
</section><!-- End Breadcrumbs -->
<!-- ======= Blog Section ======= -->
<section id="blog" class="blog">
<div class="container">
<div class="row">
<div class="col-lg-8 entries">
{% for article in category %}
<article class="entry" data-aos="fade-up">
<div class="entry-img">
<img src="{{ article.thumbnail.url }}" alt="" class="img-fluid">
</div>
<h2 class="entry-title">
{{ article.title }}
</h2>
<div class="entry-meta">
<ul>
<li class="d-flex align-items-center"><i class="icofont-user"></i>
John Doe</li>
<li class="d-flex align-items-center"><i class="icofont-wall-clock"></i>
<time>{{ article.publish }}</time></li>
<li class="d-flex align-items-center"><i class="icofont-tags"></i>
<ul class="tags">
{% for cat in article.category_published %}
#{{ cat.title }}
{% endfor %}
</ul>
</li>
<li class="d-flex align-items-center"><i class="icofont-comment"></i>
12 Comments</li>
</ul>
</div>
<div class="entry-content">
{{ article.description|truncatewords:30}}
<div class="read-more">
Read More
</div>
</div>
</article><!-- End blog entry -->
{% endfor %}
<div class="blog-pagination">
<ul class="justify-content-center">
<li class="disabled"><i class="icofont-rounded-left"></i></li>
<li>1</li>
<li class="active">2</li>
<li>3</li>
<li><i class="icofont-rounded-right"></i></li>
</ul>
</div>
</div><!-- End blog entries list -->
<div class="col-lg-4">
<div class="sidebar" data-aos="fade-left">
<h3 class="sidebar-title">Search</h3>
<div class="sidebar-item search-form">
<form action="">
<input type="text">
<button type="submit"><i class="icofont-search"></i></button>
</form>
</div><!-- End sidebar search formn-->
{# <h3 class="sidebar-title">Categories</h3>#}
{# <div class="sidebar-item categories">#}
{# <ul>#}
{# {% for cat in category %}#}
{# <li class="active"><a href="{% url 'website:category' cat.slug %}">#{{ cat.title
}}</a></li>#}
{# {% endfor %}#}
{# </ul>#}
{##}
{# </div><!-- End sidebar categories-->#}
<h3 class="sidebar-title">Recent Posts</h3>
<div class="sidebar-item recent-posts">
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-1.jpg" alt="">
<h4>Nihil blanditiis at in nihil autem</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-2.jpg" alt="">
<h4>Quidem autem et impedit</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-3.jpg" alt="">
<h4>Id quia et et ut maxime similique occaecati ut</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-4.jpg" alt="">
<h4>Laborum corporis quo dara net para</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
<div class="post-item clearfix">
<img src="assets/img/blog-recent-posts-5.jpg" alt="">
<h4>Et dolores corrupti quae illo quod dolor</h4>
<time datetime="2020-01-01">Jan 1, 2020</time>
</div>
</div><!-- End sidebar recent posts-->
<h3 class="sidebar-title">Tags</h3>
<div class="sidebar-item tags">
<ul>
<li>App</li>
<li>IT</li>
<li>Business</li>
<li>Business</li>
<li>Mac</li>
<li>Design</li>
<li>Office</li>
<li>Creative</li>
<li>Studio</li>
<li>Smart</li>
<li>Tips</li>
<li>Marketing</li>
</ul>
</div><!-- End sidebar tags-->
</div><!-- End sidebar -->
</div><!-- End blog sidebar -->
</div>
</div>
</section><!-- End Blog Section -->
</main><!-- End #main -->
{% endblock %}
Your category view is returning all articles, if you just want published articles in the category you need to filter them.
def category(request, slug):
# filter only published articles
cat = get_object_or_404(Category, slug=slug, status=True)
context = {
"published_articles_in_category": cat.articles.filter(status='Published')
}
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.
My models are as shown below.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
def __str__(self):
return ".`. {}_____{}".format(self.size_id,
self.prod_id)
This is the form I used to add and edit the model.
forms.py
from django import forms
from user.models import SizeProductMapping
class SizeProductMapForm(forms.ModelForm):
class Meta:
model = SizeProductMapping
fields = ['size_id', 'prod_id']
Here is the view I created to add ,update and delete the record.
views.py
def sizeProductMap(request):
form = SizeProductMapForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect("/admin1/sizeProductMap/")
else:
sizeProductMap_show = SizeProductMapping.objects.all()
# start paginator logic
paginator = Paginator(sizeProductMap_show, 3)
page = request.GET.get('page')
try:
sizeProductMap_show = paginator.page(page)
except PageNotAnInteger:
sizeProductMap_show = paginator.page(1)
except EmptyPage:
sizeProductMap_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show, 'form': form})
def sizeProductMap_delete(request, id):
sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
sizeProductMap_delete.delete()
return redirect('/admin1/productSizeMap')
def sizeProductMap_edit(request, id):
instance = SizeProductMapping.objects.get(size_p_map_id=id)
form = SizeProductMapForm(instance=instance)
if request.method == 'POST':
form = SizeProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/sizeProductMap')
return render(request, 'admin1/sizeProductMap.html', {'form': form})
This is my urls.
urls.py
from django.urls import path
from admin1 import views
urlpatterns = [
path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]
This is the Html page where I want to display the form according to the page request.
sizeProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
<center>Size Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{% if sizeProductMap_show %}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Size Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-size-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.size_id.label_tag}}
</th>
<td>{{form.size_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Size Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Size Product Mapping Id</th>
<th>Product ID</th>
<th>Size ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in sizeProductMap_show %}
<tr>
<td>{{x.size_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.size_id}}</td>
<td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-size-product-map-delete' x.size_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if sizeProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in sizeProductMap_show.paginator.page_range %}
{% if sizeProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if sizeProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
And if it is possible to reduce the number of line of code please also help. Thanks in advance.
I've found out the answer. There was a really a silly mistake by me.
In the sizeProductMap.html there is a mistake let me point out that:
sizeProductMap.html
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing.
I have to check {% if instance %} according to my views.py.
I have web applicaction.
This is part of my code:
mailaliases.html
{% extends "bootstrap/base.html" %}
{% block title %}
Strona do edycji aliasów
{% endblock %}
{% block styles %}
{{super()}}
<link rel="stylesheet" href="{{url_for('.static', filename='starter-template.css')}}">
{% endblock %}
{% block content %}
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Badaj.to / SLA</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Główna</li>
<li>Zmiana hasła</li>
<li>Panel Administratora</li>
<li>Wyloguj się</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
</br></br>
<p class="lead"><h1>Wybierz użytkownika, któremu chcesz ustawić alias.<br></B></p>
<font size="4">
{{ tablepoczta }}
</font>
</div>
</div><!-- /.container -->
{% endblock %}
here are definied classes
class UserPoczta(UserMixin, dbpoczta.Model):
__bind_key__ = 'dbpocztamysql'
__tablename__ = "flask_test_poczty"
id = dbpoczta.Column(dbpoczta.Integer, primary_key=True)
address = dbpoczta.Column(dbpoczta.String(60), unique=True)
goto = dbpoczta.Column(dbpoczta.String(800), unique=False)
active = dbpoczta.Column(dbpoczta.Integer, unique=False)
class AliasesResult(Table):
__bind_key__ = 'dbpocztamysql'
id = Col('Id', show=False)
# id = Col('Id')
address = Col('Adres e-mail')
goto = Col('Aliasy')
active = Col('Aktywny')
editpoczta = LinkCol('Edytuj', 'editpoczta', url_kwargs=dict( id = 'id'))
class UserPocztaForm(Form):
__bind_key__ = 'dbpocztamysql'
__tablename__ = "flask_test_poczty"
id = StringField('Id')
address = StringField('e-mail')
goto = StringField('Aliasy')
active = StringField('Aktywny')
here is route
#app.route('/mailaliases')
#login_required
def mailaliases():
if current_user.role == 'admin':
qrypoczta = dbpoczta.session.query(UserPoczta).order_by(UserPoczta.address.desc())
resultspoczta = qrypoczta.all()
tablepoczta = AliasesResult(resultspoczta)
tablepoczta.border = True
return render_template('mailaliases.html', tablepoczta=tablepoczta)
return render_template('notauthorized.html', name=current_user.username)
I would like to add column to table on website fe column name error_addresses. In this table should be addresses which are in goto column in row and not exist in column addresses in database. This table show e-mail address and aliases in goto column. For example I have some mail like mail1#mail.pl, mail2#mail.pl, mail3#mail.pl and if anyone add to aliass alia1#mail.pl addresses mail1#mail.pl, mail20#mail.pl I would like show mail20#mail.pl in new column error_addresses in row with this aliases.
I'm tried using loop for and if
if current_user.role == 'admin':
if userpoczta:
form = UserPocztaForm(formdata=request.form, obj=userpoczta)
if request.method == 'POST' and form.validate():
save_changes(userpoczta, form)
for adresy in dbpoczta.session.query(UserPoczta.address):
if userpoczta.goto not in adresy:
return ("error")
return redirect('/mailaliases')
return render_template('edit_aliases.html', form=form)
else:
return 'Error loading #{id}'.format(id=id)
return render_template('notauthorized.html', name=current_user.username)
I'm making a sign in system in Django Python, i've been preparing the forms.py, views.py and the template itself, but so far the form fail to load on the template, can anyone help?
Forms.py
class Email_Only_SignUp_Form(forms.Form):
email = forms.EmailField(initial='Your Email...')
Views.py
def email_only_signup_form(request, template_name):
if request.method == 'POST':
signup_form = Email_Only_SignUp_Form(request.POST)
if signup_form.is_valid():
email = signup_form.cleaned_data['email']
username = email
try:
#check for duplicate username
User.objects.get(username=username)
email_error = 'email already exist'
except:
#initial creation of user object
try:
import os, random, string
length = 13
chars = string.ascii_letters + string.digits + '!#$()'
random.seed = (os.urandom(1024))
password = ''.join(random.choice(chars) for i in range(length))
User.objects.create_user(username,
username,
password,
)
user = User.objects.get(username=username)
user_profile=UserProfile(user=user)
user_profile.save()
#send email to user
try:
admin_email = settings.EMAIL_ORIGIN_MEMBERS
email_txt = loader.get_template('account/emails/createaccount.html')
email_html = loader.get_template('account/emails/createaccounthtml.html')
email_context = Context({'u_name': username,
'username': username,
'password': password,
})
new_user_mail = EmailMultiAlternatives('Welcome!',
email_txt.render(email_context),
admin_email,
[user.email, ],
headers={'Reply-To': 'admin#admin.com'}
)
new_user_mail.attach_alternative(email_html.render(email_context), 'text/html')
new_user_mail.send()
except:
pass
return redirect('/account/thankyou/?next=%s'%next)
except:
pass
else:
print('user form in not valid')
else:
signup_form = Email_Only_SignUp_Form()
return render_to_response(template_name, locals(), context_instance=RequestContext(request))
email_only_signup_form.html
{% extends "index.html" %}
{% block heroslider %}
<div class="page_title2" style="padding:150px 0px 50px 0px;">
<div class="container">
<h1>User Registration</h1>
</div>
</div><!-- end page title -->
{% endblock %}
{% block main_body %}
<style type="text/css">
input[type='radio'], input[type='checkbox'] {
width:20px;
vertical-align: middle;
}
div.reg_error {
position:relative;
top:-10px;
margin-top:0px;
padding-top:0px;
color:red;
}
</style>
<div class="container">
<form class="pagesignup logiform" action="" method="POST">{% csrf_token %}
<div class="row">
<div class="large-12 columns" style="margin-bottom: 30px;">
<div class="reg_form">
<div class="sky-form">
<header>REGISTER</header>
</div>
<div class="row">
<div class="large-12 columns">
<p>Email<br/>
{{signup_form.email}}
<div class="reg_error">{{ signup_form.email.errors.as_text }}{{email_error}}</div></p>
</div>
</div>
<div class="row">
<div class="large-12 large-centered columns" style="text-align:center;padding:20px;">
<input class="but_medium1" style="border:none;" type = "submit" value="REGISTER" /><br>
<br>By clicking on register, you have read and agreed to our terms of use
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- Google Code for Sign Up Page (landed) Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 969557266;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "5zU4CJby_FoQkoqpzgM";
var google_remarketing_only = false;
/* ]]> */
</script>
<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/conversion/969557266/?label=5zU4CJby_FoQkoqpzgM&guid=ON&script=0"/>
</div>
</noscript>
{% endblock %}
You have not passed the signup_form to the template.
return render_to_response(template_name, {'signup_form': signup_form}, context_instance=RequestContext(request))
I have no idea what locals() does.
Edit: I just saw locals which is a built in python function. It will be better if you explicitly pass the variables you need in the template.
Edit 2: Check if it is the correct template_name. In the template simply print and see the form {{ signup_form }}. See if it is available.
You are not returning the form.
Try changing the last line of the view to
return render_to_response(template_name, locals(), context_instance=RequestContext(request, {'signup_form' : signup_form ))