Django: international subroutes - django

It's written in official documentation here that i18n_patterns() is only allowed in your root URLconf.
This is a problem for me because I need those URLs working:
/en/products/
/fr/produits/
/sv/produkt/
/en/products/detail/[my product name]/
/en/produits/detail/[my product name]/
/sv/produkt/detalj/[my product name]/
/sv/produkt/detalj/[my product name]/
Heres my root urls.py:
urlpatterns += i18n_patterns(
url(_(r'^produits/detail/'),
include('produits.urls', namespace="produits")
),
url(_(r'^produits/'),
include('produits.urls', namespace="produits")
),
)
So, for the lastest translation works ok, but the first one doesn't. The translation is ok, but I want to transfer the last part ('detail/') to the app produits that should handle it transparently.
How do I do?

Here's how I've solved the problem. This is not a good solution but it's the only one working for now with Django 1.8.
I've removed my routes from my "produits" application, and added them to the main urls.py which means mixing application configuration with global configuration. I dont like it.
I've also added the name of the application before each route: produits_detail and produits_index. Thus I know the app those routes are for. Once again I dont like mixing "global setting" and specific settings, but it seems I have no choice. Anyway, few lines of code, and it works pretty well.
from django.contrib import admin
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _
from produits import views as p_views
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', include(admin.site.urls)),
]
urlpatterns += i18n_patterns(
url(_(r'^produits/detail/(?P<slug>[a-zA-Z0-9-_]+)/$'),
p_views.DetailView.as_view(), name='produits_detail'),
url(_(r'^produits/'),
p_views.IndexView.as_view(), name='produits_index'),
)

Related

How to fix "error path not found" in django rest framework

I am trying to build an API of my blogging website using Django rest framework, but my URL is not matching.
I am trying Django Rest framework for the first time so I am not quite able to fix this. But I think I mess this up in url_patterns.
Here is my URL code from the main directory(the directory which contains settings.py) .
`
from django.conf.urls import url,include
from django.contrib import admin
from django.urls import path, include
from blog import views
from rest_framework import routers
router = routers.DefaultRouter()
router.register(r'apipost',views.PostViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
]
`
I am trying url http://127.0.0.1:8000/apipost and expect to get value in json format.
You need to add router.urls to your urlpatterns.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'',include('blog.urls')),
path('api-auth/',include('rest_framework.urls',namespace='rest_framework')),
]
urlpatterns += router.urls
Django REST Framework Won't magically register your router in urlpatterns, you have to do it by yourself. You can use urlpatterns += router.urls if you want to add them to the root of your urlpatterns, or url(r'^api/', include((router.urls, 'app_name'))), if you want to set subpath for them.

ImportError: cannot import name 'patterns'

