Changes between Version 13 and Version 14 of NewformsHOWTO


Ignore:
Timestamp:
02/18/08 19:36:59 (7 years ago)
Author:
jarrow
Comment:

Added a method for custom field validation in admin and ModelForm instances. Plus some formatting.

Legend:

Unmodified
Added
Removed
Modified
  • NewformsHOWTO

    v13 v14  
    427427== Q: What happened to filter_interface? ==
    428428
    429 A: Use ```filter_vertical``` and ```filter_horizontal``` on the !ModelAdmin class like so.
    430 E.g.
     429A: Use ```filter_vertical``` and ```filter_horizontal``` on the !ModelAdmin class like so:
     430
    431431{{{
    432432#!python
     
    437437== Q: How do I add custom !JavaScript/CSS? ==
    438438
    439 Override `form_add()` and `form_change()` in ModelAdmin.
     439Override `form_add()` and `form_change()` in ```ModelAdmin```.
    440440
    441441E.g. to add TinyMCE:
    442442{{{
     443#!python
    443444class MyModelAdmin(admin.ModelAdmin):
    444445    save_on_top = True
     
    460461== Q: How do I add custom validation? ==
    461462
    462 Again, override `form_add()` and `form_change()` in ModelAdmin and provide a custom form that does the validation.
     463One option is to again override ```form_add()``` and ```form_change()``` in ```ModelAdmin``` and provide a custom form that does the validation.
     464
     465If 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].
     466
     467Here we add regex validation to a field (see #6556 for the workaround):
     468
     469{{{
     470#!python
     471class UraniaEventID(models.CharField):
     472    def formfield(self, **kwargs):
     473        defaults = {'regex':r"^[A-Za-z][1-9][1-7][0-9]$"}
     474        defaults.update(kwargs)
     475        return super(models.CharField, self).formfield(form_class=forms.RegexField, **defaults)
     476       
     477    # WORKAROUND to have this field generated by django in the database (see #6556)
     478    def get_internal_type(self):
     479        return "CharField"
     480
     481class Event(models.Model):
     482    urania_event_id = UraniaEventID(max_length=4)
     483}}}
Back to Top