Django - Register App Model in Custom AdminSite - django

I have a django project with three apps: website, blog, and customauth. The customauth app implements a custom user and AdminSite. The blog app has a Post model. I am trying to register the Post model with the custom AdminSite and I receive the following error:
NoReverseMatch at /my_admin/
Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/my_admin/
Django Version: 2.0.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'app_list' with keyword arguments '{'app_label': 'blog'}' not found. 1 pattern(s) tried: ['admin\\/(?P<app_label>customauth)/$']
Here is customauth/admin.py:
class MyAdminSite(admin.AdminSite):
site_title = "Custom Administration Area"
site_header = 'Custom Administration Area'
def get_urls(self):
urls = super(MyAdminSite, self).get_urls()
my_urls = [
url(r'^my_view/$', self.my_view, name='my_view'),
]
return my_urls + urls
def my_view(self,request):
value = "You're looking at the new admin view."
context = dict(
# Include common variables for rendering the admin template.
self.each_context(request),
# Anything else you want in the context...
key=value,
)
return TemplateResponse(request, "website/admin.html", context)
admin_site = MyAdminSite(name='myadmin')
# Now register the new UserAdmin...
admin_site.register(MyUser, UserAdmin)
And here is blog/admin.py:
from django.contrib import admin
from customauth.admin import admin_site
# Register your models here.
from .models import Post
class PostAdmin(admin.ModelAdmin):
pass
admin_site.register(Post,PostAdmin)
Here is the website/urls.py:
from django.contrib import admin
from django.urls import include, path
from customauth.admin import admin_site
from . import views
urlpatterns = [
path('admin/', admin.site.urls, name='admin'),
path('my_admin/', include('customauth.urls'), name='custom_admin'),
path('', views.index, name='index'),
path('latest_news/', include('blog.urls'), name='latest_news')
]
And here is the customauth/urls.py:
from . import views
from .admin import admin_site
urlpatterns = [
path('', admin_site.my_view, name='custom_admin'),
]
What am I doing wrong?

I figured out what I did wrong.
The problem is the way I configured the urls.
In website.urls I changed:
path('my_admin/', include('customauth.urls'), name='custom_admin'),
to
path('my_admin/', admin_site.urls, name='custom_admin'),
And that solved the problem. I no longer need the customauth.urls file.

Related

Page not found (404) on django

I am using django 3.2 to build a personal e-commerce project, Got Error-Page not found (404) on visiting my products page url Method:GET URL:http://127.0.0.1:8000/products Using the URLconf defined in main.urls. I have followed all the conventions and the other pages are all working but this one is giving me a[urls[\views][1][browser display] hard time as i feel everything is correct, i might be wrong, pls help and if u need to see more of my code, please let me know.
This is my code for urls
from django.urls import path
from django.views.generic.detail import DetailView
from django.views.generic import *
from main import models, views
app_name = 'main'
urlpatterns = [
path('', views.home, name='home'),
path('about_us/', views.about_us, name='about_us'),
path('contact-us/', views.ContactUsView.as_view(), name='contact_us'),
path(
"products/<slug:tag>/",
views.ProductListView.as_view(),
name="products"
),
path("product/<slug:slug>/", DetailView.as_view(model=models.Product), name='product'),
]
my code for views
from django.views.generic.edit import FormView
from .forms import ContactForm
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.shortcuts import get_object_or_404
from main import models
class ProductListView(ListView):
template_name = "main/product_list.html"
paginate_by = 4
def get_queryset(self):
tag = self.kwargs['tag']
self.tag = None
if tag != "all":
self.tag = get_object_or_404(
models.ProductTag, slug=tag
)
if self.tag:
products = models.Product.objects.active().filter(
tags=self.tag
)
else:
products = models.Product.objects.active()
return products.order_by("name")
then my browser
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/products
Using the URLconf defined in booktime.urls, Django tried these URL patterns, in this order:
admin/
[name='home']
about_us/ [name='about_us']
contact-us/ [name='contact_us']
products/<slug:tag>/ [name='products']
product/<slug:slug>/ [name='product']
^media/(?P<path>.*)$
The current path, products, didn’t match any of these.
You have to create a path to url ending with "products/". You create url just to sent with parameter "tags". "products/slug:tag/"
So, add 'products/' to your urls path the url below and you'll access with 'http://127.0.0.1:8000/products/'
path(
"products/",
views.ProductListView.as_view(),
name="products"
)

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

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'),
]

