Issue with views on button click - django

I am trying to make a carousel that you can upload pictures to. However, when I click on the upload button, It switches to another page, rather than giving me just the upload selection panel as Intended. Can anyone tell me why this might be?
Views.py
from django.shortcuts import render
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from webportal.views.authentication import LoginForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.conf import settings
from webportal.forms.forms import DocumentForm
from webportal.models import Document
is_server = True
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('webportal.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
#documents=DocumentForm().
# Render list page with the documents and the form
return render_to_response(
'webportal/carousel.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
Carousel.html
{% load staticfiles %}
{% load filename %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<div class="carousel-inner" role="listbox">
{% for document in documents %}
<div class="item {% if forloop.first %} active {% endif %}">
<div class="row">
<div class="col">
<img src = "{{STATIC_URL}}img" >
</div>
</div>
</div>
{% endfor %}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- /.carousel -->
</div>
</div>
<form action="{% url 'webportal:list' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</div>
Forms:
class DocumentForm(forms.Form):
docfile = forms.ImageField(label='Select a file', help_text='max. 42 megabytes')
Models:
class Document(models.Model):
docfile = models.ImageField(upload_to='webportal/static/img/')

I'm not sure what you mean by "just the upload selection panel as Intended".
Firstly, I see a problem by you returning an empty form if the submitted form is invalid, you should rather return the existing form and show the errors.
Your form, upon clicking the upload button will send a POST request to your server and your view generates a whole new HTML page as a response. HTTP is stateless, meaning that whatever your browser showed before is basically no longer of relevance. So naturally you will see a new page.

Related

Django- Template not found

I can't seem to get my delete, edit and add review functionality working. The errors come as soon as I try to navigate to the urls I have set up. When I try and add a new review using my link on the reviews page I get the below message:
TemplateDoesNotExist at /reviews/add
I don't understand why because I have linked the url above to the template, which I have created.
The issue I have with my edit/delete views is that the url it searches for when I click the button is just /edit/ or /delete/ rather than reviews/edit/int:pk or reviews/delete/int:pk as per my urls.
I have pasted my code below, any help would be much appreciated! I have the feeling I am going to kick myself when I realise!
reviews.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created }}</p>
<p>Last Updated: {{ review.updated }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="edit/{{ review.id }}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="delete/{{ review.id }}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'home:add_review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
add_review.html:
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{{ review_form }}
{% csrf_token %}
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
</div>
</div>
{% endblock %}
views.py:
from django.shortcuts import render
from django.views import View
from django.urls import reverse_lazy
from django.views.generic import UpdateView, DeleteView
from .models import Reviews
from .forms import ReviewForm
def home(request):
''' Returns the home page.'''
return render(request, 'home/index.html')
def reviews(request):
''' Returns the reviews page.'''
serialized_reviews = []
reviews = Reviews.objects.all()
for review in reviews:
serialized_reviews.append({
"title": review.title,
"content": review.content,
"user": review.user,
"created": review.created,
"updated": review.updated,
})
context = {
"reviews": serialized_reviews
}
print(serialized_reviews)
return render(request, 'home/reviews.html', context)
class AddReview(View):
'''View which allows the user to add a new review.'''
def get(self, request, *args, **kwargs):
review = Reviews
review_form = ReviewForm
context = {
'review': review,
'review_form': review_form,
'user': review.user,
'title': review.title,
'content': review.content,
}
return render(request, 'add_review.html', context)
def post(self, request, *args, **kwargs):
review_form = ReviewForm(data=request.POST)
if review_form.is_valid():
obj = review_form.save(commit=False)
obj.user = request.user
obj.save()
return redirect("home:reviews")
class DeleteReview(DeleteView):
'''View which allows the user to delete the selected review.'''
model = Reviews
template_name = 'delete_review.html'
success_url = reverse_lazy('reviews')
class EditReview(UpdateView):
'''View which allows the user to edit the selected review.'''
model = Reviews
template_name = 'edit_review.html'
fields = ['title', 'content']
urls.py:
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.home, name='home'),
path('reviews', views.reviews, name='reviews'),
path('reviews/add', views.AddReview.as_view(), name='add_review'),
path('reviews/delete/<int:pk>', views.DeleteReview.as_view(), name='delete_review'),
path('reviews/edit/<int:pk>', views.EditReview.as_view(), name='edit_review'),
]
The main difference is my app name, which is 'core'. Also, I forgot to add the content field to the model, but that is easily done, the form will just handle it as soon as you do the migration. (except on list.html)
models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
class Reviews(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
title = models.CharField(max_length=128)
created_at = models.DateTimeField(auto_now_add=timezone.now())
updated_at = models.DateTimeField(auto_now=timezone.now())
forms.py
from django import forms
from core.models import Reviews
class ReviewsForm(forms.ModelForm):
class Meta:
model = Reviews
fields = '__all__'
views.py
from core.models import Reviews
from core.forms import ReviewsForm
from django.shortcuts import render, redirect
def list_reviews(request):
reviews = Reviews.objects.all()
context = {
"reviews": reviews
}
return render(request, 'reviews/list.html', context)
def add_review(request):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
form.save()
return redirect('/reviews/')
else:
form = ReviewsForm()
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def edit_review(request, pk):
if request.method == 'POST':
form = ReviewsForm(request.POST)
if form.is_valid():
obj = Reviews.objects.get(id=pk)
obj.title = form.cleaned_data['title']
obj.user = form.cleaned_data['user']
obj.save()
return redirect('/reviews/')
else:
obj = Reviews.objects.get(id=pk)
form = ReviewsForm(instance=obj)
context = {
'form': form
}
return render(request, 'reviews/detail.html', context)
def delete_review(request, pk):
obj = Reviews.objects.get(id=pk)
obj.delete()
return redirect('/reviews/')
urls.py
from django.urls import path
import core.views as views
app_name = 'core'
urlpatterns = [
path('reviews/', views.list_reviews, name='list-reviews'),
path('reviews/add', views.add_review, name='add-review'),
path('reviews/edit/<int:pk>/', views.edit_review, name='edit-review'),
path('reviews/delete/<int:pk>/', views.delete_review, name='delete-review'),
]
list.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid home-container">
<div class="row align-items-center">
<div class="col-sm-12 text-center mt-4">
<h2><strong>Reviews</strong></h2>
</div>
</div>
{% for review in reviews %}
<hr class="hr-1">
<div class="row featurette">
<div class="col-sm-12">
<h2 class="featurette-heading">{{ review.title }}</h2>
<p class="lead">{{ review.content }}</p>
<div class="row justify-content-between mx-1">
<p>By: {{ review.user }}</p>
<p>Created on: {{ review.created_at }}</p>
<p>Last Updated: {{ review.updated_at }}</p>
</div>
<!-- Add user authentication if -->
<div class="text-center">
<a href="{% url 'core:edit-review' pk=review.id %}" class="mx-2">
<button class="positive-button mb-2">Edit</button></a>
<a href="{% url 'core:delete-review' pk=review.id %}" class="mx-2 mb-2">
<button class="negative-button">Delete</button></a>
</div>
</div>
</div>
{% endfor %}
<div class="row">
<div class="col-sm-12 text-center py-4">
{% if user.is_authenticated %}
<a href="{% url 'core:add-review' %}">
<button class="positive-button-lg">Add a review</button>
</a>
{% else %}
<p>If you would like to add your own review, please login or sign up if you haven't already!</p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
detail.html
{% extends "base.html" %}
{% load static %}
{% block content %}
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-auto text-center p-3">
<form method="post" style="margin-top: 1.3em;">
{% csrf_token %}
<table>
{{ form }}
</table>
<button type="submit" class="btn btn-primary btn-lg">Save</button>
</form>
</div>
</div>
{% endblock %}
According to your urls, It is a review/edit/<int:pk>.
So you must add same thing in href tag.
Change this:
<a href="edit/{{ review.id }}"
To this:
<a href="review/edit/{{ review.id }}"
That's why you are getting that error
I've fixed it, firstly the path in my add_review view was wrong, which I have amended and it now works (thanks Ivan).
I also was not actually bringing the ID through on my 'reviews' view in the first place, so when following the links on my edit and review buttons, it didn't know what I meant by 'id', as I hadn't specified what that was in the view context.
Thanks for the help all!
I think you're writing in your urls the wrong way, like this below your div text-center:
<a href="edit/{{ review.id }}" class="mx-2">
It should be:
<a href="{% url 'yourappname:edit' review.id %}">

How do I upload Image using Bootstrap Card and Django for loop?

I am trying to upload image. I used Django for loop and inside it placed Bootstrap Card.
I have added the code of models.py and views.py:
The problem I am facing is that the images are not appearing on the browser while rest of the details such as name and price is loading perfecting.
Products
{% for product in products %}
<div class="row">
<div class="column">
<div class="card" style="width: 18rem;">
<img src="{{product.image_url}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.name}}</h5>
<p class="card-text">${{product.price}}</p>
ORDER NOW
</div>
</div>
</div>
</div>
<ul>
{% endfor %}
`enter code here:
models.py
from django.db import models
class zoho(models.Model):
name= models.CharField(max_length=255)
price=models.FloatField()
stock=models.IntegerField()
imageurl=models.CharField(max_length=300)
`
enter code here
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import zoho
def index(request):
products= zoho.objects.all()
return render(request, 'index.html', {'products': products})
{% for product in products %}
.....
<img src="{{product.image.url}}" alt="Product Image" class="img-fluid">
.......
......
{% endfor %}
<form enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{form | crispy}}
<input type="submit" class="btn btn-success btn-sm mr-3 mb-2 px-3 py-1" value="Save" />
.....
</form>
image_url = models.ImageField(upload_to ='upload_profile_to')enter code here
In your models.py, you're saving the image link to imageurl and not image.url as you're currently calling it in the for loop block.
So, correct the way you called the variable in the for loop block

