django url variable to get parameters - django

I've a part of my urls.py file as follow:
urlpatterns = patterns('',
url(r'^$', DetailHomePublic),
url(r'^demo/$', TemplateView.as_view(template_name='public/demo.html')),
url(r'^privacy/$', TemplateView.as_view(template_name='public/privacy.html')),
url(r'^terms/$', TemplateView.as_view(template_name='public/terms.html')),
url(r'^login/$', Login),
url(r'^logout/$', Logout),
url(r'^lost_password/$', LostPassword),
url(r'^register/$', Register),
)
I've done a middleware which catch if a parameters named language is passed. It's used to change the language of the website.
class SetLanguageMiddleware:
"""
Middleware which changes the language if the GET variable named language has been set with a valid language referenced on the settings.py file
"""
def process_request(self, request):
from django.utils import translation
from django.conf import settings
from django.utils.translation import LANGUAGE_SESSION_KEY
if 'language' in request.GET:
language = request.GET['language']
#check if the language is defined in the settings.LANGUAGES global settings
if any(language in code for code in settings.LANGUAGES):
#set the given language in the session and active it for the current page too
request.session[LANGUAGE_SESSION_KEY] = language
translation.activate(request.session[LANGUAGE_SESSION_KEY])
Now, for only this given page, I'd like to add a language prefix to provide a multilingual website.
Is it possible to catach the prefix on the urls file and add it to the GET parameters, to have something like that:
urlpatterns = patterns('',
url(r'^(?P<language>[a-z]{3})$', DetailHomePublic),
url(r'^(?P<language>[a-z]{3})demo/$', TemplateView.as_view(template_name='public/demo.html')),
)
...
Thank you

Related

django use of quotes in url template tag

In myusers.urls I have set app_name = 'users' and name='users' in the urlpatterns.
Why are quotes needed around users:users in the following:
/users
is that a shortcut? Do the quotes tell django to resolve the address? Would the following work?
/users
urls.py
from django.urls import path
from . import views
app_name = 'users'
urlpatterns = [
path('', views.index, name='index'),
path('users/', views.users, name='users'),
]
views.py
from django.shortcuts import render
from myusers.models import *
# Create your views here.
def index(request):
return render(request, 'myusers/index.html')
def users(request):
users = AllUser.objects.all()
return render(request, 'myusers/users.html', {'users':users})
Unquoted arguments are template variables, not python variables, not module references, but only names with values provided to the template. This is the "context" passed to templates from views, where the key is the variable name. It can also be variables inside for loops and with constructs.
Quoted arguments are strings.
The URL tag uses its string arguments to resolve urls, by using Django's reverse and that's it. The string "users:users", refers to the URL namespace "users" and the view with name "users".

Python - Django add multiple urlpatterns for multiple views of template

