You're viewing all posts tagged with django
Dynamic ModelForm creation
That looks amazing!
def get_model_form_class(model_class, fields_list=None, exclude_list=None):
class form_class(forms.ModelForm):
class Meta:
model = model_class
fields = fields_list
exclude = exclude_list
return form_class
The idea taken from: http://stackoverflow.com/questions/297383/dynamically-update-modelforms-meta-class/297478#297478
Next order value for Django model instance
Assume, we have Django model with special weight integer field for ordering. We may want to assign its value automatically on save. Here’s the snippet implementing such behaviour:
class MyModel(models.Model):
# some fields...
weight = models.IntegerField(default=0)
class Meta:
ardering = ('weight',)
def save(self, *args, **kwargs):
self.weight = get_next_value(self, field_name='weight')
super(MyModel, self).save(*args, **kwargs)
Here’s the get_next_value implementation:
def get_next_value(instance, field_name='order', step=10, **filter):
model = instance.__class__
qs = model.objects.order_by('-%s' % field_name)
if filter:
qs = qs.filter(**filter)
try:
max_value = getattr(qs[:1][0], field_name, 0)
except IndexError:
max_value = 0
return (max_value / step + 1) * step
The implementation above can handle any field name with specified step. It can also provide next field value for filtered queryset.
Provided snippet is a part of halfbit-web-helpers collection.
Smarter Django cart
Introduction
django-carting is a basic online store application for Django. It is designed in a sketchy manner to be like a rewritable application.
Demo is available:
http://carting-demo.05bit.com
Concept
It’s conceptually differs both from Satchmo and LFS projects. Basically, that’s just a “cart application” with utilities, which can used to build full-featured online store.
The two points are:
- products catalog is always too custom to be customized
- design and html layouts are usually totally new for commercial project
So, that parts should be rewritten from scratch each time.
Feature
Cart is smartly binded to user or session. It binds to authenticated user or stores in session for anonymous user. So, cart is remebered for authenticated user and does not dissappear when session expires.
Projects powered by
Smarter Django project configuration
Two points
Generally we need different settings for Django project in development environment on localhost and on production environment. Settings may differ also across different development environments when application is developed by many programmers.
Project source is good to be stored in some VCS repository, so settings should also be stored there. Settings modifications that are common for different environments should be automatically applied after updating from repository.
How to
Here’s a couple of recipes on how to configure Django project in a bit smarter way.
1. Define settings template
Just make a copy of settings.py to settings_template.py and then import settings_template from settings:
from settings_template import *
Then you may override some settings, i.e. DUBUG flag or database settings etc.:
from settings_template import *
DEBUG = False
Note: now settings.py should not be stored in repository, but settings_template.py should be stored there.
2. Define paths based on project directory
I know many good programmers do that :) Add somewhere at start of settings, I mean settings_template.py:
import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
Now you can define media and template paths like this:
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/media/admin/'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
3. Configure serving static files
Django documentation offers to serve on not to serve static files depenging on DEBUG flag. Sometimes that may not be correct, as we may need debug mode on production environment, where static files are served by webserver.
I offer to use separate SERVE_STATIC flag in settings for this. So, here is urls.py example:
from django.conf import settings
# some urls config ...
if getattr(settings, 'SERVE_STATIC', False):
urlpatterns += patterns('',
(r'^' + settings.MEDIA_URL[1:] + r'(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT})
)
So, when I need to serve static files by development server, I just add SERVE_STATIC = True to settings.py.
Feedbacks
Please give a feedback, if it was useful or not. I hope it was :) If you have your own recipes on subject, you’re welcome to share links or snippets.
Highway to brilliant wiki, part 1. Brillixy.
Hey!
I am unsatisfied.
It’s 21st century, the age of perfect web-frameworks and rapid development. But there’s no good wiki-like engine to satisfy reasonable requirements.
There are Trac, DokuWiki and many others and others. By the way, I really appreciate Trac and DokuWiki. But I need less. And more.
So, I just need an engine which:
- has wiki-like basis: users can create, edit and delete pages,
- has hierarchical pages structure,
- can be easily themed, design is really matters,
- is written in Python / Django and uses best web-development practices.
Brillixy
I started project to make such engine. I called it “Brillixy”. It’s hosted here: http://bitbucket.org/rudi/brillixy
Some design goals are defined:
- keep specific part as tiny as possibe, reuse proven Django applications, write new ones for generic tasks
- it should has multiple-project structure, so single installation may be used by some team for a number of projects
And some design decisions are done:
- use django-treebeard for storing pages hierarchically
- use django-tagging for tagging
- use markdown as a basis for markup language, use flavours for it, use autotext to provide specific syntax
What’s next?
I’m planning to release v0.1 with most basic functions:
- creating, editing, deleting pages
- commenting pages
- simple tagging, no AJAX
- simple permissions scheme, allow everything to authenticated users
- no changesets view at this point
It should be enougth to start use it for some project. I’m planning to complete it before 9 May 2010.
Rewritable Django apps
The common good approach in designing applications for Django is write them to be reusable. Another approach is to build rewritable applications on top of reusable ones.
What’s the point?
There’re number of specific tasks, which can be splitted to generic blocks. But it seems, some “generic” blocks better not to be generic by theirs nature, because they need “a little bit specific” usage for every project.
We can build such apps in two ways:
- make big reusable application with customization settings or
- build rewritable application
Reusable vs Rewritable
Here’s comparison table of approaches.
| Reusable | Rewritable |
|---|---|
| Try to cover most generic use cases “out-of-box” and provide settings | Set of “sketches” to provide basic use cases with examples for usages and possible extendings |
| Source code is redundant as it covers different use cases | Source code is minimalistic |
| Usually depends only on Django and extra generic Python libs | Usually are build on top of other proven applications |
| You’d better not modify application source | Application source can be rewritten or extended using provided basis |
Examples
Reusable:
- django-tagging
- sorl-thumbnail
- and many other Django apps
Rewritable:
- django-accounts-basic
- (… actually, it’s hard to find examples, as that’s not common practice to publish such apps, but they MAY be useful! Here may be: basic e-shop application, basic wiki application, etc. Yes. I know, there ARE e-shops and wikis, but they are designed to be reusable, not to be rewritable).
Conclusions
Both approaches are for applications made by programmers for programmers.
Reusable applications are good for providing “out-of-box” solutions for generic tasks, they are rather “solid”, so fine customization is hard or can cause overcomplication.
Rewritable applications are good for providing code basis on top of reusable apps. They must be clean and as small as possible and it’s critical to provide working examples.