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
/ pairs -- excluding the
."
return self._html_output(u'%(label)s\n%(errors)s\n%(field)s%(help_text)s', u'%s', '', 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))