Django messages not showing up on redirects, only render

For a couple days now, I've been trying to figure out why my messages don't show up on redirects. All of the dependencies are there in my settings.py file as you can see. I don't think that's the problem because I am getting two messages to show up on signup and login if the user's passwords don't match on signup or if the user enters the wrong password on login. I notice it only works on renders, but not on redirects. I'll post an image of my file structure and also the relevant files next.
File structure images:
settings.py
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
INSTALLED_APPS = [
...
'django.contrib.messages',
...
]
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
'django.contrib.messages.middleware.MessageMiddleware',
...
]
TEMPLATES = [
...
'context_processors': [
...
'django.contrib.messages.context_processors.messages',
],
},
},
]
My urls.py in the main virtual_library folder
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from book.views import *
urlpatterns = [
path('admin/', admin.site.urls),
# Book paths
path('', include('book.urls')),
# Added Django authentication system after adding members app
path('members/', include('django.contrib.auth.urls')),
path('members/', include('members.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My urls.py in the book folder
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from .views import *
from book import views
urlpatterns = [
# Default path
path('', views.home, name='home'),
# Book paths
path('create/', views.createbook, name='createbook'),
path('current/', views.currentbooks, name='currentbooks'),
path('wanttoread/', views.wanttoreadbooks, name='wanttoreadbooks'),
path('currentlyreading/', views.currentlyreading, name='currentlyreading'),
path('read/', views.read, name='read'),
path('book/<int:book_pk>', views.viewbook, name='viewbook'),
path('book/<int:book_pk>/editbook', views.editbook, name='editbook'),
path('book/<int:book_pk>/viewonly', views.viewonly, name='viewonly'),
path('book/<int:book_pk>/delete', views.deletebook, name='deletebook'),
# Genres
path('genre/', AddGenreView.as_view(), name='addgenre'),
]
My urls.py in the members folder
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.contrib.auth import views as auth_views
from django.conf.urls.static import static
from members import views
from . import views
from .views import UserEditView, CreateProfilePageView, ShowProfilePageView, EditProfilePageView, PasswordsChangeView
urlpatterns = [
# User auth
path('signupuser/', views.signupuser, name='signupuser'),
path('loginuser/', views.loginuser, name='loginuser'),
path('logoutuser/', views.logoutuser, name='logoutuser'),
# User settings
path('edit_settings/', UserEditView.as_view(), name='edit_settings'),
# path('password/', auth_views.PasswordChangeView.as_view(template_name='registration/change_password.html')),
path('password/', PasswordsChangeView.as_view(template_name='registration/change_password.html')),
path('password_success/', views.password_success, name="password_success"),
# User profile
path('create_profile_page/', CreateProfilePageView.as_view(), name='create_profile_page'),
path('<int:pk>/edit_profile_page/', EditProfilePageView.as_view(), name='edit_profile_page'),
path('<int:pk>/profile/', ShowProfilePageView.as_view(), name='show_profile_page'),
]
base.html in the book folder
<div class="container mt-5">
{% for message in messages %}
<div class="container-fluid p-0">
<div class="alert {{ message.tags }} alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button> {{ message }}
</div>
</div>
{% endfor %} {% block content %}{% endblock %}
</div>
my currentbooks.html template to view user's books in the book folder
{% extends "book/base.html" %} {% load static %} { % block title % } Your Books { % endblock % } {% block content %}
<div class="row justify-content-center mt-5">
<div class="col-md-10">
<h1>{% if book_list %} {{ book_list.count }} total book{{ book_list.count|pluralize }} in your Mibrary...</h1>
</div>
</div>
<div class="row justify-content-center mt-5">
<div class="col-md-10">
{% if page_obj %}
<div class="container mt-1">
{% for book in page_obj %}
<div class="card-body">
{% if book.book_img %}
<img src="{{ book.book_img.url }}" alt="{{ book.title }}" class="img-fluid" style="height:150px; width:100px"> {% else %}
<img src="{% static 'book/images/logo.png' %}" alt="{{ book.title }}" class="img-fluid" style="height:150px; width:100px"> {% endif %}
<blockquote class="blockquote mt-3">
<a href="{% url 'viewonly' book.id %}">
<strong><p class="mb-0">{{ book.title|capfirst }}</p></strong>
</a>
<p class="mb-0">{% if book.summary %}{{ book.summary|truncatechars:80|safe }}{% endif %}</p>
</blockquote>
<footer class="blockquote-footer">by <cite title="Source Title">{{ book.author }}</cite></footer>
<small><p class="mb-0"><em>{{ book.user }}</em></p></small>
</div>
<hr> {% endfor %}
<div class="pagination">
<span class="step-links mr-2">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current mr-2">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
</span> {% if page_obj.has_next %}
next
last » {% endif %}
</span>
</div>
</div>
{% endif %} {% else %}
<div class="row">
<div class="col mt-5">
<a role="button" class="btn btn-outline-primary btn-lg" href="{% url 'createbook' %}">Add book</a>
</div>
<div class="col">
<h2>You haven't added any books yet...</h2>
<br>
<img src="../static/book/images/reading-list.svg" class="img-fluid mt-3" style="width:400px;" alt="Responsive image" title="stack of books">
</div>
</div>
</div>
{% endif %} {% endblock %}
views.py for currentbooks
from django.contrib import messages
...
#login_required
def currentbooks(request):
book_list = Book.objects.filter(user=request.user)
paginator = Paginator(book_list, 2)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(request, 'book/currentbooks.html', {'page_obj': page_obj, 'book_list': book_list})
my createbook.html to add books in the book folder
{% extends 'book/base.html' %} {% block title %} Add Book{% endblock %} {% block content %}
<div class="container mt-5">
<h1>Create Book...</h1>
</div>
<div class="form-group mt-3">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %} {{ error }} {{ form.media }} {{ form.as_p }}
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-outline-warning" onclick="$('#cancel').click()">Cancel</button>
</form>
<form style='display: none;' method="POST" action="{% url 'currentbooks' %}">
{% csrf_token %}
<button id="cancel" type="submit">Cancel</button>
</form>
</form>
</div>
{% endblock %}
My editbook.html view to delete in the book folder
{% extends "book/base.html" %} {% block title %} Edit Book {% endblock %} {% block content %} {% if user.id == book.user_id %}
<div class="container mt-5">
<h1>Edit Book...</h1>
{% if error %}
<div class="alert alert-danger" role="alert">
{{ error }}
</div>
{% endif %}
</div>
<div class="form-group mt-3">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %} {{ form.media }} {{ form.as_p }}
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-warning" onclick="$('#cancel').click()">Cancel</button>
<button type="button" class="btn btn-danger" onclick="$('#delete').click()">Delete</button>
</form>
<form style='display: none;' method="POST" action="{% url 'deletebook' book.id %}">
{% csrf_token %}
<button id="delete" type="submit">Delete</button>
</form>
<form style='display: none;' method="POST" action="{% url 'currentbooks' %}">
{% csrf_token %}
<button id="cancel" type="submit">Cancel</button>
</form>
</div>
{% else %}
<div class="row justify-content-center mt-5">
<h1>You are not allowed to edit this book...</h1>
</div>
{% endif %} {% endblock %}
views.py in the book folder
from django.contrib import messages
...
# Create
#login_required
def createbook(request):
if request.method == 'GET':
form = BookForm()
return render(request, 'book/createbook.html', {'form': form})
else:
try:
form = BookForm(request.POST, request.FILES)
newbook = form.save(commit=False)
newbook.user = request.user
if form.is_valid():
newbook.save()
# This message does not show up under the redirect
messages.success(request, 'Book saved!')
return redirect('currentbooks')
except ValueError:
messages.error(request, 'Bad data passed in. Try again.')
return render(request, 'book/createbook.html', {'form':BookForm()})
# Delete
#login_required
def deletebook(request, book_pk):
book = get_object_or_404(Book, pk=book_pk, user=request.user)
if request.method == 'POST':
book.delete()
# This message does not show up under redirect
messages.info(request, 'Book deleted!')
return redirect('currentbooks')
My loginuser.html to login in the members folder
{% extends 'book/base.html' %} {% block title %} Login {% endblock %} {% block content %}
<div class="container">
<h1>User Login...</h1>
<div class="row">
<div class="col mt-5">
<form method="POST">
<div class="form-group">
{% csrf_token %} {{ error }}
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" aria-describedby="usernameHelp">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control" id="password">
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-outline-danger btn-lg">Sign In</button>
</div>
</form>
</div>
<div class="col">
<img src="../../static/book/images/studying.svg" class="img-fluid" alt="Responsive image" title="woman reading II">
</div>
</div>
</div>
{% endblock %}
views.py in the members folder
from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect
...
from django.contrib import messages
...
# Auth functions
def signupuser(request):
if request.method == 'GET':
return render(request, 'registration/signupuser.html', {'form':UserCreationForm()})
else:
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.create_user(request.POST['username'], password=request.POST['password1'])
user.save()
login(request, user)
# This message does not show in the redirect
messages.success(request, 'User successfully created.')
return redirect('currentbooks')
except IntegrityError:
return render(request, 'registration/signupuser.html', {'form':UserCreationForm()})
else:
# This message does show up under render
messages.error(request, 'Passwords do not match.')
return render(request, 'registration/signupuser.html', {'form':UserCreationForm()})
def loginuser(request):
if request.method == 'GET':
return render(request, 'registration/loginuser.html', {'form':AuthenticationForm()})
else:
user = authenticate(request, username=request.POST['username'], password=request.POST['password'])
if user is None:
messages.error(request, 'Username and password do not match.')
# This message does show up under render
return render(request, 'registration/loginuser.html', {'form':AuthenticationForm()})
else:
login(request, user)
# This message does not show up under redirect
messages.success(request, 'Logged in successfully.')
return redirect('currentbooks')
#login_required
def logoutuser(request):
if request.method == 'POST':
logout(request)
# This message does not show up. I tried HttpResponseRedirect as a last option.
messages.success(request, 'Logged out successfully!')
return HttpResponseRedirect(reverse_lazy('loginuser'))
So ultimately, the messages don't seem to work with redirects, but they do work if I render and declare the folder and template name. Otherwise, no message displays if there is a redirect. I'm not quite sure what is wrong or why redirects are not working with these messages.
Matt Gleason's answer is incorrect, because messages framework doesn't store it in request object: https://docs.djangoproject.com/en/3.2/ref/contrib/messages/#storage-backends
Messages do work with redirects just fine out of the box. Check if everything is OK with your cookies (it's a default storage)

How load to Django Paginator Page (next/ previous)?

Hy,
i followed a tutorial for a multiple model search and it worked. now i want to paginate the output. But how can i load my paginator page (next/ previous) data into my template? So far if i push next i get an error.
views.py
from django.views.generic import TemplateView, ListView
from django.views.generic import View
from django.shortcuts import render
from django.db.models import Q
from django.core.paginator import Paginator
from itertools import chain
# --- Import Models
from datainput.models import Animal
from datainput.models import Farmer
<....>
class SearchView(ListView):
template_name = 'farmapi/searchview.html'
paginate_by = 2
count = 0
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['count'] = self.count or 0
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
farmer_results = Farmer.objects.search(query)
animal_results = Animal.objects.search(query)
# combine querysets
queryset_chain = chain(
farmer_results,
animal_results
)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
self.count = len(qs) # since qs is actually a list
return qs
return Farmer.objects.none() # just an empty queryset as default
template.html
{% extends 'base.html' %}
{% load class_name %}
{% load static %}
{% block custom_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}">
{% endblock %}
{% block content %}
<div style="height: 10px;">
</div>
<div class="container-fluid">
<div class='row'>
<div class="col-4 offset-md-8">
<form method='GET' class='' action='.'>
<div class="input-group form-group-no-border mx-auto" style="margin-bottom: 0px; font-size: 32px;">
<span class="input-group-addon cfe-nav" style='color:#000'>
<i class="fa fa-search" aria-hidden="true"></i>
</span>
<input type="text" name="q" data-toggle="popover" data-placement="bottom" data-content="Press enter to search" class="form-control cfe-nav mt-0 py-3" placeholder="Search..." value="" style="" data-original-title="" title="" autofocus="autofocus">
</div>
</form>
</div>
</div>
</div>
<div style="height: 10px;">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-6 offset-md-4">
{% for object in object_list %}
{% with object|class_name as klass %}
{% if klass == 'Farmer' %}
<div class='row'>
Farmer: <a href='{{ object.get_absolute_url }}'> {{ object.first_name }} {{ object.last_name }}</a>
</div>
{% elif klass == 'Animal' %}
<div class='row'>
Animal: <a href='{{ object.get_absolute_url }}'> {{ object.name }} {{ object.species }}</a>
</div>
{% else %}
<div class='row'>
<a href='{{ object.get_absolute_url }}'>{{ object }} | {{ object|class_name }}</a>
</div>
{% endif %}
{% endwith %}
{% empty %}
{% endfor %}
<div style="height: 10px;">
</div>
<div class='row'>
<results>{{ count }} results for <b>{{ query }}</b></results>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<!-- Pagniator Data -->
<div class="paginator">
<span class="step-links">
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_previous %}
« first
previous
{% endif %}
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
{% endblock %}
if i my template shows me for instance "4 Results for xyz" and "Page 1 of 2" and i push next or last Page, then i get this Error Message:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/data/searchview/?page=2 Raised by:
farmapi.views.SearchView
Invalid page (2): That page contains no results
So as far as i understand i have to explicit paginate the return of my queryset so that the paginator will put it into? Or did i miss to set a request for the paginator?
I also use a paginator where the number of items per page can be defined by the user. I added following method:
def get_paginate_by(self, queryset):
limit = int(self.request.POST.get('limit', 25))
return limit
In the template it looks like:
{% if is_paginated %}
{{ page_obj|render_paginator }}
{% endif %}
where render_paginator a template tag is.
In your template call a url like: your_url?page=2

Django Check boxes and progress bar

I'm new to Django a few week or two in to learning.
Django Ver 1.11
Python Ver 2.7
I'm making a Todo app in Django and I'm done with the application, but I want to add some extra features to it.
1. Sub tasks Checkbox that update the progress bar on the main page
2. and after the progress bar has reached 100% the status changes to done of the task.
I've made the login, registration, logout, adding new tasks and deleting the ones that are complete to my app so far.
here is the code
Models.
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class To_DO_Fun(models.Model):
Task_Name = models.CharField(max_length=20, default='')
Task_Text = models.TextField(max_length=45, default='')
Task_Done = models.BooleanField(default=False)
owner = models.ForeignKey(User)
def __str__(self):
return self.Task_Name + ' is ' + str(self.Task_Done) + ' by ' + str(self.owner)
forms
from .models import To_DO_Fun
from django import forms
class Form_todo(forms.ModelForm):
class Meta:
model = To_DO_Fun
fields = ['Task_Name','Task_Done']
class Form_Task(forms.ModelForm):
class Meta:
model = To_DO_Fun
exclude = ['Task_Name','Task_Done', 'owner']
fields = ['Task_Text']
views
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from .models import To_DO_Fun #Class Name
from .forms import Form_todo, Form_Task #Form Name
from django.contrib import messages
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import JsonResponse
def HomeFun(request): #To view contents of the home page
return render(request, "ToDo_Files/HomePage.html")
#login_required(login_url='Login-Page')
def Display_Page(request):
if request.user.is_superuser:
all_items = To_DO_Fun.objects.all()
else:
all_items = To_DO_Fun.objects.filter(owner = request.user)
context = {'all_items':all_items}
if request.method == "POST":
obj_todo = To_DO_Fun()
obj_todo.Task_Name = request.POST.get('Task_Name')
obj_todo.owner_id = request.POST.get('owner_id')
obj_todo.save()
context = {'all_items': all_items}
messages.success(request, ("Good Luck."))
return render(request,'ToDo_Files/Display_Page.html',context )
else:
return render(request , 'ToDo_Files/Display_Page.html', context)
return render(request,'ToDo_Files/Display_Page.html',context )
#login_required(login_url='Login-Page')
def remove(request, To_DO_Fun_id):
if request.user.is_superuser:
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.delete()
messages.success(request, ('Task Deleted.'))
return redirect('Display-Page')
else:
return redirect('Logout-Page')
#login_required(login_url='Login-Page')
def data(request, To_DO_Fun_id):
if request.method == "POST":
item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
form = Form_Task(request.POST, instance= item_all)
if form.is_valid():
form.save()
messages.success(request, ("Task Updated."))
return redirect('Display-Page')
else:
item_all = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
return render(request, 'ToDo_Files/details.html', {'item_all' : item_all})
return redirect('Display-Page')
#login_required(login_url='Login-Page')
def Done_status(request, To_DO_Fun_id):
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.Task_Done = True
item.save()
messages.success(request, ("Congratulations."))
return redirect('Display-Page')
#login_required
def Pen_status(request, To_DO_Fun_id):
item = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
item.Task_Done = False
item.save()
return redirect('Display-Page')
# def change_status(request, To_DO_Fun_id):
# Task_Done = request.GET.get('active', False)
# To_DO_Fun_id = request.GET.get('To_DO_Fun_id', False)
# # first you get your Job model
# task = To_DO_Fun.objects.get(pk=To_DO_Fun_id)
# try:
# task.Task_Done = Task_Done
# task.save()
# return JsonResponse({"Success": True})
# except Exception as e:
# return JsonResponse({"success": False})
# return JsonResponse('Display-Page')
def Reg_Fun(request):
if request.method == "POST":
UserReg_Form = UserCreationForm(request.POST)
if UserReg_Form.is_valid():
UserReg_Form.save()
return redirect('Login-Page')
else:
messages.error(request, ('USERNAME TAKEN'))
return redirect('Reg-Page')
else:
UserReg_Form = UserCreationForm(request.POST)
return render(request, "ToDo_Files/reg.html", {'UserReg_Form':UserReg_Form})
return redirect('Login-Page')
html for main page
{% extends 'ToDo_Files/base.html' %}
{% block asd %}
<title>Task</title>
{% if messages %}
<br>
{% for msg in messages%}
<div class="alert alert-info alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<h4>☀</h4>
</button>
{{ msg }}
</div>
{% endfor %}
{% endif %}
<br>
<center><h5>WORK HARD <br> <i>{{ user.username }}</i></h5>
{% if all_items %}
<div>
<br>
{% if request.user.is_superuser %}
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th><center><font color='#218838'>Task Name </font></center></th>
<th><center><font color='#218838'>Task Completion </font></center></th>
<th><center><font color='#218838'>Task Details </font></center></th>
<th><center><font color='#218838'>Task Author </font></center></th>
<th><center><font color='#218838'>Task Done </font></center></th>
</tr>
</thead>
{% for some in all_items %}
{% if some.Task_Done %}
<tr class="table-Success">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Pen' some.id %}'>Task Done</a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center> <strong>{{ some.owner }} </strong></center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% else %}
<tr class="table-default">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Done' some.id %}'>Task Pending </a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center> <strong>{{ some.owner }} </strong></center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% endif %}
{% endfor %}
</table>
{% else %}
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th><center><font color='#218838'>Task Name </font></center></th>
<th><center><font color='#218838'>Task Completion </font></center></th>
<th><center><font color='#218838'>Task Details </font></center></th>
<th><center><font color='#218838'>Task Done </font></center></th>
</tr>
</thead>
{% for some in all_items %}
{% if some.Task_Done %}
<tr class="table-Success">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Pen' some.id %}'>Task Done</a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% else %}
<tr class="table-default">
<td><center> <strong>{{ some.Task_Name }} </strong></center></td>
<td><center><a href='{% url 'Task-Done' some.id %}'>Task Pending </a></center></td>
<td><a href='{% url 'Task-Data' some.id %}'><center>Details </center></td>
<td><center><a href='{% url 'Del-Page' some.id %}'>Remove</a></center></td>
</tr>
{% endif %}
{% endfor %}
{% endif %}
</div>
{% endif %}
{% endblock %}
Base.html
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<style>
body {
background-color:#fffff7;
}
</style>
<body >
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href='{% url 'Display-Page' %}'>Django</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!----><!----><!----><!---->
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href='{% url 'Home-Page' %}'>Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href='{% url 'Logout-Page' %}'>Logout<span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input type="hidden" name="owner_id" value="{{request.user.id}}">
<input class="form-control mr-sm-2" type="search"placeholder="Add TO-DO" aria-label="Search" name="Task_Name">
<button class="btn btn-success my-2 my-sm-0" type="submit" >Add TODO</button>
</form>
</div>
</nav>
<div class="container">
{% block asd %}
{% endblock %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
html for the subtask
{% extends 'ToDo_Files/base.html' %}
{% block asd %}
<title>Task Details</title>
{% if item_all %}
<form class="form-inline my-2 my-lg-0" method="POST" action="">
{% csrf_token %}
<br> <br>
<input class="form-control mr-sm-2" placeholder='Subtask' aria-label="Search" name="subTask">
<br>
<button class="btn btn-success my-2 my-sm-2" type="submit" >Add</button>
</form>
<br><br><br>
{% endif %}
{% endblock %}
urls
from django.conf.urls import url
from . import views
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^(?i)Home/', views.HomeFun, name='Home-Page'),
url(r'^(?i)Display/', views.Display_Page, name='Display-Page'),
url(r'^(?i)delete/(?P<To_DO_Fun_id>\d+)/$', views.remove, name='Del-Page'),
url(r'^(?i)details/(?P<To_DO_Fun_id>\d+)/$', views.data, name='Task-Data'),
url(r'^(?i)registraion/', views.Reg_Fun, name='Reg-Page'),
url(r'^(?i)login/', auth_views.LoginView.as_view(template_name='ToDo_Files/login.html'), name='Login-Page'),
url(r'^(?i)logout/', auth_views.LogoutView.as_view(template_name='ToDo_Files/logout.html'), name='Logout-Page'),
url(r'^(?i)Done/(?P<To_DO_Fun_id>\d+)/$', views.Done_status, name='Task-Done'),
url(r'^(?i)Pending/(?P<To_DO_Fun_id>\d+)/$', views.Pen_status, name='Task-Pen'),
]
I want to see a progress bar on the main page that shows how much % the task is done after comparing or getting input from the sub task checkbox.
also that I am able to add and remove new sub tasks in the sub tasks page where I can check the and uncheck any sub task.
Thank you in advance