Django - Proper way to separate site-specific content from templates? - python

I have had trouble putting my question into words to Google the answer, but here goes:
Let's say I have a few strings that appear in multiple places in my Django project. For example, the site owner's name, contact info, the text on the main page, etc.
Right now they are all hard-coded into my templates. Sometimes these need to be changed, and it's especially a pain to replace the strings that appear in multiple places.
What is the proper Django way to pull this data out of the templates and into one central location?
Thanks in advance, I want to do this the right way :)

You can use an app such as django-chunks which allows you to save small pieces of text in the database and add them to your templates using simple template filters (you reference each piece of text with a slug). So in your template you would have:
{% load chunks %}
<html>
<head>
...
</head>
<body>
<div id="content">
...
</div>
<div id="sidebar">
{% chunk "sidebar_disclaimer" %}
</div>
<div id="footer">
{% chunk "footer_text" %}
</div>
</body>
</html>
This would create two new entries in the admin interface where you could add and adjust the text that is to appear in the sidebar and footer
There are plenty of alternatives:
django-flatblock
django-siteblocks
django-generic-flatblocks

Related

I cannot get images to work on my django project(this is my first one and im having trouble)

I have an img folder in the same directory as my html files. I want to put images onto my site but I am doing something wrong.
this is the code:
{% block a %}
<div class="row">
<div class="col-sm-4 center">
<img src="img/img01.jpeg">
</div>
</div>
{% endblock %}
this is what happens when I run the local server.
this is my file directory
Websites generally need to serve additional files such as images, JavaScript, or CSS. In Django, we refer to these files as “static files”.
Those files need to be handled another way as your templates. The documentation can be found here.
It comes basically down to defining a seperate static directory inside your app. It is really good explained in the documentation.

Nested Django view with .html inserted using include tag

I would like to know if anyone has any best practice recommendations for rendering a view within a view in Django, or something with a similar effect where both views can have their own context and methods.
I am currently rendering the dropdown using the built-in include tag. So the nested .html is using the same Django view as the rest of the page. And all the context is coming from the main view as shown below. I would like to give this dropdown its own Django view so that I only perform certain database queries and other calculations if the dropdown is opened.
<div class="container-fluid">
<div class="row">
<div class="col-6">
</div>
<div class="col-2 d-flex justify-content-center">
{% include nested.html %}
</div> ...
It would be nice if someone with experience in this could let me know what they think, and if it even makes sense to try and split this into 2 views.
In summary. I would like to know if I can somehow render a separate view using something similar to the include Django tag. So that I have control over where the view gets rendered.
Below I have outlined my implementation of the solution below, using custom inclusion tags as suggested in the comments to my question.
You can make a custom template tag file in project directory and then register these in the template library. e.g:
template_tags.py
from django import template
from users.models import Organisation
register = template.Library()
#register.inclusion_tag('nested.html', takes_context=True)
def nested_template(context, param=None): #param to pass variables from main view
context.update({
'data_list': get_data_list(param)
'organisation_id': param,
})
return context
def get_data_list(self,param):
data_list = ... #do all queries needed.
return data_list
In the template tag you point to your nested.html which does whatever you need it to do. For example:
nested.html
{% for data in data_list %}
<h4> {{data}} </h4>
{% endfor %}
Then to include the template, in your main view template:
{% load nested_template %} #at the top or anywhere before using it
{% nested_template param %} #where you want the template included
Hopefully clear enough and may assist someone

Sending messages using Django Postman

