Error during template rendering django - python

This is my code and I receive error on index page ** {% for post in posts %} Error during template renderingn template /home/elite/Downloads/django/FirstBlog/blog/templates/index.html, error at line 13
index.html
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”utf-8”>
<title>Awesome HTML5 Webpage</title>
<meta name=”description” content=”An awesome HTML5 page YOU built from scratch!”>
<meta name=”author” content=”Udemy”>
<link rel=”stylesheet” href=”style.css”>
</head>
<body>
<div class='cointainer'>
<h1>First Blog</h1>
{% for post in posts %} <<<<- This where error I get--
<h2>{{ post.tittle }}</h2>
<h3>Posted{{ post.timestamp }} by {{ post.author }}</h3>
<p>{{post.bodytext }} </p>
{% endfor %}
</div>
</body>
</html>
views page
from django.shortcuts import render
from blog.models import posts
def home(request):
entries = posts.objects.all()[:10]
return render(request, 'index.html',{'posts' : entries})
This is url page
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:l()
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'blog.views.home', name='home'),
)

Related

Unable to solve thisReverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']

I have a navbar in my template in which I am trying to add an active class, however, whenever I do such, I get this error:
NoReverseMatch at /
Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']
Exception Location: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix
Python Executable: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.2
Python Path:
['C:\\Users\\Abdullah\\Desktop\\Blog\\my_blog',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\Abdullah\\AppData\\Roaming\\Python\\Python39\\site-packages',
'C:\\Users\\Abdullah\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Wed, 21 Apr 2021 09:38:37 +0000
here is my base.html:
`{% load static %}
<!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.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="{% static 'css/base.css' %}">
<link rel="stylesheet" href="{% static 'css/posts.css' %}">
{% url 'posts' as posts %}
<nav>
<ul>
<li><a class="nav_a {% if request.path == posts %} active {% endif %}" href="{% url 'posts' %}">Blogs</a></li>
{% if request.user.is_authenticated %}
<li><a class="nav_a" href="{% url 'myposts' %}">Welcome {{ request.user }}</a></li>
<li><a class="nav_a" href="{% url 'post' %}">Post</a></li>
<li><a class="nav_a" href="{% url 'myposts' %}">My Posts</a></li>
<li><a class="nav_a" href="{% url 'logout' %}">Logout</a></li>
{% else %}
<li><a class="nav_a" href="{% url 'signup' %}">Signup</a></li>
<li><a class="nav_a" href="{% url 'login' %}">Login</a></li>
{% endif %}
</ul>
</nav>
<br>
<body>
{% block content %}
{% endblock %}
</body
</html>`
here is my urls.py:
`"""my_blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from blog_app import views
from django.contrib.auth import views as auth_views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.posts, name='posts'),
path('signup', views.signup, name="signup"),
path('login', auth_views.LoginView.as_view(template_name='blog_app/login.html'), name='login'),
path('logout', auth_views.LogoutView.as_view(template_name='blog_app/logout.html'), name='logout'),
path('post', views.post, name='post'),
path('myposts', views.myposts, name='myposts'),
path('delete_post/<int:id>', views.delete_post, name='delete_post'),
path('edit_post/<int:id>', views.edit_post, name='edit_post'),
path('read_post/<int:id>', views.read_post, name='read_post')
]`
posts views.py:
`def posts(request):
posts = Post.objects.all()
return render(request, 'blog_app/posts.html', {'posts': posts})
`
here is my blog_app/posts.html:
`{% extends 'blog_app/base.html' %}
{% block content %}
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% for post in posts %}
<div>
<h2>{{ post.title }}</h2>
<button>Read blog</button>
<h4>Posted by {{ post.author }} on {{ post.datetime }}</h4>
<br>
</div>
{% endfor %}
{% endblock %}`
models.py:
`from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import datetime
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(to=User, on_delete=models.CASCADE)
date_time = timezone.now()
# datetime = models.DateTimeField(auto=timezone.now)`
Also pls suggest way to add active link class as I am unable to do that.

NoReverseMatch: Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls\\/\\<int\\:question_id\\/\\>$']

I am following along Traversy Media's Django tutorial for the poll app and when I ran my code near the end I got the error stated in the title all of the sudden: why is detail not found?
views.py
from django.shortcuts import render
from .models import Question, Choice
# Get questions and display them
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
#Show specific question and choices
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/results.html', { 'question': question })
# Get questions and display results
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', { 'question': question })
urls.py(polls)
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id/>', views.detail, name='detail'),
path('<int:question_id/results/>', views.results, name='results'),
]
urls.py(pollster)
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
index.html
{% extends 'base.html' %}
{% block content %}
<h1 class="text-center mb-3">Poll Questions</h1>
{% if latest_question_list %}
{% for question in latest_question_list %}
<div class="card mb-3">
<div class="card-body">
<p class="lead">{{ question.question_text }}</p>
Vote Now
Results
</div>
</div>
{% endfor %}
{% else %}
<p>No polls available</p>
{% endif %}
{% endblock %}
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
crossorigin="anonymous"
/>
<title>Pollster {% block title %}{% endblock %}</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
{% block content %}{% endblock %}
</div>
</div>
</div>
</body>
</html>
Any insight would be much appreciated, I haven't been able to progress at all since I got stuck here. Thanks in advance!
You should not put slashes in the path converter parts of the paths:
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
]

