form_for_model / instance customized save and model aware validation

 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

  1. Add HTML Attributes in Model by guettli 5 years, 11 months ago
  2. Add validation for 'unique' and 'unique_together' constraints to newforms created dynamically via form_for_model or form_for_instance by bikeshedder 6 years, 10 months ago
  3. Selectively change fields, widgets or labels in forms created from models by danjak 7 years, 1 month ago
  4. Modify fields created by form_for_model by grahamu 7 years, 1 month ago
  5. Dynamic Form Class by dballanc 7 years ago

Comments

(Forgotten your password?)