Django Url NoReverseMatch at issue - django

I don't know why I am getting this issue with my code. I've tried a bunch of stuff to resolve it but I can't
NoReverseMatch at /property/
Reverse for 'property_detail' not found. 'property_detail' is not a valid view function or pattern name.
Request Method:GETRequest URL:http://127.0.0.1:8000/property/Django Version:3.0.5Exception Type:NoReverseMatchException Value:
Reverse for 'property_detail' not found. 'property_detail' is not a valid view function or pattern name.
Exception Location:E:\django_projects\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677Python Executable:E:\django_projects\env\Scripts\python.exePython Version:3.7.4Python Path:
['E:\\django_projects\\hotel\\src\\project',
'E:\\django_projects\\env\\Scripts\\python37.zip',
'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\DLLs',
'c:\\users\\user\\appdata\\local\\programs\\python\\python37\\lib',
'c:\\users\\user\\appdata\\local\\programs\\python\\python37',
'E:\\django_projects\\env',
'E:\\django_projects\\env\\lib\\site-packages']
html code
<ul class="probootstrap-main-nav">
<li class="active">Home</li>
<li>Properties</li>
<li>Agents</li>
<li>About</li>
<li>Contact</li>
</ul>
project/urls (project directory)
urlpatterns = [
path('admin/', admin.site.urls),
path('property/', include('property.urls', namespace='property')),
path('agents/', include('agents.urls', namespace='agents')),
path('about/', include('about.urls', namespace='about')),
path('contact/', include('contact.urls', namespace='contact')),
]
propert/urls (app)
from django.urls import path
from . import views
app_name= 'property'
urlpatterns = [
path('', views.property_list, name='property_list'),
path('<int:id>', views.property_detail, name='property_detail'),
]
property/views
from django.shortcuts import render
from .models import (Property, Category)
from .forms import ReserveForm
def property_list(request):
property_list = Property.objects.all()
template = 'list.html'
context = {
'property_list': property_list,
}
return render(request, template, context)
def property_detail(request, id):
property_detail = Property.objects.get(id=id)
if request.method == 'POST':
reserve_form = ReserveForm(request.POST)
if reserve_form.is_valid():
reserve_form.save()
else:
reserve_form = ReserveForm()
return render(request, 'detail.html', {
'property_detail': property_detail,
'reserve_form': reserve_form
})

Related

Django Sitemap is not working gives error "Reverse for 'index' not found. 'index' is not a valid view function or pattern name."

I'm trying to implement a Sitemap for my app and I get the error
"Reverse for 'index' not found. 'index' is not a valid view function or pattern name."
even though these views are set up.
What could cause this? I have no problem with dynamic sitemaps, just the static one.
My views.py
def front_page(request):
return render(request, 'django_modules_testing_app/front_page.html', {})
def about_us(request):
return render(request, 'ihgr_app/about_us.html', {})
def index(request):
return render(request, 'django_modules_testing_app/index.html', {})
urls.py
from django.urls import path
from . import views
from . import blocks
from django.contrib.sitemaps.views import sitemap
from .sitemaps import DjangoModulesTestingApp
app_name = 'django_modules_testing_app'
sitemaps = {
'main_app':DjangoModulesTestingApp
}
urlpatterns = [
path('', views.front_page, name='front_page'),
path('', views.index, name='index'),
path('', views.about_us, name='about_us'),
path('category_details/<slug:slug>/', blocks.category_details, name='category_details'),
path('search_website/', views.SearchWebsite.as_view(), name='search_website'),
path('sitemap.xml', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap')
]
sitemaps.py
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
class StaticSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
protocol = 'http'
def items(self):
return ['front_page','index','about_us']
def location(self, item):
return reverse(item)
You've to specify your app name inside reverse(...) like this
class StaticSitemap(Sitemap):
changefreq = 'weekly'
priority = 0.8
protocol = 'http'
def items(self):
return ['front_page','index','about_us']
def location(self, item):
return reverse(f"django_modules_testing_app:{item}")

Django NoReverseMatch at http://127.0.0.1:8000/boards/1/new/

This is my site urls:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('boards.urls'))
]
And this is my app urls:
urlpatterns = [
path('',views.home,name='home'),
path('boards/<int:pk>',views.board_topic,name='board_topic'),
path('boards/<int:pk>/new/',views.new,name='new_topic')
]
This is the Views for app:
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):
board = Board.objects.all()
return render(request,'home.html',{
'board':board,
})
def board_topic(request,pk):
# try:
# board = Board.objects.get(pk=pk)
# except:
# raise Http404
board = get_object_or_404(Board,pk=pk)
return render(request,'topics.html',{
'board':board
})
def new(request,pk):
boards = get_object_or_404(Board, pk=pk)
return render(request, 'new_topic.html', {
'board' : boards
})
when I try to go to http://127.0.0.1:8000/boards/1/new/ then this error occurs:
enter image description here
please help me.
Here's how I was able to get rid of my error
In my app's url:
urlpatterns = [
path('',views.home,name='home'),
path('boards/<int:pk>',views.board_topic,name='board_topic'),
path('boards/<int:pk>/new/',views.new,name='new_topic')
]
In the second path I was using name= 'board_topic'
and in my templates file i was using url as href = ' url "board.pk board_topics" '
so that was why i was getting that error .
THANK YOU TO EVERYONE WHO RESPONDED

How do I fix the NoReverseMatch Django error?