I'm very very new to Python 3 and Django and I get to the following problem: I use a standard Template and now how to set it up when there is 1 view. But I don't get the code right for multiple views. I currently run the page locally
At the moment I have tried to change different orders within urlpatterns, and they do work when only 1 url in in there, but I can't get the second one in
views.py
from django.shortcuts import render, render_to_response
# Create your views here.
def index(request):
return render_to_response('index.html')
def store(request):
return render_to_response('store.html')
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from myapp import views as views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^store/$', views.store, name='store'),
url(r'^admin/', admin.site.urls)
]
urlpatterns += staticfiles_urlpatterns()
I would like the url pattern that lets me go to the index view and the store view
EDIT:
Full code is shared via: https://github.com/lotwij/DjangoTemplate
The error in the comments shows you are going to http:/127.0.0.1:8000/store.html, but your URL pattern url(r'^store/$', ...) does not include the .html, so you should go to http:/127.0.0.1:8000/store/.
The Django URL system uncouples the URL from the name of the template (sometimes the view doesn't even render a template!). You could change the regex to r'^store.html$ if you really want .html in the URL, but I find the URL without the extension is cleaner.

Django Caching on front-end

I was working with 2 applications that are within a DJango project: "customer" and "vendors". Each application has a HTML file named "testindex.html".
Whenever I typed:
http://myhost/customer/basic_info
the correct page would show up
If I typed
http://myhost/vendors/basic_info
the page from http://myhost/customer/basic_info would show up
I found out that it was due to caching (since both applications use "testindex.html"). So again, "testindex.html" is caching.
How can one get around this problem?
TIA
Details are listed below. I have the following views defined:
urls.py for the project
urlpatterns = [
... snip ...
url(r'^customer/', include('libmstr.customer.urls')),
url(r'^vendors/', include('libmstr.vendors.urls')),
]
views.py for customer
from django.shortcuts import render
def basic_info(request):
return render(request, 'testindex.html', {})
views.py for vendors
from django.shortcuts import render
def basic_info(request):
return render(request, 'testindex.html', {})
urls.py for customers
from django.conf.urls import url
from . import views
# list of templates
app_name = 'customer'
urlpatterns = [
url(r'^basic_info/$', views.basic_info, name='basic_info'),
]
urls.py for vendors
from django.conf.urls import url
from . import views
# list of templates
app_name = 'vendors'
urlpatterns = [
url(r'^basic_info/$', views.basic_info, name='basic_info'),
]
It sounds like you have two templates, customers/templates/testindex.html and vendors/templates/testindex.html.
When you call render(request, 'testindex.html', {}), the app directories template loader searches the templates directory for each app in INSTALLED_APPS, and stops the first time it finds a match. If customers is above vendors in INSTALLED_APPS, then it will always use the customers template.
For this reason, Django recommends that you name your templates customers/templates/customers/testindex.html and vendors/templates/vendors/testindex.html, and change your views to use customers/testindex.html and vendors/testindex.html. This way you avoid clashes.

Mezzanine ignores the view, displays the template but does not pass the context

I created a view for my model, with the corresponding urls and template files. Then, in the admin panel, I have created a Rich text page, specifying the same URL (ingredients) defined in urlpatterns. Mezzanine ignores the view, displays the template but does not pass the context.
How can I solve it?
These are the codes:
models.py
from django.db import models
from mezzanine.pages.models import Page
from django.utils.translation import ugettext_lazy as _
class Ingredient(Page):
name = models.CharField(max_length=60)
information = models.TextField(null=True, blank=True, verbose_name=_("Description"))
views.py
from django.template.response import TemplateResponse
from .models import Ingredient
def ingredients(request):
ingredients = Ingredient.objects.all().order_by('name')
templates = ["pages/ingredients.html"]
return TemplateResponse(request, templates, {'ingredients':ingredients})
urls.py
from django.conf.urls import url
from .views import ingredients
urlpatterns = [
url("^$", ingredients, name="ingredients"),
]
TemplateResponse does not expect the request in its arguments. See the docs.
return TemplateResponse(templates, {'ingredients':ingredients})
However I expect you meant to use the standard render function there:
return render(request, "pages/ingredients.html", {'ingredients':ingredients})
Ok, the solution has been define my app urls before any other definition in my project urls.py file.
project_name/project_name/urls.py
# Add the urlpatterns for any custom Django applications here.
# You can also change the ``home`` view to add your own functionality
# to the project's homepage.
urlpatterns = [
url(r'^ingredients/', include("apps.ingredients.urls")),
]
urlpatterns += i18n_patterns(
# Change the admin prefix here to use an alternate URL for the
# admin interface, which would be marginally more secure.
url("^admin/", include(admin.site.urls)),
)

Urls.py says my view is not defined (class based view)

This is my urls.py for my project:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^CMS/', include('CMSApp.urls')),
url(r'^admin/', include(admin.site.urls)),
]
and this is my urls.py for my app (CMSApp):
from django.conf.urls import patterns, url
urlpatterns = patterns(
'CMSApp.views',
url(r'^users$', user_list.as_view()),
url(r'^users/(?P<pk>[0-9]+)$', user_detail.as_view()),
)
When I go to
CMS/users
it gives me a name error saying that
name 'user_list' is not defined
Any idea why?
When I do
from CMSApp import views
urlpatterns = patterns(
'',
url(r'^users$', views.user_list.as_view()),
)
it works but I'm just wondering why the former does not work?
It appears that you're using Django 1.8 for your project; the behavior you're trying to use was removed in 1.8, as documented here: https://docs.djangoproject.com/en/1.8/releases/1.8/#django-conf-urls-patterns
You have to import
from CMSApp.views import user_list
Otherwise django won't know user_list is defined.
If you just use user_list without importing it explictly, python will consider it is a local variable and return NameError.
Once user_list is defined in views.py, you have to explicitly tell python to search for it there.