NoReverseMatch at / after upgrade from 1.3 to 1.4 - django

The project was working fine with Django 1.3, once I updated to 1.4 results on this error:
NoReverseMatch at /
Reverse for 'app_list' with arguments '()' and keyword arguments '{'app_label': ''}' not found.
urls.py:
from views import home
urlpatterns = patterns('',
(r'^$', home),
(r'^projects/', include('projects.urls')),
(r'^admin/', include(admin.site.urls)),
)
projects.url:
from django.conf.urls.defaults import *
from views import *
urlpatterns = patterns('projectcenter.projects.views',
url(r'project/(\d+)/$', project_detail, name = 'project_detail' ),
)
views.py
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from projects.models import Project
def home(request):
template = 'index.html'
user = request.user
projects = Project.objects.current()
if projects:
map_center = projects[0].location
else:
map_center = (0, 0)
data = {'user': user,
'projects': projects,
'map_center': map_center ,
}
return render_to_response(template, data,
context_instance=RequestContext(request))

I ran into this today and solved it by just updating the relevant line to:
url(r'^admin/', include(admin.site.urls)),
Not sure why that fixed it though.

In the index.html template I was inheriting from this template:
{% extends "admin/change_list.html"%}
I removed the line above and it worked fine.
I really don't know why it worked.
Thanks.

Related

Why am I getting error 404 in my django project when everything seems correct?

I have two apps in my Django project:basket and store. In root url files I configured the urls.py like this:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
store/urls.py:
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.all_products, name='all_products'),
path('<slug:slug>/', views.product_detail, name='product_detail'),
path('category/<slug:category_slug>/',
views.category_list, name='category_list')
]
basket/urls.py:
from django.urls import path
from . import views
app_name = 'basket'
urlpatterns = [
path('', views.basket_summary, name='basket_summary'),
path('add/', views.basket_add, name='basket_add'),
]
I am getting an error:
Page not found(404)
Request Method:GET
Request URL:http://127.0.0.1:8000/basket/
Raised by:store.views.product_detail
this is my store/views.py:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
context = {
'product': product,
}
return render(request, 'store/products/detail.html', context)
please help me solve this problem i've been stuck on this for a long time.
Try this way if you want to avoid 404 error:
from django.shortcuts import get_object_or_404, render
from .models import *
def product_detail(request, slug):
try:
product = Product.objects.get(slug=slug, in_stock=True)
context = {
'product': product,
}
except Product.DoesNotExist:
raise ValidationError('Product Does not exist ')
return render(request, 'store/products/detail.html', context
)

NoReverseMatch at Error Django/Python

I've tried to explore other questions here about this but having trouble diagnosing my error--hoping someone here can help me out.
Here is the full error:
NoReverseMatch at /
Reverse for 'projects' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Error during template rendering
In template /home/django/chrisblog/posts/templates/posts/home.html, error at line 0
The error happened when I tried to create a few additional pages on the website--just essentially copying the template of another page. These pages are using an extends tag with a 'base.html' template.
My URL file looks like this
from django.conf.urls import url
from django.contrib import admin
import posts.views
import sitepages.views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', posts.views.home, name="home"),
url(r'^resources/', sitepages.views.resources, name="resources"),
url(r'^projects/', sitepages.views.projects, name="projects"),
url(r'^about/', sitepages.views.about, name="about"),
url(r'^posts/(?P<post_id>[0-9]+)/$', posts.views.post_details, name="post_detail"),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and my Views file
from django.shortcuts import render
from . import models
def about(request):
return render(request,'sitepages/about.html')
def resources(request):
return render(request,'sitepages/resources.html')
def projects(request):
return render(request,'sitepages/projects.html')
Let me know if this is enough to go on. Thanks for the help.

Django does not match urls