Password reset not redirecting to template html file in django

I am trying to use a template html file for my password reset form. But it is not redirecting to my template file rather it is redirecting ti Django administration page. I don't want to use django administration page for resetting the password change link.
password_reset_form.html:
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="{% static 'employeeregistration/css/master.css' %}">
</head>
<body>
{% load bootstrap4 %}
<div class="container title">
<h2 style="text-align:center; padding-top:100px;">Reset your password</h2>
</div>
<div class="container">
<form method="POST" action="{% url 'password_reset' %}">
{% csrf_token %}
{{ form.as_p }}
{% buttons %}
<button type="submit" class="btn btn-primary">Send confirmation mail</button>
{% endbuttons %}
</form>
</div>
</body>
</html>
urls.py:
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'registration'
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name="registration/login.html"), name='login'),
path('password_reset/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset_form.html"), name='password_reset'),
# path('password_reset/password_reset_done/', auth_views.PasswordResetView.as_view(template_name="registration/password_reset_done.html"), name='password_reset_done'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('signup/', views.EmployeeSignUp.as_view(), name='signup'),
]
views.py:
from django.contrib.auth import login, logout
from django.contrib.auth.mixins import(LoginRequiredMixin,
PermissionRequiredMixin)
from django.views.generic import (TemplateView,ListView,
DetailView,CreateView,
UpdateView,DeleteView)
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import CreateView
from . import forms
class EmployeeSignUp(CreateView):
"""
Views for employee sign up
"""
form_class = forms.NewEmployeeRegistrationForm
success_url = reverse_lazy("login")
template_name = 'registration/signup.html'
class AdminView(TemplateView):
template_name = 'registration/admin.html'
project urls.py:
from django.contrib import admin
from django.urls import path, include
# from django.contrib.auth import views
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name='home'),
path('admin/', admin.site.urls),
path('about/', views.AboutView.as_view(), name='about'),
path('registration/', include("django.contrib.auth.urls")),
path('registration/', include('registration.urls', namespace='registration')),
# path('registration/password_reset', include('registration.urls', namespace='password_reset')),
# path('registration/password_reset_done', include('registration.urls', namespace='password_reset_done')),
]
Since you have specified a namespace, in the action attribute in password_reset_form.html, you have to first specify the name of the namespace the name of the view separated by a colon. You can find the appropriate documentation here
So you have to change password_reset_form.html to-
<!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<link rel="stylesheet" href="{% static 'employeeregistration/css/master.css' %}">
</head>
<body>
{% load bootstrap4 %}
<div class="container title">
<h2 style="text-align:center; padding-top:100px;">Reset your password</h2>
</div>
<div class="container">
<form method="POST" action="{% url 'registration:password_reset' %}">
{% csrf_token %}
{{ form.as_p }}
{% buttons %}
<button type="submit" class="btn btn-primary">Send confirmation mail</button>
{% endbuttons %}
</form>
</div>
</body>
</html>
Also you have two paths in your root project urls.py which lead to the same url. So consider changing it to
from django.contrib import admin
from django.urls import path, include
# from django.contrib.auth import views
from . import views
urlpatterns = [
path('', views.HomePage.as_view(), name='home'),
path('admin/', admin.site.urls),
path('about/', views.AboutView.as_view(), name='about'),
# path('registration/', include("django.contrib.auth.urls")),
path('registration/', include('registration.urls', namespace='registration')),
# path('registration/password_reset', include('registration.urls', namespace='password_reset')),
# path('registration/password_reset_done', include('registration.urls', namespace='password_reset_done')),
]
I have commented out one url pattern which might be causing the issue.

