Keep getting Server Error - 500 - python

Every time I request a blog post on my website, I receive a server error 500. I have been trying to debug it for the past 3 days, and I have not been able to figure out what is going on. Here is the views.py for the blog detail:
def blog_detail():
post = Post.objects.get(request_post)
try:
Next_Post_id = (post.id + 1)
Next_Post = Post.objects.get(id=Next_Post_id)
Next_Post = Next_Post.id
except ObjectDoesNotExist:
Next_Post = None
# Previous Post
try:
Previous_Post_id = (post.id - 1)
Previous_Post = Post.objects.get(id=Previous_Post_id)
Previous_Post = Previous_Post.id
except ObjectDoesNotExist:
Previous_Post = None
context = {'post': post, 'Next_Post': Next_Post, 'Previous_Post': Previous_Post}
return render(request, "BlogHome/pages/post.html", context)
and here is the post.html template:
{% extends "BlogHome/includes/WELL.html" %}
{% block content %}
<script>
document.title = "Pike Dzurny | {{post.title}}"
</script>
<div class="container-fluid text-center">
<center>
<div class="well" id="WellPost">
<div class="container-fluid">
<h2 align="center" id="TitleText">{{post.title}}</h2>
<h3 align="center" id="BodyText">{{ post.date|date:"m-d"}}</h3>
<h3 align="left">{{ post.body|safe }}</h3>
{% if post.id == 1 %}
<ul class="pager">
<li class="previous disabled"><a href="/blog/{{ Previous_Post.id }}"><span
aria-hidden="true">←</span> Older</a></li>
<li class="next "><a href="/blog/{{ Next_Post.id }}">Newer <span
aria-hidden="true">→</span></a></li>
<h1>hi 1</h1>
</ul>
{% if Next_Post is defined %}
<ul class="pager">
<li class="previous disabled"><span aria-hidden="true">←</span> Older</li>
<li class="next">Newer <span aria-hidden="true">→</span>
</li>
</ul>
<h1>2</h1>
{% Previous_Post is defined %}
<ul class="pager">
<li class="previous"><a href="/blog/{{ Previous_Post.id }}"><span aria-hidden="true">←</span>
Older</a></li>
<li class="next disabled">Newer <span aria-hidden="true">→</span></li>
</ul>
<h1>3</h1>
{% else %}
<ul class="pager">
<li class="previous disabled"><span aria-hidden="true">←</span> Older</li>
<li class="next disabled">Newer <span aria-hidden="true">→</span></li>
</ul>
<h1>4</h1>
{% endif %}
</div>
<div class="container-fluid">
</div>
</center>
</div>
{% endblock %}
Post is the model that contains the blog post. I have not been able to find the reasong why when I request a blog page it throws an error. Does anyone know why?

I figured out what happened. After #Tnerual's comment, I checked my urls.py and realized request_post wasn't defined.

Related

Pagination in Django ListView when using get_context_data

