I am relatively new to Django and started to create my first To-Do-List.
However I get an error whenever I try to create an href that says: NoReverseMatch at /aufgabenzettel/
I have desperately tried to fix it for the last five hours and am very frustrated because the error just seems to be caused by a single line of code... Please help! It would be awesome and I really appreciate every hint!
Here's the code:
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("<int:aufgabenzettel_id>", views.details, name="details")
]
views.py
from django.shortcuts import render
from .models import Aufgabenzettel
# Create your views here.
def index(request):
return render(request, "aufgabenzettel/index.html", {
"Aufgabenliste":Aufgabenzettel.objects.all()
})
def details(request, aufgabenzettel_id):
aufgabenzettel = Aufgabenzettel.objects.get(pk=aufgabenzettel_id)
return render(request, "aufgabenzettel/details.html", {
"details":aufgabenzettel
})
models.py
from django.db import models
# Create your models here.
class Aufgabenzettel(models.Model):
Aufgabeselbst = models.CharField(max_length=64)
def __str__(self):
return f"{self.Aufgabeselbst}"
layout.html
<!DOCTYPE html>
<html lang="de">
<head>
<title>Aufgabenzettel</title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
index.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1>Meine Aufgaben</h1>
<ul>
{% for Aufgabeselbst in Aufgabenliste %}
<li>
<a href="{% url 'details' aufgabenzettel.id %}">
Aufgabe {{ Aufgabeselbst }}
</a>
</li>
{% endfor %}
</ul>
{% endblock %}
details.html
{% extends "aufgabenzettel/layout.html" %}
{% block body %}
<h1> Aufgabe {{ details }}</h1>
Zurück zu Aufgabe
{% endblock %}
The exact error:
Reverse for 'details' with arguments '('',)' not found. 1 pattern(s) tried: ['aufgabenzettel/(?P<aufgabenzettel_id>[0-9]+)$']
Whenever I delete the line <a href="{% url 'details' aufgabenzettel.id %}"> in index.html the programme works perfectly fine...
Let me know if you need some more information!!
I really appreciate your help!
Related
i am trying to display image from db with views and in the inspact broswer i see it find my image but still return me 404 error. my models.py:
class HomePhoto(models.Model):
title = models.CharField(max_length=100)
img = models.ImageField(upload_to='home_page_images/')
view.py:
def index(request):
data = HomePhoto.objects.all()
return render(request, 'home.html',{'data':data,})
html:
{% for d in data %}
<img src="{{d.img}}" alt="Third slide">
{% endfor %}
url.py:
urlpatterns = [
path('',views.index,name='index')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
the html in the broswer inspact:
<img src="home_page_images/orangeshirt_1ZrO8ay.jpg" alt="Third slide"> <!--THIS IS THE RIGHT PATH AND THE RIGHT NAME OF THE IMAGE-->
You are forgetting about accessing the url member:
{% for d in data %}
<img src="{{d.img.url}}" alt="Third slide">
{% endfor %}
{% for d in data %}
<img src="{{d.img.url}}" alt="Third slide">
{% endfor %}
you need to add url: d.img.url
Try this:
{% load static %}
<img src="{% static 'my_app/example.jpg' %}" alt="My image">
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.
Im really lost about this, im trying to understand a django inheritance template about
I have a layout with a navbar and html structure:
todos/templates/todos/layout.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<title>Practice Django</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark justify-content-between">
<div>
<a class="navbar-brand" href="/">Django app</a>
Page 1
Page 2
</div>
<form action="" class="form-inline">
<input
type="search"
placeholder="Search Todo"
aria-label="Search"
class="form-control mr-sm-2"
/>
<button type="submit" class="btn btn-outline-success my-2 my-sm-0">
Search
</button>
</form>
</nav>
<div class="container">
{% block content %} {% endblock %}
</div>
</body>
</html>
then im trying to setup a index page with a grid, a column for show todos and the another one for create a new todo.
todos/templates/todos/base.html
{% block content %}
<h1 class="text-center">Base Page</h1>
<div class="row">
<div class="col">
{% block todolist %}
{% include 'todos/todos_list.html' %}
{% endblock %}
</div>
<div class="col">
{% block addtodo %}
{% include 'todos/add_todo.html' %}
{% endblock %}
</div>
</div>
{% endblock %}
todos/templates/todos/add_todo.html
{% extends 'todos/base.html' %}
{% block addtodo %}
<h3 class="text-center">subpage addtodo</h3>
{% endblock %}
todos/templates/todos/todos_list.html
{% extends 'todos/base.html' %}
{% block todolist %}
<h3 class="text-center">subpage todolist</h3>
{% endblock %}
For try to understand it, i made a same classes for both views, todo_list and add_todo from different class sources.
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader
from django.views.generic import ListView, DetailView
from .models import Todo
class TodoList(ListView):
template_name = 'todos/todos_list.html'
context_object_name= 'todos'
# Lo que devuelve esta funcion se añade al context object name
def get_queryset(self):
return Todo.objects.all()
class AddTodo(ListView):
template_name = 'todos/add_todo.html'
context_object_name= 'todos'
# Lo que devuelve esta funcion se añade al context object name
def get_queryset(self):
return Todo.objects.all()
My urls.py i guess, to show both classes in index pages, the same route url
from django.urls import path
from . import views
urlpatterns = [
path('', views.TodoList.as_view(), name='todolist'),
path('', views.AddTodo.as_view(), name='addtodo')
]
But this does not work, with this error:
RecursionError at /
maximum recursion depth exceeded while calling a Python object
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 3.1.1
Exception Type: RecursionError
Exception Value:
maximum recursion depth exceeded while calling a Python object
Exception Location: /home/adrian/.local/lib/python3.8/site-packages/django/utils/functional.py, line 241, in inner
Python Executable: /usr/bin/python3
Python Version: 3.8.2
Python Path:
['/home/adrian/code/python/practice',
'/usr/lib/python38.zip',
'/usr/lib/python3.8',
'/usr/lib/python3.8/lib-dynload',
'/home/adrian/.local/lib/python3.8/site-packages',
'/usr/local/lib/python3.8/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Thu, 24 Sep 2020 16:43:24 +0000
I was thinking to make both operations (show todo list and add a new todo form) with the same class, but i dont know how do it that properly, the object its show a both classes, templates in the same route, in this case in root /.
Any clues about? thanks in advance
You should not use {% include %}, since then you end up with infinite recursion. You can for example make a base:
{% block content %}
<h1 class="text-center">Base Page</h1>
<div class="row">
<div class="col">
{% block items %}
{% endblock %}
</div>
<div class="col">
{% block otheritems %}
{% endblock %}
</div>
</div>
{% endblock %}
If you later use {% extend … %} [Django-doc], it means you take the entire template of the one your refer to, but for the blocks you specify and the "child template", you render another value. So your child can look for example as:
{% extends 'todos/base.html' %}
{% block items %}
<h3 class="text-center">subpage addtodo</h3>
{% endblock %}
{% extends 'todos/base.html' %}
{% block items %}
<h3 class="text-center">subpage todolist</h3>
{% endblock %}
Here you will thus render the <h1 class=""> part in the child templates. The only thing that will differ is that the part in the block {% block items %} … {% endblock %} by the content you provide.
Here it however looks like you want two views to provide content for the same page. That is not how it works. A view is the logic that maps a request to a response. A view does not per se renders a template, nor does it only renders maximum one template. A view can render as much templates as you want.
If you thus want a single page with two items to fill in, you make a view, that renders for example a template that fills in the two blocks. So we thus define a single URL pattern for this path:
from django.urls import path
from . import views
urlpatterns = [
path('', views.TodoList.as_view(), name='add_todo'),
]
and in the view, we allow one to also access the list of todos:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader
from django.views.generic import ListView, DetailView
from .models import Todo
class TodoList(CreateVieww):
template_name = 'todos/todos_list.html'
model = Todo
fields = '__all__'
def todos(self):
return Todo.objects.all()
in the template, we finally fill in two blocks: one with the Todos, and one with the form:
{% extends 'todos/base.html' %}
{% block items %}
{% for todo in view.todos %}
{{ todo }}
{% endfor %}
{% endblock %}
{% block otheritems %}
<form method="post" action="{% url 'add_todo' %}">
{{ form }}
</form>
{% endblock %}
I'm new in Django. My problem is when I click the title which is in a.html, it's directing me to this URL; http://localhost:8000/aba/R%C3%BCyada%20Aba%20G%C3%B6rmek
in this URL I'm getting an error message; Page not found 404
Here is I wanna do; When I click the title, I wanna show my article details dynamically
dreamarticle/urls.py
from django.contrib import admin
from django.urls import path, re_path
from dreamarticle import views
app_name = "Dreamarticle"
urlpatterns = [
re_path('/aba/(.*?)/',views.aba,name="aba"),
path('a/',views.a,name="a"),
]
blog/urls.py
from django.contrib import admin
from django.urls import path,include
from article import views
from dreamarticle import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name="index"),
path('articles/',include("article.urls")),
path('user/',include("user.urls")),
path('dreamarticle/',include("dreamarticle.urls")),
]
dreamarticle/views.py
def aba(request, title):
context = dict()
context.update(
dreamarticlesaba=get_object_or_404(dreamarticle, title=title),
)
return render(request, "aba.html", context)
aba.html
{% extends "layout.html" %}
{% block body%}
<!-- Content here -->
<br>
<div class="container">
<div class="row">
{% if dreamarticlesaba %}
{% for dreamarticle in dreamarticlesaba %}
<div class="col-md-12 dreamdetail">
<h1>{{dreamarticle.title}}</h1>
<hr>
<p>{{dreamarticle.content|safe|escape}}<p>
</div>
{% endfor %}
{% endif %}
</div>
</div>
a.html
{% extends "layout.html" %}
{% block body%}
{% include "includes/searchbar.html" %}
<!-- Content here -->
<br>
<div class="container">
<div class="row">
{% if dreamarticles %}
{% for dreamarticle in dreamarticles %}
<div class="col-md-4 text-center bg-primary">
<br><b>{{dreamarticle.title}}</b>
<b>{{dreamarticle.title}}</b>
</a>
</div>
{% endfor %}
{% endif %}
</div>
</div>
{% endblock body%}
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/aba/R%C3%BCyada%20Aba%20G%C3%B6rmek
Using the URLconf defined in blog.urls, Django tried these URL patterns, in this order:
admin/
[name='index']
articles/
user/
dreamarticle/
The current path, aba/Rüyada Aba Görmek, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
I am new to Django and I am practicing template inheritance. I am currently having trouble inheriting templates on the 3rd level. The base level is a template that my whole site uses (ex: navbars). The second level is the content of my site. However this content is a bit lengthy so I took a portion(contactform.html) of it and created its own HTML file for that portion.
I am able to get my home.html into my index.html like so
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head lang="en">
<link href="{% static "css/boothie.css" %}" rel="stylesheet" type="text/css">
<script src="{% static "js/boothie.js" %}"></script>
<script src="{% static "js/jquery.easing.1.3.js" %}"></script>
<title>Boothie</title>
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
Within my home.html I want to include my contactform.html. This is what I have so far.
{% extends "index/index.html" %}
{% load staticfiles %}
{% block content %}
...
...
...stuff...
<!-- contact -->
{% block contactform %}{% endblock %}
{% endblock %}
My contactform.html:
{% extends "home/home.html" %}
{% load staticfiles %}
{% block contactform %}
<section id="contact">
<!-- HTML! -->
</section>
{% endblock %}
This is what is currently in my home/views.py:
from django.shortcuts import render
from django.views import generic
class HomeView(generic.TemplateView):
template_name = "home/home.html"
my home/urls.py:
from django.conf.urls import patterns, url
from home.views import HomeView
urlpatterns = patterns('',
url(r'^$', HomeView.as_view(), name="home"),
)
TEMPLATE_DIRS:
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
os.path.join(BASE_DIR, 'home'),
)
here is a picture of my project structure:
Instead of inheriting, just include the contactform template in the home template. In home/home.html put:
<section id="contact">
{% include 'home/contactform.html' %}
</section>
You dont need to extend, instead include
Example, keep the contents of the contact_form.html with just the required html content (without the extends, and the block tag, etc..), and then include the html snippet. Now, django would do the magic for you - The included snippet would have all the context variables too.
{% extends ".." %}
{% load staticfiles %}
{% block content %}
...
...
...stuff...
{% include /path/to/contactform.html %}
{% endblock %}