Code

Changes between Version 28 and Version 29 of NewformsHOWTO


Ignore:
Timestamp:
04/03/08 07:37:49 (6 years ago)
Author:
james@…
Comment:

Updated docs on adding custom js or css

Legend:

Unmodified
Added
Removed
Modified
  • NewformsHOWTO

    v28 v29  
    437437== Q: How do I add custom !JavaScript/CSS? == 
    438438 
    439 Override `form_add()` and `form_change()` in ```ModelAdmin```. 
    440  
    441 E.g. to add TinyMCE: 
    442 {{{ 
    443 #!python 
    444 class MyModelAdmin(admin.ModelAdmin): 
    445     save_on_top = True 
    446     inlines = (MyOtherModelInline,) 
    447     def form_add(self, req): 
    448         class _AddForm(forms.BaseForm): 
    449             media = forms.Media( 
    450                 js = ['/site_media/js/tiny_mce/tiny_mce.js', 
    451                         '/site_media/js/add_editor.js']) 
    452         if self.declared_fieldsets: 
    453             fields = flatten_fieldsets(self.declared_fieldsets) 
    454         else: 
    455             fields = None 
    456         return forms.form_for_model(self.model, form=_AddForm, fields=fields, formfield_callback=self.formfield_for_dbfield) 
    457 }}} 
    458  
    459 Note that this behaviour will change, a much more user-friendly way to control this will be added soon. 
     439Since changeset [7365] you can pass a media definition to the ModelForm, eg: 
     440 
     441{{{ 
     442#!python 
     443class PageFormWithMedia(forms.ModelForm):  
     444    class Media:  
     445        js = ('/some/form/javascript',)  
     446        css = {  
     447        'all': ('/some/form/css',)  
     448        }  
     449    class Meta:  
     450        model = Page 
     451 
     452class PageOptions(admin.ModelAdmin): 
     453    form = PageFormWithMedia 
     454   
     455admin.site.register(Page, PageOptions) 
     456}}} 
    460457 
    461458== Q: How do I add custom validation? == 
    462459 
    463 One option is to again override ```form_add()``` and ```form_change()``` in ```ModelAdmin``` and provide a custom form that does the validation. 
     460One option is to override ```form_add()``` and ```form_change()``` in ```ModelAdmin``` and provide a custom form that does the validation. 
    464461 
    465462If you want custom validation for a field in the admin '''and''' newforms [http://www.djangoproject.com/documentation/modelforms/ ModelForm] instances you can subclass a field in your model and override ```formfield()```. You can then return the form field you like or a complete [http://www.djangoproject.com/documentation/newforms/#creating-custom-fields custom form field].