- Author:
- fivethreeo
- Posted:
- May 13, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 0 (after 0 ratings)
A way to make form_for_model more customizable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | from emmetcms.pages.models import Page
from django import newforms as forms
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.defaultfilters import slugify
def as_dl(self):
"Returns this form renderd as HTML <dt>/<dd> pairs -- excluding the <dl></dl>."
return self._html_output(u'<dt>%(label)s</dt>\n<dd>%(errors)s</dd>\n<dd>%(field)s%(help_text)s</dd>', u'<dd>%s</dd>', '</dd>', u' %s', False)
def form_for_model(model, form=forms.BaseForm, **kwargs):
realform = forms.form_for_model(model, form=form, **kwargs)
return type(realform.__class__.__name__, (realform,),
{'_instance': model(), 'save': form.save, 'as_dl': as_dl})
def form_for_instance(instance, form=forms.BaseForm, **kwargs):
realform = forms.form_for_instance(instance, form=form, **kwargs)
return type(realform.__class__.__name__, (realform,),
{'_instance': instance, 'save': form.save, 'as_dl': as_dl})
def formfield_callback(f, **kwargs):
if f.name not in ('slug','created_by','last_edited_by'):
return f.formfield(**kwargs)
class PageBaseForm(forms.BaseForm):
def clean_title(self):
self.clean_data['slug'] = slugify(self.clean_data['title'])
return self.clean_data['title']
def save(self, user):
if self._instance._get_pk_val():
mode = 'changed'
else:
mode = 'created'
if mode == 'created':
self._instance.created_by = user
self._instance.last_edited_by = user
return forms.save_instance(self, self._instance, True)
def newpage(request):
NewPageForm = form_for_model(Page, form=PageBaseForm, formfield_callback=formfield_callback)
if request.method == 'POST':
form = NewPageForm(request.POST.copy())
if form.is_valid():
form.save(request.user)
else:
form = NewPageForm()
return render_to_response('pages/newpage.html', {'form': form}, context_instance=RequestContext(request))
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.