How to get rid of app name in the particular url? - django

I have this urls.py in my app
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from products import views
app_name = 'products'
router = DefaultRouter()
router.register(r'products', views.ProductViewSet, basename='products')
router.register(r'categories', views.ProductCategoryViewSet, basename='categories')
router.register(r'brands', views.BrandViewSet, basename='brands')
urlpatterns = [
path('', include(router.urls)),
]
And this is my project's urls.py
from django.contrib.auth import views as auth_views
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'),
name='login'),
path('logout/', auth_views.LoginView.as_view(template_name='users/logout.html'),
name='logout'),
path('__debug__/', include('debug_toolbar.urls')),
]
urlpatterns += [
...
path('products/', include('products.urls', namespace='products')),
...
]
And viewsets:
from rest_framework import viewsets, permissions
from .models import (
Product,
ProductCategory,
Brand,
)
from .serializers import ProductSerializer, ProductCategorySerializer, BrandSerializer
#all other viewsets are the same
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
A router for my app generates urls almost as expected, I can go to 'site/products/categories' for categories 'site/products/brands' for brands BUT for products url is 'site/products/products'. How to make it not to add app name in this case? I want it to be just 'site/products'.

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from products import views
app_name = 'products'
router = DefaultRouter()
router.register(r'categories', views.ProductCategoryViewSet, basename='categories')
router.register(r'brands', views.BrandViewSet, basename='brands')
router.register(r'', views.ProductViewSet, basename='products')
urlpatterns = [
path('', include(router.urls)),
]
Django is trying to match url to one url from list of router urls, so if you have two same urls, but one is faster in list, Django will pick always the first one.

Related

I am currently using django 4.0 getting this error while including ('rest_auth.urls')

from django.contrib import admin
from django.urls import path,include
from Users.urls import *
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
path("",include("Users.urls")),
path('api/v1/rest-auth/', include('rest_auth.urls')),
]
Error:-ImportError: cannot import name 'url' from 'django.conf.urls'
In rest_auth.urls do this:
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
app_name = 'recipe'
urlpatterns = [
path('',include(router.urls)),
]
Hope your problem will solve now.

How to remove last / character in root URL API in Django

API only work with url below:
http://127.0.0.1:1997/api/v1/groups/
How can I remove the last '/' so that it works like below:
http://127.0.0.1:1997/api/v1/groups
My config url code:
import os
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from rest_framework.schemas import get_schema_view
from rest_framework_swagger.renderers import SwaggerUIRenderer, OpenAPIRenderer
from groups import views as group_views
API_VERSION = os.getenv('API_VERSION')
API_ROOT = f"api/{API_VERSION}/"
router = routers.DefaultRouter()
router.register('groups', group_views.GroupViewSet)
schema_view = get_schema_view(
title='next_blog',
renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer])
urlpatterns = [
path('admin', admin.site.urls),
path('api_auth', include(
'rest_framework.urls', namespace='rest_framework')),
path('docs', schema_view, name='docs'),
path(API_ROOT, include(router.urls)),
]
Thanks everyone !
Set the trailing_slash argument to False when instantiating the router.
router = DefaultRouter(trailing_slash=False)
Django Rest Framework Default Router

Seeing only one endpoint in browsable API instead of two

How come I can only see one of my URLs (users) instead of both in the django rest browsable API?
urls:
urlpatterns = [
path("admin/", admin.site.urls),
path("api-auth/", include("rest_framework.urls")),
path("", include("accounts.urls")),
path("", include("properties.urls")),
]
I expected to see users AND properties
accounts.urls:
from django.urls import path, include
from accounts.views import UserViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r"users", UserViewSet)
urlpatterns = [path("", include(router.urls))]
properties.urls:
from django.urls import path, include
from properties.views import PropertyViewSet, UnitViewSet
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r"properties", PropertyViewSet)
router.register(r"units", UnitViewSet)
urlpatterns = [path("", include(router.urls))]

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