I have a problem with Django, I created a 'login' app and added the URL on mysite/urls.py as below:
from django.conf.urls import include, patterns, url
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
url(r'^user-auth/', include('user_auth.urls')),
url(r'^file-upload/', include('file_uploader.urls')),
url(r'^pagination/', include('pagination.urls')),
patterns('login.views',
url(r'^login/', 'loginView'),
url(r'^greeting/', 'formView'),
url(r'^logout/', 'logoutView')
)
]
However, when I started the server, I received the message on console as:
File "/home/win/Python/mysite/mysite/urls.py", line 16, in <module>
from django.conf.urls import include, patterns, url
ImportError: cannot import name 'patterns'
Do you meet any problem like this? and any resolution do you have to resolve it.
Please please help me.
Thanks
In the latest release of Django (as of this post), patterns is not used.
You can use re_path for the same effect. For Example:
from django.urls import include, re_path
from django.contrib import admin
from myapp.views import *
urlpatterns = [
re_path(r'^admin', include(admin.site.urls)),
re_path(r'^$', home, name='home'),
]
For more information please follow: Documentation
FYI patterns has been removed in Django 1.10. See release 1.10 notes:
https://docs.djangoproject.com/en/2.0/releases/1.10/
If you want to use earlier versions (but i don't see why you would want to do it) , anything below that i.e. 1.9 should be ok, but do note it has been slotted for deprecation since 1.8 i think.
And if you're using django, especially if you are new, I don't see why you would want to use your own login app. Django has a very mature and customizable auth backend. For starters, I strongly suggest you check it out. Useful examples of usage at https://djangobook.com/authentication-views/
If you are using the latest version of Django, then patterns is has been deprecated. You would simply use URL and/or Path depending on if you are on 1.11 or 2.0. If you require patterns, then you would need to downgrade to an earlier Django version.

In Django 1.11 getting Circular Import Errors When including app URLconf files in project URLconf File

I'm new to Django, have been doing several tutorials to get really comfortable with the structuring, and am now running through the official tutorial.
I've created an polls App, which has a polls/views.py file as follows:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello, World. You're at the polls index.")
I've also created an App URLconf file polls/urls.py with the following code:
from django.conf.urls import url
from . import views
url_patterns = [
url(r'^$', views.index, name='index'),
]
This is pretty much exactly as done in the Django tutorial.
My issue is when I'm specifying url routes in the main projectname/url.py file on a project level as such:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]
When doing this, I get the following error:
django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'polls.urls' from 'ProjectFolder\\polls\\urls.py'>' 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.
This is how the official Django tutorial dictates it to be done. However, if I explicity import the polls/views.py file from the app, I can accomplish the task as follows:
from django.conf.urls import url
from django.contrib import admin
from polls import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', views.index),
]
My immediate concern is the import of every app/urls file I ever create being necessitated by this approach, as well as the obvious divergence from the official Django instruction.
I hesitated to even ask this question because I feel that such a fundamental issue has bound to have an easy fix. Any help would be greatly appreciated.
To clarify, I can get around the error by explicitly importing the view files from apps. Whenever using the Django documentation-described approach of using the include() function I receive the error. I can appreciate the value of this function, and would like to know why is giving me the error described above.
Just writte urlpatterns = [ .. and not url_patterns in your poll.views.py.

NameError name 'Views' is not defined

from django.conf.urls import url, patterns, include
from django.contrib import admin
from django.views.generic import TemplateView
from collection import *
#from collection.views import index,thing_detail,edit_thing
urlpatterns = [
url(r'^$', views.index, name='home'),
url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'),
url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'),
url(r'^things/(?P<slug>[-\w]+)/$', 'views.thing_detail' ,name='thing_detail'),
url(r'^things/(?P<slug>[-\w]+)/edit/$', 'views.edit_thing',name='edit_thing'),
url(r'^admin/', include(admin.site.urls)),
]
After running the server there is an error "NameError: name 'views' is not defined"
Any help ??
You aren't importing your own views.
Try adding this to your urls.py:
from . import views
Or if you are importing them from a specific app, try replacing . with the app name
First thing I notice is the import *, realize that this will/can cause confusion for other Developers reading your scripts. Python has a methodology that insists that explicit is better than implicit. Which in this senario means you should be explicit about what you are importing.
from django.conf.urls import url, patterns, include
from django.contrib import admin
from django.views.generic import TemplateView
from collection import views as collection_views
urlpatterns = [
# Function Based Views
url(r'^$', collection_views.index, name='home'),
url(r'^things/(?P<slug>[-\w]+)/$', collection_views.thing_detail ,name='thing_detail'),
url(r'^things/(?P<slug>[-\w]+)/edit/$', collection_views.edit_thing,name='edit_thing'),
# Class Based Views
url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'),
url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'),
# Admin
url(r'^admin/', include(admin.site.urls)),
]
Here instead of importing everything from collection I'm importing just your views and assigning them to a variable. Then using that variable in the URL definitions.
Be sure to import your views by
specifying its location and the methods inside the view to be imported on your urls.py.
from . collection import *
(line above means from current location find collection.py and import everything on it)
Happy coding!

Django import views multiple times in urls.py

In Django, is it not possible to have multiple views imports from the urls.py?
For example, I have the following code in urls.py:
from mysite.books import views
from mysite.contact import views
urlpatterns = patterns('',
(r'^contact/$', views.contact),
(r'^search/$', views.search),
)
However, the server displays an error unless I disable one of the couples. So my questions are threefold:
1) Is it not possible to have multiple import views statements?
2) How to get around this?
3) What is best practice for where to put all your views.py? One file? Multiple files? etc.
Thank you.
1) Yes it is.
2)
from mysite.books import views as books_views
from mysite.contact import views as contact_views
urlpatterns = patterns('',
(r'^contact/$', contact_views.contact),
(r'^search/$', books_views.search),
)
3) Per Django docs, "This code can live anywhere you want, as long as it’s on your Python path.". I keep all the app views in app/views.py
You can import as many things as you like, but objects have to have unique names for them to be distinguished.
There are a couple of ways of dealing with this. One is to simply import the functions, rather than the module:
from mysite.books.views import books
from mysite.contact.views import contact
This is obviously only good if you only have one or two views in each file. A second option is to import the modules under different names:
from mysite.books import views as books_views
from mysite.contact import views as contact_views
A third option is not to import the views at all, but use strings to refer to them:
urlpatterns = patterns('',
(r'^contact/$', 'contact.views.contact'),
(r'^search/$', 'book.views.search'),
)
A fourth is to have separate urls.py for each application, and include the urlconfs in the main urls.py.
I think that another option would be:
urlpatterns = patterns('mysite.books.views',
(r'^contact/$, 'contact'),
)
urlpatterns += patterns('mysite.contact.views',
(r'^search/$, 'search'),
)
as described in djangobook.