Django 2.0 - Not a valid view function or pattern name (Customizing Auth views)

I´m working on a course exercise and I'm stuck for a few hours and I'm not sure what is causing the app to break, next, you will find the files involved and perhaps you can find out the solution. Thanks for your help!
Project structure
This error is being thrown when I log in:
Internal Server Error: /account/login/
...
django.urls.exceptions.NoReverseMatch: Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name.
[04/Apr/2018 17:12:15] "POST /account/login/ HTTP/1.1" 500 151978
At the end of the settings.py file
from django.urls import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('dashboard')
LOGIN_URL = reverse_lazy('login')
LOGOUT_REDIRECT_URL = reverse_lazy('logout')
The urls.py file
from django.contrib.auth import views as auth_views
from django.urls import path
from . import views
app_name = 'account'
urlpatterns = [
# path('login/', views.user_login, name='login'),
path('', views.dashboard, name='dashboard'),
# login / logout urls
path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'),
path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'),
]
The views.py file
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import render
#login_required
def dashboard(request):
return render(request, 'account/dashboard.html', {'section': 'dashboard'})
The base.html template
{% load staticfiles %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="{% static "css/base.css" %}">
</head>
<body>
<div id="header">
<span class="logo">Bookmarks</span>
{% if request.user.is_authenticated %}
<ul class="menu">
<li> {% if section == "dashboard" %}class="selected"{% endif %}>My dashboard</li>
<li> {% if section == "images" %}class="selected"{% endif %}Images</li>
<li> {% if section == "people" %}class="selected"{% endif %}People</li>
</ul>
{% endif %}
<span class="user">
{% if request.user.is_authenticated %}
Hello {{ request.user.first_name }}, Logout
{% else %}
{% endif %}
</span>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
I appreciate your help. Thanks a lot!
You've set a namespace for your urls:
app_name = 'account'
You need to use that namespace when reversing urls with reverse/reverse_lazy or {% url %}:
LOGIN_REDIRECT_URL = reverse_lazy('account:dashboard')
LOGIN_URL = reverse_lazy('account:login')
LOGOUT_REDIRECT_URL = reverse_lazy('account:logout')
Perhaps when specifying {% url 'appname:views' %} you specified the wrong appname
For example, like:
wrong - {% url 'accuant:dashboard' %}
right - {% url 'account:dashboard' %}

Homepage in Django isn't working

I'm currently trying to create a homepage for Django, but when I test it, it just shows me a blank page with nothing on it. This is what I have so far. First is my URL page from mysite:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('firstapp.urls')),
]
and my url page from firstapp:
from django.conf.urls import url
from firstapp.views import HomePage
urlpatterns = [
url(r'^$', HomePage.as_view(), name='home'),
]
this is my views page:
from django.shortcuts import render
from django.views.generic import TemplateView
class HomePage(TemplateView):
template_name = 'home/home.html'
def home(request):
return render(request, self.template_name)
this is the base.html which extends to home.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel='stylesheet' href='{% static "css/base.css" %}'/>
</head>
<html>
<p>{{ variable }}</p>
<script src= '{% static "js/base.js" %}'></script>
</body>
</html>
And finally home.html itself.
{% extends 'base.html' %}
{% block body %}
<div class="container">
<p>Testing Home</p>
</div>
{% endblock %}
Now if it works, I should be seeing "Testing Home"...but...I see nothing. I just get an empty white page. Any idea why this is happening?
Your base.html doesn't have a {% block body %} defined anywhere in it. You need blocks to be defined in the template you're extending, otherwise you'll have nothing to override inside the extended template.
base.html
<html>
<body>
<p>{{ variable }}</p>
{% block body %}{% endblock %}
<script src= '{% static "js/base.js" %}'></script>
</body>
</html>
Note: I also fixed your opening <body> tag which you incorrectly had as <html>, leaving you with two <html> opening tags in your template.

Categories