DRF Router issue with namespace - python

I am having a hell of a time getting the reverse function to work with my DRF implementation. Here is my urls.py, which i would assume the following reverse to work for:
urls.py
from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'compressors', views.CompressorViewSet, base_name='compressors')
from django.urls import include, path
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls, namespace='router')),
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework'))
]
And then
reverse('router:compressors', kwargs)
What am I missing? I am getting a app_name not provided, which when added to this file does not help. Is there a way for me to put an app_name to the router?

Turns out its just hard to find exactly how the use basename, I did not append '-list' to my reverse. It should have been the following, hope this helps others:
reverse('router:compressors-list')

Related

Django Rest Framework: router is not working

I have used DefaultRouter() and viewset. Here is the code
from rest_framework import routers
from .api import TweetViewset, OwnersTweet
from django.urls import path
router = routers.DefaultRouter()
router.register('', TweetViewset, 'tweets')
router.register('own/', OwnersTweet, 'owner')
And project-level urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('accounts.urls')),
path('tweet/', include('tweets.urls'))
]
When I send a request to '<URL>/tweet/own/' It returned an error Not Found. But <URL>/tweet/ is working. OwnersTweet view also working fine. But I think there is smth wrong with URL. Can you help, please?
I used the path. Now it is working

Using Router vs including url in urlpatterns

Say I am creating a Todo app in Django, traditionally I would include a path to my app in the base_project urls.py file. However, today I came across a tutorial where they used a router for this same purpose I've already stated.
Why would I want to use a Router instead of including the path in my urls.py file?
For reference, here is a snip from the tutorial found at https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react
# backend/urls.py
from django.contrib import admin
from django.urls import path, include # add this
from rest_framework import routers # add this
from todo import views # add this
router = routers.DefaultRouter() # add this
router.register(r'todos', views.TodoView, 'todo') # add this
urlpatterns = [
path('admin/', admin.site.urls), path('api/', include(router.urls)) # add this
]
Here backend is the main django project name.
Both works the same. You can add url in the urlpatterns. I had the same situation as yours where in a tutorial they were using routing instead of url patteren but i studied and both works the same.

Django URL translation dependent on URL prefix language code