I am trying to complete a CS50 Project, I want to render a HTML page, the template is in respective templates/encyclopedia directory.
The error page for url 127.0.0.1:8000/wiki/HTML says NoReverseMatch at wiki/HTML.
Reverse for 'edit' not found. 'edit' is not a valid view function or pattern name.
The responsible URLS.py are "wiki/<str:search>" and "wiki/random".
I'm sorry but I don't want to post this long code here but I am stuck at this problem for weeks now.
I have tried many ways don't know what's wrong with this code.
The below is my URLS.py, the projects index url includes the below urls:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/newpage", views.newpage, name="newpage"),
# path("wiki/<str:edit>/edit", views.edit, name="edit"),
path("wiki/random", views.random, name="random"),
path("wiki/<str:search>", views.search, name="search"),
path("wiki/", views.find, name="find")
]
The below is my VIEWS.py:
from django.shortcuts import render, redirect
from django.contrib import messages
import markdown2 as md
from . import util
from django import forms
import re, random as rand
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def search(request, search):
if search in util.list_entries():
html = md.markdown(util.get_entry(search))
return render(request, "encyclopedia/search.html", {
"search": search, "html": html
})
else:
return render(request, "encyclopedia/error.html")
def random(request):
randomPage = rand.choice(util.list_entries())
if randomPage in util.list_entries():
html = md.markdown(util.get_entry(randomPage))
return render(request, "encyclopedia/search.html", {
"random": randomPage, "html": html
})
else:
return render(request, "encyclopedia/error.html")
def find(request):
if request.method == "GET":
query = request.GET.get('q')
for queryMatch in util.list_entries():
if query.casefold() == queryMatch.casefold():
html = md.markdown(util.get_entry(query))
return render(request, "encyclopedia/search.html", {
"queryMatch": queryMatch, "html": html
})
regex = re.compile(query.casefold())
matchList = []
for a in util.list_entries():
if regex.match(a.casefold()):
matchList.append(a)
if not matchList:
matchList = util.list_entries()
return render(request, "encyclopedia/list.html", {
"match": matchList
})
class NewPageForm(forms.Form):
title = forms.CharField(label="Title")
content = forms.CharField(label="Markdown Content", widget=forms.Textarea(attrs={'cols': '100'}))
def newpage(request):
if request.method == "POST":
form = NewPageForm(request.POST)
if form.is_valid():
title = form.cleaned_data["title"]
content = form.cleaned_data["content"]
if title in util.list_entries():
messages.error(request, f"'{title}' page title already exists!!\nPlease type another title.")
return render(request, "encyclopedia/newpage.html", {
"form": form
})
else:
util.save_entry(title, content)
return redirect(f"/wiki/{title}")
else:
return render(request, "encyclopedia/newpage.html", {
"form": form
})
return render(request, "encyclopedia/newpage.html", {
"form": NewPageForm()
})
# def edit(request, edit):
# entry = util.get_entry(edit)
Have you include your app.urls in project.urls?
Including other URLconfs
Some example from Django tutorial:
polls/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]

NoReverseMatch pattern not found in django2

NoReverseMatch found for a url i have tried and
{% url '/feedback/form/' %}
i am using a feedback app.
#feedback\urls.py
from django.urls import path, include
from .views import request_feedback
urlpatterns = [
path('form/', request_feedback, name = 'get_feedback' ),
]
#feedback\views.py
def request_feedback(request):
if request.method == 'POST':
feedback_form = FeedBackForm(request.POST)
if feedback_form.is_valid():
feedback_form.save()
return redirect('')
else:
feedback_form = FeedBackForm()
return render(request, 'feedback/feedbackform.html', {'feedback_form':feedback_form})
#webapp\urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('feedback/', include("feedback.urls")),
path('user/',include("user.urls")),
]
i am getting this error
NoReverseMatch at /feedback/form/
Reverse for '' not found. '' is not a valid view function or pattern name
i am using python 3.7 and django 2
i do mitigate this problem

Download BinaryFiled Data

how to download BinaryField Data/file using template. like we did for FileField.
<td><a href={{certificate.bytes.url}} download></a>
I past all url.py and view.py file below please look This may give extract view of my code. and please help me with this i am new to Django. ............................................................................................................................................................
url.py
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.defaults import page_not_found
urlpatterns=[
path('',views.index, name = 'index'),
url(r'^list/$', views.list, name='list'),
url(r'^list/create$', views.certificate_create, name='certificate_create'),
url(r'^list/(?P<id>\d+)/update$', views.certificate_update, name='certificate_update'),
url(r'^list/(?P<id>\d+)/delete$', views.certificate_delete, name='certificate_delete'),
path('download',views.download, name = 'download'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So, we need Django models which contains BinaryField for example.
models.py
class Person(models.Model):
name = models.CharField(max_length=55)
surname = models.CharField(max_length=55)
image = models.BinaryField()
class Meta:
db_table = 'person'
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('download/<int:pk>/', views.download, name='download'),
]
views.py
import io
from django.shortcuts import render
from django.http import FileResponse
from .models import Person
def index(request):
# there are listed all models.
persons = Person.objects.all()
return render(request, 'index.html', {'persons': persons})
def download(request, pk):
# this url is for download
try:
obj = Person.objects.get(pk=pk)
except Person.DoesNotExist as exc:
return JsonResponse({'status_message': 'No Resource Found'})
get_binary = obj.image
if get_binary is None:
return JsonResponse({'status_message': 'Resource does not contian image'})
if isinstance(get_binary, memoryview):
binary_io = io.BytesIO(get_binary.tobytes())
else:
binary_io = io.BytesIO(get_binary)
response = FileResponse(binary_io)
response['Content-Type'] = 'application/x-binary'
response['Content-Disposition'] = 'attachment; filename="{}.png"'.format(pk) # You can set custom filename, which will be visible for clients.
return response
index.html
{% for person in persons %}
{{ person.name }}<br />
{% endfor %}
This is solution to send binary file from server and download. All components are shown. Good luck !