Where to put REST API in Django - python

Here is a quote from Two Scoops of Django: Best Practices For Django 1.6:
In the past, we placed all API view code into a dedicated Django app
called api or apiv1, with custom logic in some of the REST views,
serializers, and more. In theory it’s a pretty good approach, but in
practice it means we have logic for a particular app in more than just
one location.
Our current approach is to lean on URL configuration. When building a
project-wide API we write the REST views in the views.py modules, wire
them into a URLConf called something like core/api.py or
core/apiv1.py and include that from the project root's urls.py
module. This means that we might have something like the following
code:
# core/api.py
""" Called from the project root's urls.py URLConf thus:
url(r" ˆ api/", include("core.api"), namespace="api"),
"""
from django.conf.urls.defaults import patterns, url
from flavors import views as flavor_views
from users import views as user_views
urlpatterns = patterns("",
# {% url "api:flavors" %}
url(
regex=r" ˆ flavors/ $ ",
view=flavor_views.FlavorCreateReadView.as_view(),
name="flavors"
),
# {% url "api:flavors" flavor.slug %}
url(
regex=r" ˆ flavors/(?P<slug>[-\w]+)/ $ ",
view=flavor_views.FlavorReadUpdateDeleteView.as_view(),
name="flavors"
),
# {% url "api:users" %}
url(
regex=r" ˆ users/ $ ",
view=user_views.UserCreateReadView.as_view(),
name="users"
),
# {% url "api:users" user.slug %}
url(
regex=r" ˆ users/(?P<slug>[-\w]+)/ $ ",
view=user_views.UserReadUpdateDeleteView.as_view(),
name="users"
),
)
But I don't understand where to put core/api.py. Is this a separate Django app called core? Where api.py should sit?

It means create the file you have as core/api.py (along with an empty core/__init__.py file) and then add the line url(r" ˆ api/", include("core.api"), namespace="api") to the root urls.py file of your project.
You don't have to call it core/api.py, that is just a suggestion from the authors
what does we write the REST views in the views.py modules mean?
It means what you've done, for each of the Django apps in your project, such as flavors, users they will have a views.py (or views/*.py) in them where you'd put the code for both the API and non-API views. (this is just a sane naming convention, nothing more... Django relies on the urlpatterns to tell it how to connect url routes to view code)
It's great to build up stuff like this from scratch as a way to learn Django. If you're doing a serious REST API project have a look at Django REST framework.

Related

Refer to my (reusable) app's url namespace in Django