I am currently facing this problem with Django ListView. Basically, I need to filter some questions per topic and I would like to paginate the results.
My code is working perfectly about the queryset part (the results are showed correctly) but I am facing a problem with pagination.
Let's say I have so far 8 items in my query, if I choose to paginate_by = 10, it shows me just one page. If, otherwise, I choose to paginate by, let's say, 3, it shows me 3 pages to choose in the template (which is correct) but it shows me ALL the results of the query in my page.
I post some code to be more clear
models.py:
class Tag(models.Model):
name = models.CharField(max_length=300, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def clean(self):
self.name = self.name.capitalize()
def __str__(self):
return self.name
class Question(models.Model):
post_owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=5000, default='')
body = tinymce_models.HTMLField()
tags = models.ManyToManyField(
Tag, related_name='tags')
viewers = models.ManyToManyField(
User, related_name='viewed_posts', blank=True)
views.py:
class TagQuestionsListView(ListView):
template_name = 'main/tag_questions.html'
paginate_by = 20
def get_queryset(self, **kwargs):
tag = Tag.objects.get(name=self.kwargs['name'])
questions = Question.objects.filter(tags=tag)
return questions
def get_contextdata(self, **kwargs):
context = super().get_context_data(**kwargs)
context['tag'] = Tag.objects.get(name=self.kwargs['name'])
context['questions'] = Question.objects.filter(
tags=context['tag'], is_deleted=False)
return context
template:
{% extends 'base.html' %}
{% load humanize %}
{% block title %}Domande su {{tag.name}}{% endblock title %}
{% block content %}
<style>
.text {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2; /* number of lines to show */
line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>
<div class="card">
<div class="mt-3">
<h3 class="ms-2" style="display: inline;">Ultime {{ questions.count }} Domande</h3>
{% if request.user.is_authenticated %}
Fai una domanda
{% else %}
Fai una domanda
{% endif %}
</div>
<h5 class="ms-2">{{ total_questions.count }} domande totali </h5>
<hr>
{% for question in questions %}
<div class="row">
<div class="col-2 ms-2">
<p>{{ question.count_all_the_votes }} Voti</p>
<p>{{ question.count_answers }} Risposte</p>
<p>{{ question.calculate_viewers }} Visualizzazioni</p>
</div>
<div class="col-9">
<h5>{{question.title}}</h5>
<div class="text">
{{ question.body|striptags }}
</div>
{% for tag in question.tags.all %}
<a class="btn btn-sm btn-outline-primary m-1" href="{% url 'main:tag_questions' name=tag.name %}">{{tag.name}}</a>
{% endfor %}
<div class="float-end">
<a style="display: inline;" href="">{{question.post_owner}}</a>
{% if question.is_edited == False %}
<span style="display:inline;">creata {{question.created_at | naturaltime}}</span>
{% else %}
<span style="display:inline;"> modificata {{question.edited_time | naturaltime}} da <a style="display: inline;" href="">{{question.edited_by.username}}</a></span>
{% endif %}
</div>
</div>
</div>
<hr>
{% endfor %}
</div>
<div class="row mt-3">
<div class="col-lg-12">
<div class="card">
<div class="card-body">
<nav aria-label="Page navigation example">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="{% url 'main:tag_questions' name=tag.name %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.previous_page_number }}">Precedente</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">Precedente</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li class="page-item {% if page_obj.number == i%} active {% endif %} %} "><a class="page-link" href="?filter={{ filter }}&orderby={{ orderby }}&page={{ i }}">{{i}}</a></li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="{% url 'main:tag_questions' name=tag.name %}?filter={{ filter }}&orderby={{ orderby }}&page={{ page_obj.next_page_number }}">Prossima</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">Prossima</a></li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>
{% endblock content %}
With this I want my comment converter to answer.
You have to use page_obj instead questions in your template.
<--! ⬇️⬇️⬇️ -->
{% for question in page_obj %}
<div class="row">
<div class="col-2 ms-2">
<p>{{ question.count_all_the_votes }} Voti</p>
<p>{{ question.count_answers }} Risposte</p>
<p>{{ question.calculate_viewers }} Visualizzazioni</p>
</div>
<div class="col-9">
<h5>{{question.title}}</h5>
<div class="text">
{{ question.body|striptags }}
</div>
{% for tag in question.tags.all %}
<a class="btn btn-sm btn-outline-primary m-1" href="{% url 'main:tag_questions' name=tag.name %}">{{tag.name}}</a>
{% endfor %}
<div class="float-end">
<a style="display: inline;" href="">{{question.post_owner}}</a>
{% if question.is_edited == False %}
<span style="display:inline;">creata {{question.created_at | naturaltime}}</span>
{% else %}
<span style="display:inline;"> modificata {{question.edited_time | naturaltime}} da <a style="display: inline;" href="">{{question.edited_by.username}}</a></span>
{% endif %}
</div>
</div>
</div>
<hr>
{% endfor %}
So, if you define attribute paginate_by , than ListView(django docs) adds a paginator and page_obj to the context. To allow the users to navigate between pages, add links to the next and previous page, in your template.

How to use Django URL field?

