This model is designed for my webshop. The Client-object is very 'stretch-able' by defining more fields to the client. These extra fields ares stored in the ClientConfig-object.
Be sure to create a new Client-instance first and SAVE it! Without a client.id the ClientConfig won't work.
Here's a nice way of easily passing only certain settings variables to the template. Because of the way Django looks up context processors, we need a little hack with sys.modules. The [blog entry is here](http://sciyoshi.com/blog/2008/jul/10/dynamic-django-settings-context-processor/).
This snippet provides support for dynamically importing templates. This helps you to avoid naming collisions and other problems.
The format is as follows:
1. `module.submodule.app:template.html`
2. `module.submodule.app:subfolder/template.html`
3. `module.submodule.app:/subfolder/template.html`
Assuming the module is located in '/var/', these would map (respectively) to:
1. `/var/module/submodule/app/templates/template.html`
2. `/var/module/submodule/app/templates/subfolder/template.html`
3. `/var/module/submodule/app/templates/subfolder/template.html`
The colon splits the the python module from the template directory, meaning you can import from anything that has a "templates" directory. This helps me to avoid naming collisions by specifying the application I'm referring to, without having to put long paths in my extends and include tags inside other templates. It's also dynamic in that if I move a library outside the old path, it has no effect on the templates.
To get this rolling, in your `settings.py` file, add the following::
>TEMPLATE_LOADERS = (
> 'addons.template_loader.load_template_source', # <--- add this
> 'django.template.loaders.app_directories.load_template_source',
> 'django.template.loaders.filesystem.load_template_source',
># 'django.template.loaders.eggs.load_template_source',
>)
This widget will render a chained select menu powered by JavaScript to make it easier to identify foreign keys. This widget includes danjak's form decorator (http://www.djangosnippets.org/snippets/59/), and Xin Yang's chained select javascript functions (http://www.yxscripts.com/).
I developed this to be used with an IT inventory system. See screenshot here: http://bayimg.com/cAjAGAabN
The models are laid out that location -> area -> room. But the __str__ of area and room did not include unique fields, so the built-in single select box that django uses for ForeignKey's did not work for me.
A few notes:
1: I will not be maintaining this, I am only putting it out here in case it helps others.
2: The chained select menus will only be available to the first form on the page. Reason being: the template names the form, not the django backend. So, I had to reference the form in javascript as document.forms[0].
3: Due to the javascript processing, the chain select menu will not show current values other than the default specified in the javascript. Thus, form_for_instance and a dict of values passed to form_for_model will not pre-set the chained select.
4: The rendered selects are put into a vertical table. No other layout is supported.
5: The select field names for upper-leveled options are "chain_to_[destination_field_name]__[current_selects_model_name].
6: The select name for the destination option is the name that django sends internally, which is usually the field name. The value of each option in the select is the primary key associated with that object.
7: I tried to get this built in to the native form_for_model helper function for use with the default admin site, but failed miserably.
How to get it working (quick version):
1: Define your models
2: From your view, import the form_decorator and ChainSelectWidget (I put them in CustomWidgets.py and made sure it was in the path).
3: Build arguments for the form_decorator eg:
widget_overwrite=dict(field=ChainSelectWidget(order=[(top, 'order_field'), (next, 'order_field'), (field, 'order_field)]
4: Send arguments to form_decorator eg:
callback = form_decorator(widgets=widget_overwrite)
5: Build modified form eg:
mod_formclass = form_for_model(field, formfield_callback=callback)
6: Instance the modified form eg:
instanced_form = mod_formclass()
7: Send instanced form to the templating engine
8: From the template, import the chainedselects function file (replace [] with <>) eg:
[head][script language="javascript" src="path/to/chainedselects.js"][/script]
9: Display the form object as you normally would.
If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data.
These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example:
from lazy_lookup import lazy_lookup_dict
def some_view(request):
users = User.objects.values('id', 'username')
articles = Article.objects.values('user', 'title', 'body')
articles = dict([(x['user'], x) for x in articles])
return render_to_response('some_template.html',
{'data': lazy_lookup_dict(users, key=lambda x: x['id'],
article=articles,
item_name='user')})
Then in the template layer you'd write something like:
{% for user_data in data %}
{{ user_data.user.username }}, {{ user_data.article.title }}
{% endfor %}
Somebody mentioned in #django the other day that they have multiple databases with the same schema... Well *lucky me* so do I!!
This is one way to work with this issue. I've also included migrate_table_structure just in case the schema doesn't exist in the new database yet.
As per the multiple-db-support branch, write all of your databases into the OTHER_DATABASES in settings.py. You can now copy models from your various models.py files and use them in different databases at the same time.
This can also be used to migrate databases from one dialect to the other without having to translate your data into an interim format (e.g. csv, XML). You can just do:
qs = MyModel.objects.filter(**filters)
NewModel = duplicate_model_and_rels(MyModel, 'new_db')
#Assuming that the schema is already in new_db:
for mod in qs:
new = NewModel()
new.__dict__ = mod.__dict__
new.save()
I tried this using some hacks with SQLAlchemy, and the above approach is a huge amount quicker! I've used this to copy some stuff from an oracle db, into a sqlite db so i could carry on working later and transferred about 20,000 in 5 mins or so.
GOTCHAS
========
This only works against my copy of multi-db as I've made a couple of changes. My copy is substantially the same as my patch attached to ticket 4747 though, so it might work to a point (especially the data migration aspect). If it doesn't work hit me up and I'll send you my patch against trunk.
I'm not too crazy about the code in copy_field, it works fine, but looks ugly... If anyone knows of a better way to achieve the same, please let me know.
Nutshell: Subclass this form with the required fields defined to automatically generate a form based on a model in a similar fashion to how form_for_model works, but in a way that tries to be a little easier if you want to customize the form. It handles updates and creations automatically as long as any database field requirements are met.
This is something I made while trying to understand newforms, and is my own attempt at something between the simplicity of a stock form_for_model form, and a full blown custom form. The proper way is to use a callback function to customize form_for_model, but that felt cumbersome so I did it my way :) It works for me, but I'm relatively new to both python and Django so please test yourself before trusting.
This is a reasonably straight forward port of functionality provided by the `django.utils.dateformat` module into a method extending JavaScript's Date object. Its intended use is to allow client-side dynamic content to share the same date & time string formatting as Django template markup. By using this in conjunction with a context processor (to pass a format string to all templates) you can switch formats for both server-generated & client-generated dates across a complete site with a single setting.
The function supports *almost* the entire format -- as listed by the Django documentation for the [now template tag](http://www.djangoproject.com/documentation/templates/#now) -- with the exception of "I" & "T".
As a 'dumb' illustration, the following template tag usage:
It is {% now "jS F Y H:i" %}
...could equate to the following:
It is <script type="text/javascript">var now = new Date(); document.write(now.strfdate('jS F Y H:i'));</script>
It's not extensively tested (I only wrote it over the weekend), but seems to be working okay. Feel free to leave any corrections or suggestions in the comments, and I'll try to keep this entry updated if I make any fixes or changes.
**Problem:** You want to render an arbitrary number of fields assigned dynamically, as in [snippet #27](http://www.djangosnippets.org/snippets/27/), but using multiple `if` statements in a template would be tedious.
**Solution:** newforms BoundField
The example demonstrates a form with medication fields. We don't know in advance how many meds will be prescribed to a patient, but we want to display a minimum of 4 medication fields, each consisting of a label, name, and dosage.
My code uses a cheap hack of assigning a .bf attribute to the fields during __init__, but it's easy to render in a template loop: `{% for med in form.med_list %}`
*Special thanks to Honza for advice on BoundField.*
`foo = dynamic_import ( 'rawr.i.am.a.lion' )`
Will import `lion` from `rawr.i.am.a` and return it. (This isn't really Django specific)
Props to Crast for the original.
Most of the time when you want a dropdown selector based on
a ForeignKey, you'll want to use [snippet #26](http://www.djangosnippets.org/snippets/26/)
Here's an alternative approach, perhaps useful when you want to define choices once and reuse it in different views without overriding Form `__init__`.
DynamicFieldSnippetForm demonstrates how to dynamically assign fields in newforms.
1. weight is a required static field
2. height is an optional dynamic field
This example uses `request_height` as an optional keyword argument to declare whether the `height` field should be added to the form, but it's just there for demonstration purposes. If you decide to use a keyword argument in your code, be sure to pop it off (as demonstrated in the code) or you'll get an *unexpected keyword argument* error.