Django is not showing the right path when clicking on a link - django

This is what it shows when you click on the link
Page not found (404)
Request Method: GET Request URL:
http://localhost:8000/jobapplication/new/1
Using the URLconf defined in careal.urls, Django tried these URL
patterns, in this order:
^$ [name='landing-index']
^admin/
^accounts/
^taskmanager/
^login/$ [name='login']
The problem is that I don't know why it is opening the link as http://localhost:8000/jobapplication/new/1, when it should be http://localhost:8000/taskmanager/jobapplication/new/1
This is what I have in the urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.auth import views as auth_views
from landingpage import views as landingpage_views
urlpatterns = [
url(r'^$', landingpage_views.index, name='landing-index'),
url(r'^admin/', admin.site.urls),
url(r'^accounts/', include('allauth.urls')),
url(r'^taskmanager/', include('taskmanager.urls')),
url(r'^login/$', auth_views.login, name='login'),
]
This is in urls.py in the app taskmanager
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'company/$', CompanyIndex.as_view(), name='company-index'),
url(r'company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]
And this is what I have in views.py in taskmanager, related to jobapplication
# Job Application views
class JobApplicationIndex(generic.ListView):
template_name = 'taskmanager/jobapplication_index.html'
def get_queryset(self):
if self.request.user.is_authenticated:
return JobApplication.objects.filter(user=self.request.user.id).order_by('-created_at')
class JobApplicationCreate(CreateView):
model = JobApplication
fields = ['jobpost', 'sent_date', 'deadline', 'success_rate']
def get_initial(self):
jobpost = get_object_or_404(JobPost, id=self.kwargs.get('jobpost_id'))
return {
'jobpost':jobpost,
}
def form_valid(self, form):
form.instance.user = self.request.user
return super(JobApplicationCreate, self).form_valid(form)
class JobApplicationDetails(generic.DetailView):
model = JobApplication
class JobApplicationEdit(UpdateView):
model = JobApplication
#fields = ['jobpostid', 'is_favorite']
#p = JobApplication.objects.get(id=jobpostid)
#p.is_favorite = is_favorite
#p.save()
class JobApplicationUpdate(UpdateView):
model = JobApplication
fields = ['sent_date', 'deadline', 'success_rate']
template_name_suffix = '_update_form'
def JobApplicationAdd(request, jobpost_id):
if request.method == 'GET' and request.user.is_authenticated:
# If job app for this id exists, redirect to that job app page with a message
if JobApplication.objects.filter(jobpost_id=int(jobpost_id)).exists():
existing = JobApplication.objects.get(jobpost_id=int(jobpost_id))
messages.add_message(request, messages.INFO, 'An application for this opening already exists.')
return HttpResponseRedirect(reverse('taskmanager:jobapplication-detail', args=[existing.id]))
jobapp = JobApplication(user=request.user, jobpost_id=int(jobpost_id), success_rate=50)
jobapp.save()
return HttpResponseRedirect(reverse('taskmanager:index'))
--- The thing is all the other links in taskmanager work and when you click on them, the right path is opened Eg: -
- http://localhost:8000/taskmanager/jobpost/
- http://localhost:8000/taskmanager/jobpost/2/
- http://localhost:8000/taskmanager/company/2/
- http://localhost:8000/taskmanager/kpi/

Try Adding an uptick in front of the regex patterns like you did for the ones that are working.
from django.conf.urls import url
from . import views
from taskmanager.views import *
app_name = 'taskmanager'
urlpatterns = [
# Task manager urls
url(r'^$', JobApplicationIndex.as_view(), name='index'),
url(r'^jobapplication/add/(?P<jobpost_id>[0-9]+)/$', JobApplicationCreate.as_view(), name='jobapplication-add'),
url(r'^jobapplication/new/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationAdd, name='jobapplication-new'),
url(r'^jobapplication/edit/(?P<jobpost_id>[0-9]+)/$', views.JobApplicationEdit, name='jobapplication-edit'),
url(r'^jobapplication/edit/(?P<pk>[0-9]+)/$', JobApplicationUpdate.as_view(), name='jobapplication-edit'),
url(r'^jobapplication/(?P<pk>[0-9]+)/$', JobApplicationDetails.as_view(), name='jobapplication-detail'),
# Company urls
url(r'^company/$', CompanyIndex.as_view(), name='company-index'),
url(r'^company/add/$', CompanyCreate.as_view(), name='company-add'),
url(r'^company/(?P<pk>[0-9]+)/$', CompanyDetails.as_view(), name='company-detail'),
# Job Post urls
url(r'^jobpost/$', JobPostIndex.as_view(), name='jobpost-index'),
url(r'^jobpost/(?P<pk>[0-9]+)/$', JobPostDetails.as_view(), name='jobpost-detail'),
# Statistics urls
url(r'^kpi/$', views.kpi, name='kpi'),
]

Related

My django admin page gives Page not found (404)

my project was running ok I used my admin page at it was all all right today I tried to open it and it gives a Page not found (404)
No Product matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Raised by: store.views.product_detail
No Product matches the given query.
Request Method: GET
Request URL: http://127.0.0.1:8000/admin
Raised by: store.views.product_detail
I havent touched the store app or project files at all at it was waking just fine yesterday now i cannot access admin page
project urls
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('store.urls', namespace='store')),
path('basket/', include('basket.urls', namespace='basket')),
path('account/', include('account.urls', namespace = 'account')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
store urls
from django.urls import path
from . import views
app_name = 'store'
urlpatterns = [
path('', views.product_all, name='product_all'),
path('<slug:slug>', views.product_detail, name='product_detail'),
path('shop/<slug:category_slug>/', views.category_list, name='category_list'),
]
store views
from urllib import request
from django.shortcuts import get_object_or_404, render
from store.context_processors import categories
from .models import Category, Product
def product_all(request):
products = Product.products.all()
return render(request, 'store/home.html', {'products': products})
def category_list(request, category_slug=None):
category = get_object_or_404(Category, slug=category_slug)
products = Product.objects.filter(category=category)
return render(request, 'store/products/category.html', {'category': category, 'products': products})
def product_detail(request, slug):
product = get_object_or_404(Product, slug=slug, in_stock=True)
return render(request, 'store/products/single.html', {'product': product}) ```
context_processors.py wicht i have includet in my project settings
from .models import Category
def categories(request):
return {
'categories': Category.objects.all()
}
This is the code that causes the error
path('<slug:slug>', views.product_detail, name='product_detail'),
Change it to
path('detail/<slug:slug>/', views.product_detail, name='product_detail'),
The product_detail just overwrites the admin URL

why my own template_name doesn't show instead of default template_name in django?

I need to show my own template_name for (passwordResetConfirm) when I use template_name here I get the default Django template also when I get the successful message from (PasswordResetComplete) I get from the same place I mean (the default Django template too).
however, I get no errors of code.so, How can I get my own template_name in this case?
urls.py
from . import views
from django.conf.urls import url
from django.contrib.auth.views import (
LoginView,
logout,
PasswordResetView,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView,
)
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
# django\contrib\admin\templates\registration\password_reset_done.html
app_name = 'account'
class PasswordReset(PasswordResetView):
template_name = 'account/password_reset_form.html'
success_url = reverse_lazy('account:password_reset_done')
email_template_name = 'account/reset_password_email.html'
class PasswordResetDone(PasswordResetDoneView):
template_name = 'account/password_reset_done.html'
success_url = reverse_lazy('account:password_reset_complete')
class PasswordResetConfirm(PasswordResetConfirmView):
success_url = reverse_lazy('account:password_reset_complete')
template_name = 'account/password_reset_confirm.html'
def func(self, request):
return render(request, self.template_name)
class PasswordResetComplete(PasswordResetCompleteView):
template_name = 'account/password_reset_complete.html'
urlpatterns = [
# /account/
url(r'^$', views.index, name="home"),
# /account/login/
url(r'^login/$', LoginView.as_view(template_name='account/login.html'), name='login_page'),
# /account/logout/
url(r'^logout/$', logout, {'template_name': 'account/logout.html'}, name='logout'),
# /account/register/
url(r'^register/$', views.register, name='register'),
# /account/profile/
url(r'^profile/$', views.view_profile, name='view_profile'),
# /account/profile/edit/
url(r'^profile/edit/$', views.edit_profile, name='edit_profile'),
# /account/change-password/
url(r'^change-password/$', views.change_password, name='change_password'),
# /account/password-reset/
url(r'^password-reset/$', PasswordReset.as_view(), name='password_reset'),
# /account/password-reset/done/
url(r'^password-reset/done/$', PasswordResetDone.as_view(), name='password_reset_done'),
# /account/password-reset/confirm/
url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$', PasswordResetConfirm.as_view(), name='password_reset_confirm'),
# /account/password-reset/complete/
url(r'^password-reset/complete/$', PasswordResetComplete.as_view(), name='password_reset_complete'),
]
settings.py
STATIC_URL = '/static/'
# Edit the login src url redirect
LOGIN_REDIRECT_URL = 'account:view_profile'
# Edit the login src url redirect in PasswordResetCompleteView
LOGIN_URL = 'account:login_page'
# To activating PasswordResetConfirmView
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
this image explains the files that I have files image
this image shows password_reset pagepassword reset image it work's
I had the same issue, upon trying out different things, this is what worked
url(r'password_reset/$', auth_views.PasswordResetView.as_view(template_name='password_reset.html', email_template_name='registration/password_reset_email.html', subject_template_name='registration/password_reset_email.html', success_url='/password_reset_done/', from_email='your#email.com')),
url(r'password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='registration/password_reset_done.html')),
url(r'password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html', success_url='registration/password_reset_complete.html'))
I didnot create custom classes, like you did.

Django rest - router is not creating url path, giving 404, and the api webpage has incorrect urls listed

ive created some urls with the default router as per the below:
api.urls
from django.urls import path, include
from rest_framework import routers
from rest_framework_bulk.routes import BulkRouter
from . import views
router = routers.DefaultRouter()
#### NEW ####
router.register(r'data/credentials/', views.DataCredentials)
router.register(r'data/site_circuits', views.DataSiteCircuits)
router.register(r'data/subnets/', views.SubnetsSet)
router.register(r'data/device_conns/', views.DataDeviceConns)
router.register(r'data/email_subscriber/', views.DataEmailSubscriber)
router.register(r'data/pd_user/', views.DataOnCall)
router.register(r'data/bgp/', views.DataBGP)
router.register(r'data/device/routingtable/', views.DataDeviceRoutingTable)
router.register(r'monitoring/bgp/', views.MonitoringBGP)
router.register(r'monitoring/script_results/', views.MonitoringScriptResults)
router.register(r'monitoring/circuit_maintenance/', views.MonitoringCircuitMaintenance)
router.register(r'monitoring/device/routingtable/', views.MonitoringDeviceRoutingTable)
#### LEGACY ####
router.register(r'credentials', views.CredentialDataROView)
router.register(r'tasks', views.TaskSet)
router.register(r'subnets', views.SubnetsSet)
router.register(r'device_conns', views.DeviceConnViewSet)
router.register(r'script_results', views.ScriptResultsView)
router.register(r'circuit_maintenance', views.CircuitMaintenanceView)
router.register(r'email_subscriber', views.EmailSubscriberROView)
router.register(r'pd_user', views.OnCallROView)
router.register(r'bgp_monitoring_data', views.BGPMonitoringDataView)
router.register(r'bgp_status', views.BGPStatusView)
router.register(r'rt_get_devices', views.MonitoringRoutingTableGetDevice)
router.register(r'rt_get_tables', views.MonitoringRoutingTableGet)
router.register(r'rt_upload', views.MonitoringRoutingTableUpload)
router.register(r'contact_type', views.ContactTypeROView)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls')),
#### NEW ####
path('data/site_subnets/', views.DataSiteSubnets.as_view()),
path('data/site_circuits_subnets/', views.DataSiteCircuitSubnets.as_view()),
path('data/device/routing_table/', views.DataDeviceRoutingTable.as_view({'get': 'list','put': 'update'})),
path('data/geomapping/', views.DataGeoMapping.as_view()),
path('monitoring/oncall/', views.MonitoringOnCall.as_view()),
path('monitoring/site_connectivity/', views.MonitoringSiteConnectivity.as_view()),
#### LEGACY ####
path('ss_monitoring_data/', views.SiteSupernetMontioringDataROView.as_view()),
path('monitoring/routing_data', views.MontioringGetRoutingData.as_view()),
path('conn_set_single/<int:site_id>/<int:circuit_id>/', views.MonitoringConnectivitySetSingle.as_view()),
path('conn_set/', views.MonitoringConnectivitySet.as_view()),
path('site_circuits_pending/<int:days>/', views.SiteCircuitsPendingDataROView.as_view({'get': 'list'})),
path('upcoming_circuit_maintenance/<int:days>/', views.UpcomingCircuitMaintenanceView.as_view({'get': 'list'})),
path('aws_bgpdata_set/', views.MonitoringBGPDataSet.as_view()),
path('aws_dc_set/', views.MonitoringAWSDirectConnectSet.as_view()),
path('aws_vpn_set/', views.MonitoringAWSVPNSet.as_view()),
path('four_g_set/', views.FourGDataSet.as_view()),
path('contact_set/', views.ContactSet.as_view()),
path('site_contact_set/', views.SiteContactSet.as_view()),
path('device_version_set/', views.DeviceVersionSet.as_view()),
]
home.urls
from django.urls import path
from . import views
app_name = 'home'
urlpatterns = [
path('', views.index, name='index'),
....
and then I attempt to hit the URL http://localhost:8100/api/data/device/routingtable/ and I am greeted with a 404, would anyone know why this is?
and when I hit my api home page and it lists urls, they are mapped to the wrong views:
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
...
"data/device/routingtable/": "http://localhost:8100/api/rt_upload/",
...
}
views.py:
class DataDeviceRoutingTable(viewsets.ModelViewSet):
time_threshold = datetime.now() - timedelta(minutes=2)
queryset = DeviceData.objects.all().select_related('device','device_use').order_by('monitoring_order')
serializer_class = SerializerDataRoutingTable
permission_classes = (IsAdminUser,)
filter_class = DeviceData
filter_backends = (filters.SearchFilter,)
search_fields = ('device__hostname','device_use__use')
serialisers.py:
class SerializerDataRoutingTable(serializers.ModelSerializer):
hostname = serializers.ReadOnlyField(source='device.hostname', )
site_id = serializers.ReadOnlyField(source='device.site_id', )
routing_table = serializers.SerializerMethodField(source='routing_table',)
use = serializers.ReadOnlyField(source='device_use.use', )
def get_routing_table(self, instance):
try:
return json.loads(instance.routing_table)
except:
return instance.routing_table
class Meta:
model = DeviceData
fields = ('id','site_id','device_id','hostname','use', 'timestamp', 'routing_table')
depth = 1
urls.py:
from django.urls import path, include
from django.conf import settings
from django.contrib.auth import views as auth_views
from django.contrib import admin
import app_settings.views
admin.autodiscover()
handler400 = 'app_settings.views.bad_request'
handler403 = 'app_settings.views.permission_denied'
handler404 = 'app_settings.views.page_not_found'
handler500 = 'app_settings.views.server_error'
urlpatterns = [
path('', include('home.urls')),
path('api/', include('api.urls')),

URl redirection issue in Django 2

I'm new to Django and trying to build a web app with the following structure. I need your help to understand what Im doing wrong.
The flow of the application is shadesProductUploader.urls will forward '' to authSection for login and after a successful login user should be redirected to mainSection 'home/'.
Urls.py files are
shadesProductUploader.urls
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('authSection.urls')),
]
authSection.urls
from django.contrib import admin
from django.urls import path, include
from . import views
app_name = 'authSection'
urlpatterns = [
path('', views.login_view, name='login'),
]
mainSection.urls
from django.contrib import admin
from django.urls import path,include
from . import views
app_name = 'mainSection'
urlpatterns = [
path('home/', views.home),
]
and the view.py in authSection
def login_view(request):
next = request.GET.get('next')
form = userLoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username,password=password)
login(request,user)
if next:
return redirect(next)
context={'user':user}
return redirect('home/')
return render(request, 'login.html', {'form': form})
after a successful login I get this error.
What Am I missing? Not sure why I see a Url of home/ home/
Update shadesProductUploader's main section url like this:
urlpatterns = [
path('',include('mainSection.urls')),
... # other urls
]
And change in mainSection urls like this:
urlpatterns = [
path('home/', views.home, name="home"), # <-- added name here
]
And in view, use it like this:
if next:
return redirect(next)
context={'user':user}
return redirect(reverse('home'))
Here, we have named our url as home. And we got the url using reverse.

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?