I am trying to internationalize a Django dictionary application using the Django translation system. I have successfully translated most of the content on the site but I am having problems translating URL patterns, with the exception of the admin page.
My goal is to change the language of both content and URL based on prefix language code in the URL. For example:
www.example.com/en/dictionary/define // (content in English)
www.example.com/it/dizionario/definisci // (content in Italian)
www.example.com/fr/dictionnaire/définis // (content in French)
...
I checked the Django documentation on this (https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#translating-url-patterns) but found it quite vague and could not really understand it.
project-level urls.py:
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import gettext_lazy as _
from dictionary import views as dictionary_views
urlpatterns = [
path('admin/', admin.site.urls),
]
dictionary_patterns = ([
path('', dictionary_views.index, name='index'),
path(_('define/'), dictionary_views.define, name='define'),
path(_('define/<slug:headword_slug>'), dictionary_views.headword, name='headword'),
], 'dictionary')
urlpatterns += i18n_patterns(
path(_('dictionary/'), include(dictionary_patterns, namespace='dictionary')),
)
As for app-specific urls.py, I have no clue on what to do there. Should I import the dictionary_patterns variable from above and add it to the app's urlpatterns list? Should I delete the app's urls.py file altogether?
Can anybody help?
Just try to add import include in the urlpatterns like
In the project/urls.py
from django.conf.urls import include
path('en/dictionary/',include('app URL here with extension.url'),
path('it/dizionario/',include('app URL here with extension.url'),
path('fr/dictionnaire/',include('app URL here with extension.url'),
In the Appname/urls.py
urlpatterns = [
url(r'^define$/',views.name of view,name=''),
url(r'^definisci/$',views.name of view,name=''),
url(r'^définis/$',views.name of view,name=''),
Check this out:
https://docs.djangoproject.com/en/3.1/topics/http/urls/

Mix Django and DRF urls

So far, I have built a REST API with Django Rest Framework (DRF) which can be consumed by any front-end. Let call this API backend.
I am trying to add another Django app (a regular one this time i.e. no DRF) which shares the same models. Let call this app webapp
However, it seems that the URLs linked to webapp are not available.
Here is my urls.py:
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework import routers
from rest_framework.authtoken import views as token_views
from backend import views
from webapp import views as webapp_views
router = routers.SimpleRouter()
router.register(r'users', views.UserViewSet, 'User')
router.register(r'games', views.GameViewSet, 'Game')
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'membership_create/', views.MembershipCreate.as_view()),
url(r'auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
url(r'^test/', webapp_views.home, name='test'), # the new view
)
]
urlpatterns += router.urls
And the single view (from webapp.views):
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return HttpResponse("""
<h1>WEBAPP !</h1>
<p>test webapp</p>
""")
I am thus wondering if DRF and regular Django views can be mixed so easily or if it is not the right way of doing it.
EDIT:
Using the URLconf defined in WMC.urls, Django tried these URL patterns, in this order:
^admin/
^connect/
membership_create/
auth/connect_with_fb/
auth/connect_with_credentials/
debug/
^auth/
^users/$ [name='User-list']
^users/(?P<pk>[^/.]+)/$ [name='User-detail']
^users/(?P<pk>[^/.]+)/games/$ [name='User-games']
^games/$ [name='Game-list']
^games/(?P<pk>[^/.]+)/$ [name='Game-detail']
The current URL, test/, didn't match any of these.
Moving url(r'^test/', webapp_views.home, name='test') before url(r'^admin/', admin.site.urls) solves the problem although I do not know why.
urlpatterns = [
url(r'^test/', webapp_views.home, name='test'),
url(r'^admin/', admin.site.urls),
url(r'^connect/', views.CustomObtainAuthToken.as_view()),
url(r'^membership_create/', views.MembershipCreate.as_view()),
url(r'^auth/connect_with_fb/', views.ConvertTokenViewWithData.as_view()),
url(r'^auth/connect_with_credentials/', views.TokenViewWithData.as_view()),
url(r'^debug/', views.UserLoginAndIdView.as_view()),
url(r'^auth/', include('rest_framework_social_oauth2.urls'),
)
]

Django define default view with IP address

I migrated my Django project to an Ubuntu distant server. I'm using mod_wsgi in order to runserver and I have some questions about default page.
I'm really new in this domain and I apologize if my question is bad or useless ..
When I want to connect to my Django application, I have to write something like that :
http://172.XX.XX.XXX/Home/login/
If I write just :
http://172.XX.XX.XXX
I get :
Page not found
Using the URLconf defined in Etat_civil.urls, Django tried these URL patterns, in this order:
^admin/
^BirthCertificate/
^Identity/
^Accueil/
^Home/
^captcha/
^Mairie/
The current URL, , didn't match any of these.
My question is :
How I can define redirected url in order to write http://172.XX.XX.XXX in my browser and go directly to http://172.XX.XX.XXX/Home/login/ for example ?
This is urls.py file from my project :
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from BirthCertificate import views
from Identity import views
from Accueil import views
from log import views
from Mairie import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^BirthCertificate/', include('BirthCertificate.urls')),
url(r'^Identity/', include('Identity.urls')),
url(r'^Accueil/', include('Accueil.urls')),
url(r'^Home/', include('log.urls')),
url(r'^captcha/', include('captcha.urls')),
url(r'^Mairie/', include('Mairie.urls')),
]
Because I just want for example, write my IP adress in order to access to my Django application and not write all the time a complete url.
If you need some files (apache2 files, ...) please tell me which one I have to post there.
Include this in views.py file of your any app:
from django.shortcuts import redirect
def some_view(request):
return redirect('/Home/login/')
Suppose the view is in log app then,
Include this in your urls.py:
from log.views import some_view
urlpatterns = [
url(r'^$', some_view,name='index'),
url(r'^admin/', admin.site.urls),
url(r'^BirthCertificate/', include('BirthCertificate.urls')),
url(r'^Identity/', include('Identity.urls')),
url(r'^Accueil/', include('Accueil.urls')),
url(r'^Home/', include('log.urls')),
url(r'^captcha/', include('captcha.urls')),
url(r'^Mairie/', include('Mairie.urls')),
]
One method is to use RedirectView by making the following changes to your urls.py:
from django.views.generic.base import RedirectView
urlpatterns = [
url(r'^$', RedirectView.as_view(url='/Home'), name='home'),
...
]
You can either do this in Django or Configure from your webserver. Django has redirects app go through https://docs.djangoproject.com/en/1.10/ref/contrib/redirects/ for more info. You just add the source and redirect urls in the redirects section of your django admin.

Categories