I have an URL field in Django to which I am adding the URL of a photo, how can I render this image to the frontend of my website.
models.py file code for reference
class Place(models.Model):
place_photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
place_photo_1 = models.ImageField(upload_to='photos/%Y/%m/%d/')
place_photo_2 = models.ImageField(upload_to='photos/%Y/%m/%d/')
place_photo_3 = models.ImageField(upload_to='photos/%Y/%m/%d/')
place_photo_4 = models.ImageField(upload_to='photos/%Y/%m/%d/')
field_name = models.URLField(max_length=500,default='add photo url')
def __str__(self):
return self.place_title
This is my template.html code
<div class="placebox-overlap-wrapper">
<div class="overlap-box">
<div class="overlap-btns-area">
<div class="car-magnify-gallery">
<a href="{{place.place_photo.url}}" class="overlap-btn">
<i class="fa fa-expand"></i>
<img class="hidden" src="{{place.place_photo.url}}">
</a>
{% if place.place_photo_1 %}
<a href="{{place.place_photo_1.url}}" class="hidden"
data-sub-html="<h4>{{place.place_title}}</h4><p>{{place.story1}}</p>">
<img class="hidden" src="{{place.place_photo_1.url}}">
</a>
{% endif %}
{% if place.place_photo_2 %}
<a href="{{place.place_photo_2.url}}" class="hidden"
data-sub-html="<h4>{{place.place_title}}</h4><p>{{place.story2}}</p>">
<img class="hidden" src="{{place.place_photo_2.url}}">
</a>
{% endif %}
{% if place.place_photo_3 %}
<a href="{{place.place_photo_3.url}}" class="hidden"
data-sub-html="<h4>{{place.place_title}}</h4><p>{{place.story3}}</p>">
<img class="hidden" src="{{place.place_photo_3.url}}">
</a>
{% endif %}
{% if place.place_photo_4 %}
<a href="{{place.place_photo_4.url}}" class="hidden"
data-sub-html="<h4>{{place.place_title}}</h4><p>{{place.story4}}</p>">
<img class="hidden" src="{{place.place_photo_4.url}}">
</a>
{% endif %}
{% if place.place_photo_5 %}
<a href="{{place.place_photo_5.url}}" class="hidden"
data-sub-html="<h4>{{place.place_title}}</h4><p>{{place.story5}}</p>">
<img class="hidden" src="{{place.place_photo_5.url}}">
</a>
{% endif %}
{% if place.field_name %}
<a href="{{place.field_name}}" class="hidden"
data-sub-html="<h4>{{place.place_title}}</h4><p>{{place.story5}}</p>">
<img class="hidden" src="{{place.field_name}}">
</a>
{% endif %}
</div>
</div>
</div>
</div>
This is my: Admin file reference
Showing 5 images to the frontend: frontend part of the website
Problem part : Not showing URL part image
This is my view.py
def place(request):
places = Place.objects.order_by('-added_date')
paginator = Paginator(places,9)
page = request.GET.get('page')
paged_places = paginator.get_page(page)
country_search = Place.objects.values_list('country',flat=True).distinct()
location_search = Place.objects.values_list('location',flat=True).distinct()
architecture_search = Place.objects.values_list('architecture',flat=True).distinct()
data = {
'places': paged_places,
'country_search':country_search,
'location_search': location_search,
'architecture_search': architecture_search,
}
return render(request,'place/place.html',data)
I am new to Django, so if I am doing any mistake then please help me out. It would be really appreciable

Django paginator issue

I am currently working on a django blog and I've coded a search bar where you type something and, if there's any post that contains what you've typed in the title, it should appear all the posts. This part is perfectly well-written. However, there's an error with the pagination. As you'll see in the views.py. The maximum num of posts per page is 3. However, you can see there's four. However, the paginator detects there should be another page for the fourth posts. Here's an image that shows that.
Here's the views.py:
class ElementSearchView(View):
elements_list = Element.objects.all()
def get(self, request, *args, **kwargs):
paginator = Paginator(self.elements_list, 3)
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
paginated_queryset = paginator.page(page)
except PageNotAnInteger:
paginated_queryset = paginator.page(1)
except EmptyPage:
paginated_queryset = paginator.page(paginator.num_pages)
queryset = Element.objects.all()
query = request.GET.get('q')
if query:
queryset = queryset.filter(
Q(title__icontains=query)
).distinct()
context = {
'query': queryset,
'queryset': paginated_queryset,
'page_request_var': page_request_var,
}
return render(request, 'periodic/search_results_table.html', context)
And here's the html template: The pagination is at the end of the template.
{% load static %}
<html>
{% include 'periodic/head_search.html' %}
<body>
{% include 'periodic/header.html' %}
<br>
<br>
<div class="container">
<div class="row">
<!-- Latest Posts -->
<main class="posts-listing col-lg-8">
<div class="container">
<div class="row">
<!-- post -->
{% for element in query %}
<div class="post col-xl-6 wrap-login100">
<div class="post-thumbnail"><img src="{{ element.thumbnail.url }}" alt="..." class="img-fluid"></div>
<div class="post-details">
<a href="{{ element.get_absolute_url }}">
<h3 class="h4">{{ element.title }}</h3></a>
</div>
</div>
{% endfor %}
</div>
<!-- Pagination -->
<nav aria-label="Page navigation example">
<ul class="pagination pagination-template d-flex justify-content-center">
{% if queryset.has_previous %}
<li class="page-item"> <i class="fa fa-angle-left"></i></li>
{% endif %}
<li class="page-item">{{ queryset.number }}</li>
{% if queryset.has_next %}
<li class="page-item"> <i class="fa fa-angle-right"></i></li>
{% endif %}
</ul>
</nav>
{% if is_paginated %}
<nav aria-label="Page navigation example">
<ul class="pagination pagination-template d-flex justify-content-center">
{% if page_obj.has_previous %}
<li class="page-item"> <i class="fa fa-angle-left"></i></li>
{% endif %}
<li class="page-item">{{ page_obj.number }}</li>
{% if page_obj.has_next %}
<li class="page-item"> <i class="fa fa-angle-right"></i></li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</main>
</body>
{% include 'periodic/scripts_search.html' %}
</html>
As the user #ikilnac mentioned,
you are looping over the original queryset and not the paged one in your template
That simply means that in your loop, you do this
{% for element in query %}
<div class="post col-xl-6 wrap-login100">
<div class="post-thumbnail"><img src="{{ element.thumbnail.url }}" alt="..." class="img-fluid"></div>
<div class="post-details">
<a href="{{ element.get_absolute_url }}">
<h3 class="h4">{{ element.title }}</h3></a>
</div>
</div>
{% endfor %}
And then after that, you are using the tag in the form of {% if queryset.has_previous %} with the original queryset rather than the paged one in the template (the query).
There's a good example of it here - Paginate with Django