I've been working on a django web app (using Django 1.3), a web catalogue of products, and it was working fine until I was asked to add a custom admin site. I'm fully aware of the Django admin site, but the client is very old-fashioned, and is tech-ignorant so I have to make a "for dummies" version admin site. The root urlconf:
from django.conf.urls.defaults import *
from django.views.generic import TemplateView
from store.models import Category
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^^$', TemplateView.as_view(
template_name='homepage.html',
get_context_data=lambda: {
'crumb': 'home',
'category_list':Category.objects.all()
}
),
name='home'),
url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': '/static/img/favicon.ico'}),
url(r'^store/', include('store.urls', app_name='store', namespace='store')),
)
And the urlconf for the store app:
from django.conf import settings
from django.conf.urls.defaults import *
from store import views
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
)
and the original views:
from django.http import Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView
from store.models import Category, Brand, Product
def get_brands(request):
q = request.GET.get('q')
if q is not None:
category = get_object_or_404(Category, slug__iexact=q)
try:
brands = category.brands.all()
except:
brands = []
template = 'infobox.html'
data = {
'category': category,
'brands': brands,
}
return render( request, template, data )
class GalleryView(ListView):
context_object_name = 'product_list'
template_name = 'store/gallery.html'
def get_queryset(self):
self.category = get_object_or_404(Category, slug__iexact=self.args[0])
try:
brand = Brand.objects.get(slug__iexact = self.args[1])
self.brand_name = brand.name
except:
#no brand is specified, show products with no brand
if self.category.category_products.filter(brand__isnull=True):
#if there are products with no brand, return those
return self.category.category_products.filter(brand__isnull=True)
else:
#if all products have a brand, return the products of the first brand
all = self.category.brands.all()
if all:
brand = all[0]
self.brand_name = brand.name
return brand.brand_products.all()
else:
raise Http404
else:
#brand is specified, show its products
return Product.objects.filter(category=self.category, brand=brand)
def get_context_data(self, **kwargs):
context = super(GalleryView, self).get_context_data(**kwargs)
category = self.category
category_brands = self.category.brands.all()
context['category_list'] = Category.objects.all()
context['category'] = category
context['crumb'] = category.name
context['category_brands'] = category_brands
try:
context['brand'] = self.brand_name
except:
context['brand'] = None
return context
Now, my custom admin app was working fine on my local dev environment, but when I added the new urls and views to prod, Django doesn't seem to match any of the new urls. The original views and urls still work, but none of the new urls get matched and I just keep getting a 404 Not Found error.
The updated urlconf:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from store import views
admin_urls = patterns ('',
url(r'^$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
)
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^login/$', views.admin_login, name='login'),
url(r'^logout/$', views.admin_logout, name='logout'),
url(r'^logout/success/$', views.admin_logout_success, name='logout_success'),
url(r'^test/', views.test, name='test'),
url(r'^admin/', include(admin_urls, namespace='admin')),
url(r'^ajax/$', views.ajax_request, name='ajax_request'),
)
Note that not even the simple '/store/test/' url does not get matched. I'm not really sure why Django isn't matching my urls, and any help is appreciated.
I'm not exactly sure what was happening since all of my templates linked to other pages using the {% url %} tag, but I think the reason my urls were getting muddled up was because I was using the r'^(\w+)/$' regex, so it was matching any word. I simply moved the urlconfs with the (\w+) rule to the bottom of urls.py, and refactored them to be a little more specific and they were gold again.
The updated urlconf:
from django.conf import settings
from django.conf.urls.defaults import patterns, include, url
from django.contrib.auth.decorators import login_required
from store import views
admin_urls = patterns ('',
)
urlpatterns = patterns ('',
url(r'^category/$', views.get_brands, name='get_brands'),
url(r'^(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^(\w+)/(\w+)/$', views.GalleryView.as_view(), name='gallery'),
url(r'^login/$', views.admin_login, name='login'),
url(r'^logout/$', views.admin_logout, name='logout'),
url(r'^logout/success/$', views.admin_logout_success, name='logout_success'),
url(r'^ajax/$', views.ajax_request, name='ajax_request'),
url(r'^administration/$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^administration/add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
)
As you mentioned in the comments, removing login_required fixes the problem. Here's what the django docs have to say about the decorator:
login_required() does the following:
If the user isn’t logged in, redirect to settings.LOGIN_URL, passing the current absolute path in the query string. Example:
/accounts/login/?next=/polls/3/.
If the user is logged in, execute the view normally
[...] Note that if you don't specify the login_url parameter, you'll
need to map the appropriate Django view to settings.LOGIN_URL.
In other words, it goes to a default url you can override in settings.LOGIN_URL.
Now here's what I think happened - I think you defined your own login here:
url(r'^login/$', views.admin_login, name='login'),
And because the login_required in the new urls pointed at the default url, which doesn't exist it returned 404. However, when you configured the login_required views after your other urls:
url(r'^login/$', views.admin_login, name='login'),
...
url(r'^administration/$', login_required(views.AdminIndexView.as_view()), name='admin_index'),
url(r'^administration/add/(\w+)/$', login_required(views.AdminAddView.as_view()), name='admin_add'),
it worked. Why is that? You didn't overrid LOGIN_URL here right? But you sort of did - because at this point, you redefined the namespace 'login' to point to your own view. Now this isn't mentioned anywhere in the docs, but it makes sense, and looking at the default admin templates you can see this is the namespace being used.
Does that make sense to you?

Django NoReverseMatch Error

I'm trying to develop a blog script with Django. But when I want to show post links, I get NoReverseMatch error.
My views.py
# -*- coding: utf-8 -*-
# Create your views here.
from .models import Yazi, Yorum, Kategori
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
from django.contrib.sites.models import Site
def Home(request):
try:
posts = Yazi.objects.filter(yayinlanmis=True).order_by('-yayinlanma_tarihi')
except Yazi.DoesNotExist:
raise Http404
site = Site.objects.get_current()
c = RequestContext(request,{
'posts':posts,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_list.html', c)
def Detail(request, slug):
post = Yazi.objects.get(slug=slug)
site = Site.objects.get_current()
c= RequestContext(request,{
'posts':post,
'site':site
})
return render_to_response('Penguencik_Yazilar/yazi_detail.html',c)
Urls.py in application folder.
from django.conf.urls import patterns, url
import views
urlpatterns = patterns('',
url(r'^$', views.Home,name='index'),
url(r'^/makale/(?P<slug>[0-9A-Za-z._%+-]+)$', views.Detail,name='detail'),
)
Urls.py in project folder
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', include('Penguencik_Yazilar.urls',namespace='blog')),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And template code. What am I doing wrong?
{% load url from future %}
...
Read
Try to change this:
Read
to:
Read
Cause your view expect slug keyword here (?P<slug>[0-9A-Za-z._%+-]+).

Django: How can i get the url of a template by giving the namespace?

While i'm rendering a template i would like to retrieve the url of the template by giving the namespace value and not the path. For example instead of this:
return render(request, 'base/index.html', {'user':name})
i would like to be able to do the following:
from django.shortcuts import render
from django.core.urlresolvers import reverse
return render(request, reverse('base:index'), {'user':name})
but the above produces an error. How can i do it? Is there any way to give the namespace to a function and get the actual path?
Extended example:
- urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('',
url(r'^', include('base.urls', namespace='base')),
)
- app base: urls.py
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index', name='index'),
)
- app base: views.py
from django.shortcuts import render
from django.core.urlresolvers import reverse
def homepage(request):
'''
Here instead of 'base_templates/index.html' i would like to pass
something that can give me the same path but by giving the namespace
'''
return render(request, 'base_templates/index.html', {'username':'a_name'})
Thanks in advance.
Template names are hard coded within the view. What you can also do is that you can pass the template name from the url pattern, for more details see here:
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns('base.views',
url(r'^/?$', 'index',
{'template_name': 'base_templates/index.html'},
name='index'),
)
Then in view get the template name:
def index(request, **kwargs):
template_name = kwargs['template_name']