NoReverseMatch Django, get_success_url in CreateView - django

i create a create view in my blog app to create a post. in the
create view I used the function get_success_url. I want when i create
a post, that it will redirect to the blog_post_list. H
i get the error: NoReverseMatch
I guess it has to do sth with the urlpatterns.
main urls.py
from django.conf.urls import url, include
from django.contrib import admin
from blog.views import AboutPageView, ContactPageView
urlpatterns = [
url(r'', include('blog.urls', namespace='posts')),
url(r'^blog/', include('blog.urls', namespace='posts')),
url(r'^about/$', AboutPageView.as_view(), name='about'),
url(r'^contact/$', ContactPageView.as_view(), name='contact'),
#admin and login
url(r'^admin/', admin.site.urls),
]
urls in blog app
from django.conf.urls import url
from .views import blog_postListView, blog_postDetailView, blog_postCreateView
urlpatterns = [
url(r'^$', blog_postListView.as_view(), name='blog_post_list'),
url(r'^create/', blog_postCreateView.as_view(), name='blog_post_create'),
url(r'^(?P<slug>[-\w]+)$', blog_postDetailView.as_view(), name='detail'),
]
views in blogapp
class blog_postCreateView(CreateView):
#model = blog_post
form_class = blog_postForm
template_name = "form.html"
#fields = ["title", "content"]
def get_success_url(self):
return reverse("blog_post_list")

You haven't included the namespace so it isn't able to find the blog_post_list
So just add the namespace in the reverse call
reverse("posts:blog_post_list")
For more information on NoReverseMatch errors, see What is a NoReverseMatch error, and how do I fix it?

Related

Django: how to access functions in the views.py

I have a few functions in the view.py in my Django project:
Here is the views.py and urls.py under polls:
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def search(request):
return HttpResponse("You're at the polls search.")
polls/urls.py
from django.urls import path
from . import views
from django.conf.urls import include, url
urlpatterns = [
path('', views.index, name='index'),
path('', views.search, name='search'),
]
I am able to get the index page, but have trouble to reach the page in the search function. I got the error below:
How do I access the search function in the views.py? Thanks!
edit your polls/urls.py as below:
urlpatterns = [
path('', views.index, name='index'),
path('search/', views.search, name='search'),
]
the first argument of the path is the url pattern.
I think you misunderstood the third argument(name). it has nothing to do with the url pattern, it's a name for the url, that'll be useful for url reversing. read the document for more information

Django redirect user to app based on permission and group

Say i have a django project which have 4 apps 1 app is for logging in
project urls:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^', include('Login.urls')),
url(r'^admin/', admin.site.urls),
]
settings:
LOGIN_REDIRECT_URL = '/'
login app urls:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
]
now say i have 3 apps based on user type i.e. Admin, Team Lead, Worker
so i want to redirect user based on their type of employment.
how can i achieve this ?
any help is appreciated
I guess that you will manually add/edit the user groups.
That can be done from django admin panel.
Here is the group/permission django docs: Permissions and Authorization
This is what I did:
I've created an index view in order to get the user group and redirect to the respective view that you want.
So, index view in views.py:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
group = request.user.groups.filter(user=request.user)[0]
if group.name=="employees":
return HttpResponseRedirect(reverse('worker'))
elif group.name=="teamLeader":
return HttpResponseRedirect(reverse('teamLeader'))
elif group.name=="admin":
return HttpResponseRedirect(reverse('adm'))
context = {}
template = "index.html"
return render(request, template, context)
And urls in urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from app import views as app_views
urlpatterns = [
url(r'^login/$', auth_views.login, name='login'),
url(r'^$', app_views.index, name='index'),
url(r'^employees/$', app_views.employees, name='employees'),
url(r'^teamLeader/$', app_views.teamLeader, name='teamLeader'),
url(r'^adm/$', app_views.adm, name='adm'),
]
In settings.py
LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'
Is this what you want to do?

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

NoReverseMatch at /new_application/check_login/

I am new to DJango. I am getting error 'NoReverseMatch at /new_application/check_login/' while redirecting view from another view.
different files listed below.
Main urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^new_application/', include('new_application.urls')),
]
views.py
from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Login
...
def check_login(request):
...
return HttpResponseRedirect(reverse('new_application:loggedin',args=(user,)))
def loggedin(request, user):
return render(request, 'new_application/loggedin.html',{'full_name': user.first_name +" "+ user.last_name})
Application urls.py
from django.conf.urls import url
from . import views
app_name = 'new_application'
urlpatterns = [
url(r'^$', views.login, name='login'),
url(r'^check_login/$', views.check_login, name='check_login'),
url(r'^loggedin/$', views.loggedin, name='loggedin'),
url(r'^invalid_login/$', views.invalid_login, name='invalid_login'),
url(r'^logout/$', views.logout, name='logout'),
]
Here is an error image : error image
please give the solution for fixing this error.
Thank You.
The regex pattern must match against the given url...
url(r'^loggedin/(?P<user>\w+)/$', views.loggedin, name='loggedin'),
Reverse should match one of URL names from urls.py
return HttpResponseRedirect(reverse('loggedin',args=(user,)))

Page not found (404) Error in Django

My urls.py is
from django.conf.urls import patterns,url
from rango import views
urlpatterns=patterns('',url(r'^$',views.index,name='index'))
urlpatterns=patterns('',url(r'^about/$',views.about,name='about'))
My views.py is
from django.shortcuts import render
from rango.models import Category
# Create your views here.
from django.http import HttpResponse
def index(request):
category_list = Category.objects.order_by('-likes')[:5]
context_dict={'categories':category_list}
return render(request, 'rango/index.html', context_dict)
def about(request):
return HttpResponse("go to index")
When I am trying to go to the address http://127.0.0.1:8000/rango I am getting page not found. But I am able to go to the address http://127.0.0.1:8000/rango/about.
When I remove the about url pattern in urls.py, I am able to go to the address http://127.0.0.1:8000/rango but not http://127.0.0.1:8000/rango/about, as the about url pattern does not exist.
I am unable to access both urls at once.
You have defined urlpatterns twice. The second patterns containing the about view replaces the first, which stops you accessing the index view.
Instead of,
urlpatterns=patterns('',url(r'^$',views.index,name='index'))
urlpatterns=patterns('',url(r'^about/$',views.about,name='about'))
it should be:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
)
In Django 1.7+, you don't need to use patterns any more, so you can simplify it to
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
]