I am trying to build a simple blog application on an ubuntu droplet hosted on digital ocean.
I have the DJango app in mid development and I am getting a No reverse match for a view that existes
Here is the error:
'NoReverseMatch at / Reverse for 'post_detail' not found. 'post_detail' is not a valid view function or pattern name.'
Here is my Url Patterns:
from . import views
urlpatterns = [
url(r'^$', views.post_list, name='post_list'),
url(r'^post/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
~
Here is My view
from django.shortcuts import render, get_object_or_404
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
~
Here is My nginx file:
server {
listen 80;
server_name XXX.XXX.XXX.XXX;
location = /favicon.ico { access_log off; log_not_found off; }
location /static/ {
root /home/XXXX/Django;
}
location / {
include proxy_params;
proxy_pass http://unix:/home/XXX/Django/BizBlog.sock;
}
}
Where is the error occurring? I can't figure this out, I have worked with Django before and know it has to do with the url searching for the string patterns in my view function and being unable to find it but the function is there. What is wrong?
Here is my main url.py:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'', include('blog.urls')),
]
Just stop the django development server process, restart the services waitress on windows/gunicorn on linux and nginx on windows/linux.
Related
I would like to redirect all 404 pages to a home page. I try this but it don't work
app/views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
def home(request): return HttpResponse('<h1> HOME </h1>')
def redirectPNF(request, exception): return redirect('home')
app/urls.py
from . import views
urlpatterns = [ path('home', views.home, name="home"), ]
app/settings.py
handler404 = 'app.views.redirectPNF'
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
DEBUG = False
Just Add this line in urls.py instead of settings.py
Everything else seems ok.
It is also mentioned in the django documentation that setting handler variables from anywhere else will have no effect. It has to be set from URLconf
The default error views in Django should suffice for most web applications, but can easily be overridden if you need any custom behavior. Specify the handlers as seen below in your URLconf (setting them anywhere else will have no effect).
app/urls.py
from . import views
handler404 = 'app.views.redirectPNF' # Added this line in URLconf instead of settings.py
urlpatterns = [ path('home', views.home, name="home"), ]
code of project named carparts urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('parts.urls')),
]
code for my app named parts urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index,name='index'),
path('about', views.about,name='about'),
path('contact', views.contact,name='contact'),
]
code for views.py
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
# return HttpResponse('this is home page')
def about(request):
return render(request, 'about.html')
def contact(request):
return render(request, 'contact.html')
index page code output is show in http://127.0.0.1:8000 but my about and contact page shows Page not found (404) . Can any one help me with this code.
Thank you
Joint '/' in your both urls.py like that:
urlpatterns = [
path('', views.index,name='index'),
path('about/', views.about,name='about'),
path('contact/', views.contact,name='contact'),
]
According Django Design philosophy on Definitive URLs:
Technically, foo.com/bar and foo.com/bar/ are two different URLs, and
search-engine robots (and some Web traffic-analyzing tools) would
treat them as separate pages. Django should make an effort to
“normalize” URLs so that search-engine robots don’t get confused.
I have a simple return HttpResponseRedirect(reverse('index')) where 'index' is the name of the view. on running the server the index view is correctly displayed but gives out this error "NoReverseMatch at /vehicle_movement/checkinview"on redirecting.
I was working on django 1.1 for the same project but switched to django 2.2 later. Redirect was working fine with url django 1.1 but gives this error with path django 2.2. Another change that i have done is earlier in 1.1 project the index view url was written in the main url.py but now it is written in the apps urls.py.
This is views.py
def index(request):
return render(request,'vehicle_movement/index.html',{})
def CheckinView(request):
if request.method == "POST":
checkin_form = CheckinForm(data = request.POST)
if checkin_form.is_valid():
checkin_form.save()
return HttpResponseRedirect(reverse('index'))
else:
HttpResponse("Error")
else:
checkin_form = CheckinForm()
return render(request,'vehicle_movement/checkin.html',{'checkin_form':checkin_form})
This is the Main urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(('vehicle_movement.urls','vehicle_movement'),namespace = 'vehicle_movement')),
]
This is app urls.py
app_name = 'vehicle_movement'
urlpatterns = [
path('', views.index, name='index'),
path('index', views.index, name='index'),
]
This is the structure
Warehouse
-Warehouse
-init.py
-settings.py
-urls.py
-static
-templates
-vehicle_movement
-urls.py
-views.py
The TEMPLATES_DIR
TEMPLATES_DIR = os.path.join(BASE_DIR,'templates')
``
You've namespaced your app urls, so you need to use that namespace when reversing them:
reverse('vehicle_movement:index')
But you've also got two paths with the same name in your app urls, which will cause conflicts, if not an error. Delete one of them.
Check name="htmlfilename" in app urls is correct or not.
I have created a Django project but I am using Apache as the webserver. Can anyone tell me how can I redirect an error code like 404 or 500 or 400 to a custom error html page instead of getting a standard error message on page in case an error was to occur ? I've tried the solutions available on the web but none seems to work
I have a blog supported by django,in project's urls.py:
from django.conf.urls import handler400, handler403, handler404, handler500
urlpatterns = [
url(r'^$', IndexView.as_view(), name='index'),
url(r'^admin/', admin.site.urls),
....
url(r'^rss/$', BlogFeed(), name='rss'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='sitemap')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if not settings.DEBUG:
handler400 = 'common.views.bad_request'
handler403 = 'common.views.permission_denied'
handler404 = 'common.views.page_not_found'
handler500 = 'common.views.server_error'
common/views.py:
def bad_request(request):
context = {}
return render(request, '400.html', context, status=400)
def permission_denied(request):
context = {}
return render(request, '403.html', context, status=403)
def page_not_found(request):
context = {}
return render(request, '404.html', context, status=404)
def server_error(request):
context = {}
return render(request, '500.html', context, status=500)
from django.conf.urls import (handler403, handler404, handler500)
handler403 = 'my_app.views.permission_denied'
handler404 = 'my_app.views.page_not_found'
handler500 = 'my_app.views.server_error'
You can handle the requests like this.
The exception missing in a view is a solution for this problem.
Change:
def bad_request(request):
for:
def bad_request(request, exception):
Django admin panel throws 404 when passing any url parameters
Example url:
/admin/app/model/ - OK
/admin/app/model/?foo=bar - 404
/admin/app/model/?p=1 - 404
Nginx+uwsgi
Project urls file (admin,admin_tools,application urls)
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
import restaurant.views
import club.views
import hotel.views
import custom_app.views
import cart.views
from django.views.decorators.csrf import csrf_exempt
from django.contrib import admin
import settings
handler404 = 'custom_app.views.handler404'
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin_tools/', include('admin_tools.urls')),
(r'^$', custom_app.views.Index.as_view()),
(r'^restaurant$', restaurant.views.Index.as_view()),
(r'^which$', csrf_exempt(TemplateView.as_view(template_name='custom_app/which.html'))),
(r'^cart/add', cart.views.AddToCart.as_view()),
(r'^cart/delete', cart.views.RemoveFromCart.as_view()),
(r'^cart/send', cart.views.SendCart.as_view()),
(r'^cart/delivery', cart.views.SetDelivery.as_view()),
(r'^restaurant/about', restaurant.views.About.as_view()),
(r'^restaurant/payment', restaurant.views.Payment.as_view()),
(r'^restaurant/vip', restaurant.views.Vip.as_view()),
(r'^restaurant/menu/(?P<slug>.+)', restaurant.views.Menu.as_view()),
(r'^restaurant/menu/', restaurant.views.Menu.as_view()),
(r'^restaurant/cart/', cart.views.Basket.as_view()),
(r'^restaurant/tables/', restaurant.views.Tables.as_view()),
(r'^restaurant/success_ordering', restaurant.views.SuccesTableOrder.as_view()),
(r'^vacancy', custom_app.views.Vacancy.as_view()),
(r'^hotel$', hotel.views.Main.as_view()),
(r'^hotel/services', hotel.views.Services.as_view()),
(r'^hotel/room/(?P<room>\d+)$', hotel.views.Main.as_view()),
(r'^hotel/order/option/toggle$', hotel.views.ToggleOption.as_view()),
(r'^hotel/order/date/toggle$', hotel.views.ToggleDate.as_view()),
(r'^hotel/order/send$', hotel.views.Send.as_view()),
(r'^club/events/old/(?P<year>\d+)/(?P<month>\d+)', club.views.OldEvents.as_view()),
(r'^club/events/old/', club.views.OldEvents.as_view()),
(r'^club/about', club.views.About.as_view()),
(r'^club/event/(?P<pk>\d+)', club.views.DetailEvent.as_view()),
(r'^club$', club.views.Main.as_view()),
url(r'^admin/', include(admin.site.urls)),
(r'^ckeditor/', include('ckeditor.urls')),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
Nginx configuration file:
server
{
listen %server_ip%;
server_name custom.ru www.custom.ru;
root /home/custom/www/;
location ~* ^/resize/([\d\-]+)/([\d\-]+)/(.+)$ {
alias /home/custom/www/custom/$3;
image_filter resize $1 $2;
image_filter_buffer 2M;
error_page 415 = /empty;
}
location ~* ^/crop/([\d\-]+)/([\d\-]+)/(.+)$ {
alias /home/custom/www/custom/$3;
image_filter crop $1 $2;
image_filter_buffer 2M;
error_page 415 = /empty;
}
location = /empty {
empty_gif;
}
location /
{
root /home/custom/www/custom/;
uwsgi_pass unix:///home/custom/tmp/uwsgi.sock;
include uwsgi_params;
uwsgi_param UWSGI_PASS unix:///home/custom/tmp/uwsgi.sock;
uwsgi_param UWSGI_CHDIR /home/custom/www/custom/;
uwsgi_param UWSGI_SCRIPT wsgi;
}
location /static
{
alias /home/custom/www/custom/static/;
}
location /media
{
alias /home/custom/www/custom/media/;
}
location = /favicon.ico { alias /home/custom/www/favicon.ico; }
}
Try
/admin/app/action?foo=bar
instead of /?
The extra / is looking for a resource at that location