django reverse with namespace - django

I'm getting this error:
The included urlconf 'unsitiodigital.urls' does not appear to have any patterns in it.
The traceback points to this line
class Contacto(FormView):
template_name = "contacto.html"
form_class = FormContacto
success_url = reverse("main:mensaje_enviado") -->This Line
def form_valid(self, form):
form.send_email()
return super(Contacto, self).form_valid(form)
There are valid patterns, it works without the reverse line.
urls.py - general
urlpatterns = [
url(r'^', include('main.urls', namespace="main")),
url(r'^admin/', include(admin.site.urls)),
]
urls.py - main
from django.conf.urls import url
from main import views
urlpatterns = [
url(r'^$', views.Inicio.as_view(), name='inicio'),
url(r'^quienes_somos/$', views.QuienesSomos.as_view(), name='quienes_somos'),
url(r'^opciones/$', views.Opciones.as_view(), name='opciones'),
url(r'^contacto/$', views.Contacto.as_view(), name='contacto'),
-> url(r'^mensaje_enviado/$', views.MensajeEnviado.as_view(), name='mensaje_enviado')
]
So, ¿which is the correct user of reverse?. Thanks a lot.

The include path must be wrong
url(r'^', include('main.urls', namespace="main")), # the 'main.urls' path must be wrong
There are some ways you can include other urls. Try to import the patterns from the main.url module instead
from main.urls import urlpatterns as main_urls
url(r'^', include(main_urls, namespace="main"),
You also have to use reverse_lazy in the success_url.
from django.core.urlresolvers import reverse_lazy
class Contacto(FormView):
template_name = "contacto.html"
form_class = FormContacto
success_url = reverse_lazy("main:mensaje_enviado")
It is useful for when you need to use a URL reversal before your project’s URLConf is loaded.

Related

How to accommodate APIView & ViewSet views in urls.py

How would one write a urls.py file to accommodate views created from APIView and ViewSet.
entity.views.py
from .models import Entity
from .serializers import EntitySerializer
class EntityViewSet(DefaultsMixin, ListCreateRetrieveUpdateViewSet):
"""
"""
queryset = Entity.objects.all()
serializer_class = EntitySerializer
filter_fields = ('id', 'entity_number')
class PersonProfileList(APIView):
"""
person profile
"""
def get(self, request, format=None):
pass
entity.urls.py
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
entity_router = DefaultRouter()
entity_router.register(r'entity', views.EntityViewSet)
urlpatterns = [
url(r'profile/$', views.PersonProfileList.as_view(), name='profile_list'), # Is this correct?
url(r'profile/(?P<pk>[0-9]+)/$', views.PersonProfileList.as_view(), name='profile_detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
main urls.py
from django.conf.urls import include, url
from django.contrib import admin
from entities.urls import entity_router, urlpatterns
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^entities/', include(entity_router.urls)), #This I know works
url(r'^entities/', include(urlpatterns.url)), # This throws errors
]
What is the best way to accommodate both types of Views in the same URL file and have them appear under one /entity unlike now when am getting two /entity entries. Also, once I get into the /entity page in the browsable API, how do I make the /entity/profile viewable since now it only shows /entity. See images for guide.
Root Page
Entities Page

NoReverseMatch Django, get_success_url in CreateView

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?

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

Django reverse causing url circular import, why?

I get this error:
The included urlconf 'fouraxis.urls' does not appear to have any
patterns in it. If you see valid patterns in the file then the issue
is probably caused by a circular import.
I know the url pattern has something in it, it looks like this:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^perfil/', include('clientes.urls'), namespace="cliente"),
url(r'^admin/', include(admin.site.urls))
]
clientes.urls:
from django.conf.urls import url
from django.contrib.auth import views as auth_views
from clientes import views
urlpatterns = [
# login
url(r'^login/$', auth_views.login, {'template_name': 'perfiles/login.html'}, name="login"),
url(r'^logout/$', auth_views.logout, {'template_name': 'perfiles/logged_out.html'}, name="login"),
url(r'^mi_perfil/$', views.mi_perfil, name="mi_perfil"),
url(r'^registro_usuario/$', views.RegistroUsuario.as_view(), name="registro_usuario")
]
The RegistroUsuario view looks like this:
class RegistroUsuario(FormView):
template_name = "perfiles/registro_usuario.html"
form_class = UserCreationForm
success_url = reverse("cliente:mi_perfil") # THIS REVERSE
def form_valid(self, form):
return redirect("cliente:mi_perfil")
context = {'form': UserCreationForm}
I understand I can replace the reverse with a plain-text url like this perfil/mi_perfil. But, I want to know why is this happening with reverse, I can't find the explanation on de docs. Also, using reverse is better cause it is dynamic (if anytime I change the url, it still works as long as it keeps its name).
The reverse() call is made when the view is imported, which is probably when the urlconf is first loaded. You need to use reverse_lazy() instead:
from django.core.urlresolvers import reverse_lazy
class RegistroUsuario(FormView):
template_name = "perfiles/registro_usuario.html"
form_class = UserCreationForm
success_url = reverse_lazy("cliente:mi_perfil") # THIS REVERSE
def form_valid(self, form):
return redirect("cliente:mi_perfil")
context = {'form': UserCreationForm}

django - invalid syntax (urls.py, line 7)

I'm doing a slight variation on my urls.py from the tutorial where I have the following -
mysite/urls.py -
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^TidalDEV/', include('TidalDEV.urls')),
)
TidalDEV/urls.py -
from django.conf.urls import patterns, url
from TidalDEV import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
url(r'^(?P<pk>[0-9]+)/$', views.tesxml, name='tesxml'),
)
And this is the view in views.py -
def tesxml(self, request, pk, format=None, renderer_context=None):
"""
returns an XML of a jobmst listing
"""
template_vars['jobmst'] = (queryset1, [pk])
template_vars['jobdtl'] = (queryset2, [pk])
template_vars['jobdep'] = (queryset3, [pk])
t = loader.get_template('TidalAPI/templates/xml_template.xml')
c = Context(template_vars)
return HttpResponse(t.render(c), mimetype="text/xml")
When I try to hit my url at http://localhost:8080/TidalDEV/10081/ I get invalid syntax. What is the problem here?
Essentially I need the view to populate a template XML file I built.
You are missing a comma after your index view in TidalDEV/urls.py