I am trying to use Django-Postman and have gotten as far as being able to see the templates on the webpage after I press the link but I don't know how send messages works. According to the write view there should be a form loaded but all I get is the links to the other pages in the template. If someone could explain how to get this to work it would be fantastic.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav ">
<li>MyCourse</li>
<li>Timetable</li>
<li>logout</li>
<li>Inbox</li>
</ul>
</div>
Recently had to set up postman myself, and based just off your snippet, I'm going to assume you wrote the ul element yourself.
So, if that's the case, postman actually expects to handle all of that for you. According to the docs, you need to create a base.html template inside your own template directory. A few blocks are expected to be present inside this template, namely {% title %} (text it will add to the page's title), {% extrahead %} (some extra js and css), {% content %} (would contain the missing forms you're looking for) and {% postman_menu %} (the menu links automatically generated by postman).
You could always create the menu links yourself, but I'd suggest you create a /postman folder in your app's template folder, then copy the base.html from the installed postman app (this contains the code for how to layout the ul). Just a little more django-esque, and usefull if you need to fiddle with the names of the template tags, etc, but that's up to you.
Hope this helps, happy coding.

How to use django base extension along with angularjs ng-include?

I'm using ng-include like this
HTML
<div ng-app="myapp" ng-controller="myctrl" ng-include="/static/html/main.html"></div>
main.html
{% extends "app\base.html" %}
{% block content %}
<div ng-controller="myctrl1">
some content
</div>
{% endblock %}
base.html
<div ng-controller="myapp2">some content </div>
but this is not working, it is showing an errorr "SyntaxError: Unexpected token % at Object.parse (native)"
Please suggest me a better way to implement this.
I don't quite know what you're trying to do here. Angular templates and Django ones are quite different, even if they superficially share the same {{ var }} syntax. You can't inherit an Angular template from a Django one, or vice versa.
But there's no reason to want to do that anyway. Angular is already loading the template as a partial, which means it will be inserted into the div in base.html. There's no need for inheritance here at all.

In Django, what is the best way to manage both a mobile and desktop site?

I'd like everything to function correctly, except when it's mobile, the entire site will used a set of specific templates.
Also, I'd like to autodetect if it's mobile. If so, then use that set of templates throughout the entire site.
Have two sets of templates, one for mobile, one for desktop. Store the filenames in a pair of dictionaries, and use the User-agent header to detect which set should be used. Also allow manual selection of which site to use via a session entry.
If you place a class on your body (Django uses something similar to specify what column style to use), you could use the same templates but simply use different stylesheets. I'm not sure what main differences you are using separate templates for, but this might allow you to cut down on re-coding the templates multiple times.
best practice: use minidetector to add the extra info to the request, then use django's built in request context to pass it to your templates like so.
from django.shortcuts import render_to_response
from django.template import RequestContext
def my_view_on_mobile_and_desktop(request)
.....
render_to_response('regular_template.html',
{'my vars to template':vars},
context_instance=RequestContext(request))
then in your template you are able to introduce stuff like:
<html>
<head>
{% block head %}
<title>blah</title>
{% if request.mobile %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-mobile.css">
{% else %}
<link rel="stylesheet" href="{{ MEDIA_URL }}/styles/base-desktop.css">
{% endif %}
</head>
<body>
<div id="navigation">
{% include "_navigation.html" %}
</div>
{% if not request.mobile %}
<div id="sidebar">
<p> sidebar content not fit for mobile </p>
</div>
{% endif %>
<div id="content">
<article>
{% if not request.mobile %}
<aside>
<p> aside content </p>
</aside>
{% endif %}
<p> article content </p>
</aricle>
</div>
</body>
</html>
There are different strategies.
If you've a lot of views that renders to template files for the web version, and don't want to rewrite all views checking if the request is coming from a mobile user-agent, you'd be better writing a Middleware.
A workflow could be like this:
def process request:
if from_mobile:
settings.TEMPLATE_DIRS=settings.TEMPLATE_MOBILE_DIRS
else:
settings.TEMPLATE_DIRS=settings.TEMPLATE_WEB_DIRS
There is only a little problem here: As Django Documentation reports, it's not correct to change settings at runtime: http://docs.djangoproject.com/en/dev/topics/settings/#altering-settings-at-runtime
So you may want to call
django.conf.settings.configure(default_settings, **settings)
The answer depends heavily on the type of your target audience. If you target for modern mobile browsers equivalents to their desktop counterparts (such as WebKit-based), all you need is specific stylesheet with appropriate media query (you are basically designing for low-res rather than mobile).
Totally different strategy is needed if your site (e.g. airline schedules) must to be accessible widest possible range of mobile devices, some of running very old / limited browsers. Then custom (html) templates may be easiest way to go.
You might want to check out mobilesniffer and django-bloom to see if they fit your purposes.

Categories

Resources