Zinnia rewriting urls does doesn't work

I'm trying to customize the url of entries in zinnia to show slugs of entries only, ie .../blog/slug.
I've been following closely the documentation here - I've overwritten the get_absolute_url method, I've added the view and configured the urls and registered the _base model in django settings - yet the error persists:
zinnia_customized models.py:
from django.db import models
from zinnia.models_bases.entry import AbstractEntry
class EntryWithNewUrl(AbstractEntry):
"""Entry with '/blog/<id>/' URL"""
#models.permalink
def get_absolute_url(self):
return ('zinnia:entry_detail', (),
{'slug': self.slug})
class Meta(AbstractEntry.Meta):
abstract = True
zinnia_customized views.py:
from django.views.generic.detail import DetailView
from zinnia.models.entry import Entry
from zinnia.views.mixins.entry_preview import EntryPreviewMixin
from zinnia.views.mixins.entry_protection import EntryProtectionMixin
class EntryDetail(EntryPreviewMixin, EntryProtectionMixin, DetailView):
queryset = Entry.published.on_site()
template_name_field = 'template'
project urls.py:
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
url(r'^admin/tools/', include('admin_tools.urls')),
url(settings.ADMIN_URL, include(admin.site.urls)),
url(r'^users/', include('anpene.users.urls', namespace='users')),
url(r'^accounts/', include('allauth.urls')),
url(r'^blog/', include('zinnia_customized.urls', namespace='zinnia')),
url(r'^comments/', include('django_comments.urls')),
]
zinnia_customized urls.py:
blog_urls = [
url(r'^', include('zinnia.urls.capabilities')),
url(r'^search/', include('zinnia.urls.search')),
url(r'^sitemap/', include('zinnia.urls.sitemap')),
url(r'^trackback/', include('zinnia.urls.trackback')),
url(r'^blog/tags/', include('zinnia.urls.tags')),
url(r'^blog/feeds/', include('zinnia.urls.feeds')),
url(r'^blog/authors/', include('zinnia.urls.authors')),
url(r'^blog/categories/', include('zinnia.urls.categories')),
# url(r'^blog/', include('zinnia.urls.entries')),
url(r'^blog/', include('zinnia_customized.urls.entries')),
url(r'^blog/', include('zinnia.urls.archives')),
url(r'^blog/', include('zinnia.urls.shortlink')),
url(r'^blog/', include('zinnia.urls.quick_entry')),
]
urlpatterns += patterns('',
url(r'^', include(blog_urls), name='blog')
)
zinnia_customized app urls/entries.py:
from django.conf.urls import url
from django.conf.urls import patterns
from zinnia_customized.views import EntryDetail
urlpatterns = [
url(r'^(?P<slug>[\w-]+)/$', EntryDetail.as_view(), name='entry_detail'),
]
zinnia_customized admin.py:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from zinnia.models.entry import Entry
from zinnia.admin.entry import EntryAdmin
class EntryUrlAdmin(EntryAdmin):
"""blank"""
admin.site.register(Entry, EntryUrlAdmin)
settings:
...
ZINNIA_ENTRY_BASE_MODEL = 'zinnia_customized.models.EntryWithNewUrl'
...
And the error:
NoReverseMatch at /blog/
Reverse for 'entry_detail' with arguments '()' and keyword arguments '{'slug': u'pies'}' not found. 1 pattern(s) tried: [u'blog/(?P<year>\\d{4})/(?P<month>\\d{2})/(?P<day>\\d{2})/(?P<slug>[-\\w]+)/$']
My problem was that I've created a folder called urls in my zinnia_customized, therefore django wasn't sure if it was supposed to use the folder or urls.py

