I try to run this code but I get this error
NoReverseMatch at /
Reverse for 'all-posts' not found. 'all-posts' is not a valid view function or pattern name.
and I think my code is okay, here's a bit of it
My urls.py
from django.urls import path
from . import views
app_name = "blog"
urlpatterns = [
path("", views.index, name="home"),
path("all_posts", views.all_posts, name="all-posts"),
path("<str:tag>", views.sort_post, name="sorted")
]
here's my views.py
from django.shortcuts import render
from .models import Auhtor, Post, Caption
def index(request):
return render(request, "blog/index.html")
def all_posts(request):
all = Post.objects.all()
return render(request, "blog/all.html", {"all": all})
def sort_post(request, tag):
sort = Post.objects.filter(tag__caption=tag)
return render(request, "blog/sorted.html", {"sorted": sort})
and here's my all.html
{% extends "blog/base.html" %}
{% load static %}
{% block title %}
My Blog
{% endblock %}
{% block content %}
<div class="nav">
<ul>
All posts
</ul>
</div>
{% endblock %}
Related
i am struggling with this error, please any help,
i tried many solution for this error but nothing work
views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,Http404
from .models import Board
# Create your views here.
def home(request):
boards = Board.objects.all()
return render(request,'home.html',{'boards':boards})
def board_topics(request,board_id):
# try:
# board = Board.objects.get(pk=board_id)
# except:
# raise Http404
board = get_object_or_404(Board,pk=board_id)
return render(request,'topics.html',{'board':board})
def new_topic(request,board_id):
return render(request,'new_topic.html')
def about(request):
return HttpResponse(request,'yes')
url.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('about/',views.about,name='about'),
path('boards/<int:board_id>/', views.board_topics, name='board_topics'),
path('boards/<int:board_id>/new/', views.new_topic, name='new_topic')
]
new_topic.html
{% extends 'base.html' %}
{% block title %} creat new topic {% endblock %}
{% block breadcrumb %}
<li class="breadcrumb-item"> Boards </li>
<li class="breadcrumb-item"> {{board.name}} </li>
<li class="breadcrumb-item active">New Topic</li>
{% endblock %}
Usually I could easily read where the error is coming from and deal with it but in this case I can't spot the cause of the error hence I'm unable to progress with my study. Any help will be greatly appreciated.
You have to tell it what board_id is, since that's what you have in your URL.
<li class="breadcrumb-item"> {{board.name}} </li>
I'm trying to make a simple app that uses the django built-in User model. I have created a registration page, but when I run the server, I get this error at the index page. Here's the code I'm using:
Registration.html
<!DOCTYPE html>
{% extends "basic/base.html" %}
{% block title_block %}
<title>Registration</title>
{% endblock title_block %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registering</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form: </h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{userForm.as_p}}
{{profileForm.as_p}}
<input type="submit" value="Register" name="">
</form>
{% endif %}
</div>
{% endblock body_block %}
Views.py for the 'register' method
def register(request):
registered = False
if(request.method == 'POST'):
userForm = forms.UserForm(data=request.POST)
profileForm = forms.UserProfileInfoForm(data=request.POST)
if((userForm.is_valid()) and (profileForm.id_valid())):
user = userForm.save()
user.set_password(user.password)
user.save()
profile = profileForm.save(commit=False)
profile.user = user
if('profileImage' in request.FILES):
profile.profileImage = request.FILES['profileImage']
profile.save()
registered = True
else:
print(userForm.errors, profileForm.errors)
else:
userForm = forms.UserForm()
profileForm = forms.UserProfileInfoForm()
return render(request, 'basic/registration.html', {'userForm':userForm, 'profileForm':profileForm, 'registered':registered})
This is the urls.py for the project
from django.contrib import admin
from django.urls import path, include
from basic import views
urlpatterns = [
path('', views.index, name='index'),
path('admin/', admin.site.urls),
path('basic/', include('basic.urls', namespace='basic'))
]
This is the urls.py for the basic app
from django.urls import path
from . import views
app_name = 'basic'
urlpatterns = [
path('register/', views.register)
]
And the link to the page in base.html
<a class="nav-link" href="{% url 'basic:register' %}">Register</a>
What can cause the error here?
You must include a name argument to the register route.
path('register/', views.register, name='register')
https://docs.djangoproject.com/en/2.1/topics/http/urls/#reverse-resolution-of-urls
try this (inside your html file)
<a class="nav-link" href={% url 'basic:register' %}>Register</a>
and your urls.py (inside your app) as this:
urlpatterns = [
path('register/', views.register,name='register'),
]
this method worked for me I was fasing the same issue.
My question: why i am not able to view search only ayan rand's book with classbased list view?
this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine.
But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted .
Views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect
from django.views.generic import TemplateView,ListView,DetailView
def store_listView(request,):
queryset=Book.objects.all()
context={
"objects_list":queryset
}
return render(request,'bookstores/store.html',context)
class SearchBookDetail(ListView):
template_name = "bookstores/store.html"
queryset = Book.objects.filter(author__icontains='Ayan Rand')
print("Ayan Rand query set", queryset)
Urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.views.generic import TemplateView
from store.views import (Home,ContactView,LoginView,
store_listView,
SearchBookDetail,
book_createview,
QuoteslistView,
AyanRandBookDetail,
quotesFunctionView)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',Home.as_view()),
url(r'^contact/$',ContactView.as_view()),
url(r'^login/$',LoginView.as_view()),
url(r'^store/$',store_listView),
url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()),
url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()),
url(r'^quotes/$',quotesFunctionView)]
store.html:
{% extends "home.html" %}
{% block head_title %}Store || {{ block.super }} {% endblock head_title %}
{% block content %}
<head>
<meta charset="UTF-8">
<title>Store</title>
</head>
<h6>Books available</h6>
<ul>
{% for obj in objects_list %}
<li>{{obj}}<br>
{{obj.book_image}} <br>
{{obj.description}} <br>
{{obj.author}}<br>
{{obj.genre}}<br>
{{obj.price}}<br>
</li>
{% endfor %}
</ul>
{% endblock content %}
ListView sends its data to the template as object_list, not objects_list.
I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django
I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django