I want to write a reusable Django application.
I tell my users to add the following to their urls.py
path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'),
And in my urls.py I want to have a view login_callback.
Now in my view, I need to get a value of slack_integration:login_callback.
I can trust the user that he/she will integrate it with slack_integration prefix and use it. But is this the best practise? Can I somehow get the name of the namespace for the app if user chooses a different name for it?
Thanks a lot!
Using namespace= within urls.py files is no longer supported, as it moves something specific to the Django app outside of the Python package that is the Django app.
The best practice now is to define the app_name within the urls.py file inside the Django app.
The old way: DON'T DO THIS (pre-Django 2.0)
the root urls.py
path('slack/', include(('slack_integration.urls', 'slack_integration'), namespace='slack_integration'),
The new way: DO THIS! (Django 2.0+)
the root urls.py
from django.urls import path, include
urlpatterns = [
path('slack/', include(('slack_integration.urls', 'slack_integration')),
]
slack_integration/urls.py
from django.urls import path
app_name = "slack_integrations"
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
As you can see, this keeps the namespace for the patterns within the app itself, along with the templates most likely to use it. The days of extra instructions on how to include an app are over! Good luck.

Can I reference project URLs in Django templates by providing the project name?

I have a Django project called reports with apps report_1, report_2 etc.
For certain reasons, I want to treat the project as an app, so I have added reports to INSTALLED_APPS alongside report_1 and report_2 and also created views.py file and templates folder in the main project folder (where settings.py sit).
In the urls.py I have added app_name = reports.
However, calling the url from within template will work only if I skip the app name: so {% url 'reports:index' %} will throw
'reports' is not a registered namespace'
error, but {% url 'index' %} will work.
Why is that so? I thought Django traverses all apps listed in INSTALLED_APPS, looks for app_name (which is provided) and matches it with URL name.
app_name does not work in the root url config. See ticket 28413 and this discussion on the django-developers mailing list.
If you really want to include some patterns under the report namespace, you can include a 2-tuple containing a list of url patterns and a namespace.
reports_patterns = ([
path('myurl', views.my_view, name='myview'),
], 'reports')
urlpatterns = [
...
path('', include(reports_patterns)
...
]
You could then use {% url 'reports:myview' %} in the template.
See the docs on URL namespaces and included URLconfs for more info
you can add :
app_name = 'polls'
in above urls.py on which app your are use :
urlpatterns=[
....
]
and then every where you need load template use:
{% url 'appname:index.html' %}

Current way to get Home URL (Domain) in Django Template?

This is so simple, yet it seems that its not provided.
Basically, if my site is...
http://www.example.com
http://127.0.0.1:8000
Or a non-root install like
http://www.example.com/ye-ol-django/
http://127.0.0.1:8000/ye-ol-django/
...I would think django would know this and have a constant available in templates.
The solutions I find involve:
Set it up in settings.py with SITE_URL =
Reference settings.py in a view.
Finally access it in the template with {{ SITE_URL }} or something.
Not very D.R.Y.
Not to sound spoiled, but doesn't django provide the {{ GET_ME_THE_ROOT_URL }} reference?
Sorry, django has trained me to expect goodies like this.
Just sayin' if I was writing a framework that would be the first thing I do, besides putting a small fridge beside my desk full of hotpockets and a microwave a safe but close distance away.
Ha! Nice question.
Let's break down your problem. You want some data to be available across all the templates available in your project. And also, you want to provide the value once and not repeat it across views.
Template Context Processors is the thing you are looking for.
In your settings.py file, add a new context_processor to the list of TEMPLATE_CONTEXT_PROCESSORS.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.media",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"your_app.context_processors.root_url"
)
Then, inside your_app, create a file named context_processors.py. This file will contain the following code.
from django.conf import settings
def root_url(request):
"""
Pass your root_url from the settings.py
"""
return {'SITE_URL': settings.ROOT_URL_YOU_WANT_TO_MENTION}
And, in each of your templates, you'll have a {{SITE_URL}} present in the context depending on the value you provide to ROOT_URL_YOU_WANT_TO_MENTION in your settings.py file.
Django sure spoils everyone. But provides the mechanisms to keep you spoilt.
Hope this solves your problem.
If you're rendering the template from a request, you can just name your root view, then refer to it with the url tag:
In your root urls.py:
url(r'^$', HomePageView.as_view(), name='home'),
In template.html:
click here
More good info over in the django docs: https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#url

How to structure a multilanguage Website in Django 1.6

I’m writing a simple multilanguage website in Django and I struggle a bit with switching languages. I thought it would be good to have different urls for each language (e.g. /en/contact/ for the english site, /de/kontakt/ for the german site). Maybe this does not only look better but does also make sense in the SEO context.
So I have in urls.py:
urlpatterns = pattern(‘’,
url(r’^de/kontakt/$’, mysite.views.DeKontaktView, name=‘kontakt’,),
url(r’^en/contact/$’, mysite.views.EnContactView, name=‘contact’,),
)
Now I’d like to have links on every page (in the base template) to switch the language between german and english. In the Django documentation I found the ‘set_language redirect view’ (https://docs.djangoproject.com/en/1.6/topics/i18n/translation/#the-set-language-redirect-view).
My problem is where and how to tell the view where it should redirect when switching languages. I do not always want to redirect to the frontpage of my site but to the corresponding page in the other language - which has a completely different url - not only a different language prefix in the url.
Since the ‘set_language redirect view’ seems to use the referrer unless there is a next parameter in the post data, my first idea was something like this:
views.py:
def EnContactView(request):
…
if request.LANGUAGE_CODE == ‘en’:
return render_to_response(‘en/contact.html’), context)
else:
return redirect(‘/de/kontakt/‘)
def DeKontaktView(request):
…
if request.LANGUAGE_CODE == ‘de’:
return render_to_response(‘de/kontakt.html’), context)
else:
return redirect(‘/en/contact/‘)
But I think this may not be a good solution since this would also redirect depending on the browser language. For example: if someone with browser language ‘en’ visits one of our german urls directly, e.g. via Google. Since there is neither a cookie ‘en’ nor a language choice in the session, the visitor would be redirected to the english url - which is not intended.
So what are the best practices for these situations? To sum up: I have completely different urls for the languages - not only a different language prefix in the url. For every language I do have one template (directories templates/en/ and templates/de/).
How can I switch between the corresponding pages in different languages?
and by the way: Is it possible to not use a form as a language switcher but simple links ‘de’ and ‘en’?
It would be great if someone could help me out. The “language thing” is quite confusing for a django noob.
https://docs.djangoproject.com/en/1.6/topics/i18n/translation/#translating-url-patterns
#setting.py
gettext = lambda s: s
LANGUAGES = (
('en', gettext('English')),
('de', gettext('De')),
)
#url
from django.http import Http404
from django.conf.urls.i18n import i18n_patterns
urlpatterns += i18n_patterns('',
url(r'^contact/$', mysite.views.ContactView, name='contact'),
)
#view
def ContactView(request)
if request.LANGUAGE_CODE == 'de':
return render_to_response('de/kontakt.html')
if request.LANGUAGE_CODE == 'en':
return render_to_response('en/contact.html')
raise Http404
django.conf.urls.i18n.i18n_patterns will take care of the language prefix part, django.views.i18n.set_language of (most of) the language switching part, and you can use django.utils.translation.ugettext_lazy to translate your url patterns just like any other translatable "static" text. You'll still have to handle content's translation one way or another (there are quite a few more or less pluggable apps solving this for Django models), but this part really depends on your application's domain and logic.
Here is a more full blown solution for those having problems with translations or are creating a multi-language site.
In settings.py …
Add to MIDDLEWEAR_CLASSES, locale, it enables language selection based on request:
'django.middleware.locale.LocaleMiddleware',
Add LOCALE_PATHS, this is where your translation files will be stored, also enable i18N:
USE_I18N = True
LOCALE_PATHS = (
os.path.join(PROJECT_PATH, 'locale/'),
)
Set LANGUAGES that you will be translating the site to:
ugettext = lambda s: s
LANGUAGES = (
('en', ugettext('English')),
('fr', ugettext('French')),
('pl', ugettext('Polish')),
)
Add i18n template context processor, requests will now include LANGUAGES and LANGUAGE_CODE:
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n', # this one
'django.core.context_processors.request',
'django.core.context_processors.static',
'django.contrib.messages.context_processors.messages',
)
Nest, in urls.py :
In url_patterns, add the below, it will enable the set language redirect view:
url(r'^i18n/', include('django.conf.urls.i18n')),
See Miscellaneous in Translations for more on this.
Add the following imports, and encapsulate the urls you want translated with i18n_patterns. Here is what mine looks like:
from django.conf.urls.i18n import i18n_patterns
from django.utils.translation import ugettext_lazy as _
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
)
urlpatterns += i18n_patterns('',
(_(r'^dual-lang/'), include('duallang.urls')),
(r'^', include('home.urls')),
)
Note: You can also drop your admin urls into the i18n_patterns.
Now anywhere you use text and want to convert it, import lazytext and wrap every string with it like so _('text'), you can even go to your other urls.py files and do url translation like so:
url(_(r'^dual_language/$'), landing, name='duallang_landing'),
You can wrap text that you want translated in your other files, such as models.py, views.py etc.. Here is an example model field with translations for label and help_text:
name = models.CharField(_('name'), max_length=255, unique=True, help_text=_("Name of the FAQ Topic"))
In your html templates...
Now you can go into your templates and load the i18n templatetag and use trans and transblock on the static stuff you want to translate. Here is an example:
{% load i18n %}
{% trans "This is a translation" %}<br><br>
{% blocktrans with book_t='book title'|title author_t='an author'|title %}
This is {{ book_t }} by {{ author_t }}. Block trans is powerful!
{% endblocktrans %}
Now run a makemessages for each of your locales:
./manage.py makemessages -l pl
And now all is left is to go into your /locales folder, and edit each of the .po files. Fill in the data for each msgstr. Here is one such example of that:
msgid "English"
msgstr "Angielski"
Leave the ones that make sense blank to pick up the default language.
And finally compile the messages:
./manage.py compilemessages
There is a lot more to learn with translations and internationalization is closely related to this topic, so check out the docs for it too. I also recommend checking out some of the internationalization packages available for Django like django-rosetta, and django-linguo. They help translate model content, django-rosetta does not create new entries for this in your database, while django-linguo does.
If you followed this you should be off to a good start. I believe this is the most standardized way to get your site running in multiple languages. Cheers!

Django named routes like Laravel

I'm starting to learn about Django Framework. I have this urls in my urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# Examples:
url(r'^hello/$','article.views.hello'),
)
My questions are: Can I give this routes a name, like i would in Laravel? How can i reference those named routes from template?
Thanks!
Yes, you can:
url(r'^hello/$','article.views.hello', name="hello"),
You would reference it in a template as:
{% url 'hello' %}
For more information, including how to give arguments to a named URL, see here.

Categories