Django change object details when button is clicked

Good evening!
I want to make two buttons, when one is clicked automatically change details of this object. I've already set to view two models but i don't know how to manage change only one post. Whether I should use template tag or try to use JS (which frankly I don't know how to use) Thanks for your replies!
views.py
class PostList(ListView):
template_name = 'post/index.html'
ordering = ['-date']
queryset = EveryPostPl.objects.all()
def get_context_data(self, **kwargs):
context = super(PostList, self).get_context_data(**kwargs)
context['EveryPostRu'] = EveryPostRu.objects.all()
context['EveryPostPl'] = self.queryset
return context
html
{% extends "post/base.html" %}
{% block title %}
<title>Home Page</title>
{% endblock title %}
{% block content %}
{% for obj in EveryPostPl %}
<div class="card text-center">
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs">
<li class="nav-item">
<a class="nav-link nav-main" href="#">PL</a>
</li>
<li class="nav-item">
<a class="nav-link nav-main" href="#">RU</a>
</li>
</ul>
</div>
<div class="card-body">
<h5 class="card-title">{{ obj.title }}</h5>
<p class="card-text">{{ obj.text|truncatechars:350 }}</p>
Zobacz
</div>
<div class="card-footer text-muted">
<span class="float-left">{{ obj.date|date:"d M y" }}</span>
<span class="float-right">Przesłane przez: {{ obj.User }}</span>
</div>
</div>
{% endfor %}
{% endblock content %}
enter image description here
This would work if you don't mind sending all the details to the client:
<html>
<head>
<title>JS Test</title>
<script>
function switch_to(elem_id) {
var content_divs = document.getElementsByClassName("content");
for(var i = 0; i < content_divs.length; i++){
content_divs[i].style.display = "none";
}
var elem = document.getElementById(elem_id);
elem.style.display = "block";
}
</script>
</head>
<body>
RU
PL
<div id="RU" class="content">
Some text about RU...
</div>
<div id="PL" class="content" style="display:none">
Some text about PL
</div>
</body>
</html>
(for whatever reason it won't run as a code snippet...)

How implement dynamic testimonials and carousel in django python

Im facing implementing the dynamic testimonials and carousel in django python, means i need to content in models that so present in front below i mention my code of implemetions
template.html
<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>
<!-- Wrapper for slides -->
<div class="carousel-inner">
{% for p in tests %}
{% if forloop.counter == 1 %}
<div class="item active">
{% else %}
<div class="item">
{% endif %}
<h3>{{ p.title }}</h3>
</div>`enter code here`
</div>
{% endfor %}
</div>
</div>
view.py
def home(request):
test=Testimonials.objects.all().order_by('id')[:13]
template = loader.get_template('hme/home.html')
context = {
'tests':test,
}
return HttpResponse(template.render(context, request))
I don't know what you really want to do, but your views.py can be rewrite as follows:
from django.shortcuts import render
def home(request):
tests = Testimonials.objects.order_by('id')[:13]
return render(request, 'hme/home.html', {'tests': tests})

Categories