Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for Django sites to set up site configuration variables?

Tags:

django

all! I am writing a Django blog site.

I am new to Django. Since Django has the philosophy of loose coupling, I believe it's best to follow their beliefs when using their framework.

So I am encountering a dilemma here:

I want to set up some variables for my blog, say, the blog title, slogan, and the maximum length of digest on the homepage of each blog I wrote, and how many blog digest should I display on the homepage per page.

I can do this by creating a new app in my Django project, and create models for my site's config variables, then read those variables from other app, but this practice obviously breaks the philosophy of loose coupling.

The only work around I can think of is setting up environment variables in my sites .wsgi file (I use Apache and mod_wsgi to serve Python scripts) But I don't think messing up with environment variable is 'clean' enough.

Can anyone suggest me a better solution?

like image 360
CarlLee Avatar asked Jun 21 '11 07:06

CarlLee


2 Answers

First thing you can do is set up those variables in your project's settings module, many apps do that:

# settings
BLOG_TITLE = 'My title'

Then, a good practice is to provide settings defaults, so your app should have a settings file

# blog/settings.py
from django.conf import settings
BLOG_TITLE = getattr(settings, 'BLOG_TITLE', 'MY default title')

# Then wherever, views or context processor
from blog import settings # See how we're not importing project's settings

title = settings.BLOG_TITLE

Another alternative is to create a "Blog" model that contains all those variables, this may invite you to make your app to have a blog tied per Django sites

from django.contrib.sites.models import Site
class Blog(models.Model):
  site = models.OneToOneField(Site) # Tied up to a Django site
  title = models.CharField(max_length=256)

Now you can change those values from your Admin interface and use them in your views or context processor

site = Site.objects.get_current() # Installed Django Sites app and middleware
blog = site.blog
print blog.title
like image 183
Jj. Avatar answered Oct 13 '22 00:10

Jj.


You can create settings or constants file in your app folder and use it. This way all your constants will be bound to your application:

apps/
  blog/
    __init__.py
    models.py
    urls.py
    constants.py # <-- here it is!

File can look like this:

BLOG_TITLE = 'My super blog'
# ...

And you can use tour constants like this:

import blog.constants
# ...
return render_to_response('index.html', {title: blog.constants.BLOG_TITLE})

And in template:

<title>{{ title }}</title>  
like image 40
Silver Light Avatar answered Oct 13 '22 02:10

Silver Light