'function' object has no attribute '__getitem__' django

getting type error at /. It may be too localized but I have been racking my brain and searching the web for an answer with no luck. Thank you in advance for your help
TypeError at /
'function' object has no attribute '__getitem__'
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.8.3
Exception Type: TypeError
Exception Value:
'function' object has no attribute '__getitem__'
Exception Location: /Users/wrb473/Documents/workspace/angulardjango/angulardjango/urls.py in <module>, line 22
Python Executable: /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python
Python Version: 2.7.10
url.py
from django.conf.urls import patterns, include, url
from rest_framework.routers import DefaultRouter
#from rest_framework import routers
from django.contrib import admin
from django.contrib.auth.models import User
from rest_framework import routers,serializers,viewsets
from tweeter import views
admin.autodiscover()
router = DefaultRouter()
router = routers.SimpleRouter()
router.register(r'tweets', views.TweetViewSet,base_name='tweets')
router.register(r'users', views.UserViewSet,base_name='users')
urlpatterns = patterns['',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.index, name='index'),
]
here is my views.
views.py
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_protect, ensure_csrf_cookie
from rest_framework import permissions, viewsets
from tweeter.models import Tweet
from tweeter.permissions import IsAuthorOrReadOnly
from tweeter.serializers import TweetSerializer, UserSerializer
#csrf_protect
#ensure_csrf_cookie
def index(request):
user = authenticate(username='bob', password='bob')
if user is not None:
login(request, user)
return render(request, 'tweeter/index.html')
class TweetViewSet(viewsets.ModelViewSet):
queryset = Tweet.objects.all()
serializer_class = TweetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsAuthorOrReadOnly,)
def pre_save(self, obj):
obj.user = self.request.user
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
Please help.
I think the problem is how you are defining your patterns.
urlpatterns = patterns['',
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^$', views.index, name='index'),
]
As you can see in the django source for patterns, patterns is a function, so you need to call it, with (), not using [], which is the syntax to access an item in a sequence.
So you should do this instead:
urlpatterns = patterns(''
# ...
)

view does not exist when trying to include a built in login/logout system in django views

The code is
#urls.py
from django.conf.urls import patterns, url
from employees import views
from schdeules import views
urlpatterns = patterns('',
url(r'^$', views.home, name='home'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),
url(r'^accounts/$', 'django.views.generic.simple.redirect_to', {'url': '/'}),
url(r'^accounts/profile/$', 'django.views.generic.simple.redirect_to', {'url': '/'}),
)
#views.py
# Create your views here.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
#login_required
def home(request):
welecome = 'hai welcome to opas'
context = {'temp_var': welecome}
return render(request, 'schdeules/home.html')
and iam getting an error
Exception Type: ViewDoesNotExist at /opas/
Exception Value: Could not import django.views.generic.simple.redirect_to. Parent module django.views.generic.simple does not exist.
i want to use django default login and logout modules.
if successfully logged in then i want to redirect to home page.
Thanks in advance.
The function-based generic view redirect_to was deprecated in Django 1.3, and removed in Django 1.5. Use the class-based generic view RedirectView instead.
from django.views.generic.base import RedirectView
urlpaterns = ('',
...
url(r'^accounts/$', RedirectView.as_view(url='/')),
url(r'^accounts/profile/$', RedirectView.as_view(url='/')),
)
Note that you don't have to include url patterns for /accounts/ and /accounts/profile/. You may be better to set LOGIN_REDIRECT_VIEW in your settings, so that users are redirected straight to the home page after logging in.
LOGIN_REDIRECT_VIEW = 'home' # using a named url pattern requires Django 1.5 or later