﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
6866	Easy custom media and validation in newforms-admin	mrts	nobody	"Attaching media (especially !JavaScript) and custom validation is a common use case for admin section. It should be easy.

As of [7278], `get_form()` can be used to provide a custom form that can bring in JavaScript and custom validation. Due to bugs, once this method is overriden, your form will not automatically get the custom admin widgets. As the automatic widgets are the main point of using admin, this is not generally acceptable.

The proposed behaviour (that is implemented in the attached patch -- thanks, Brosner, for the bug fix!) is as follows:

{{{
# A Foo with unique language
class Foo(models.Model):
    foo = models.TextField()
    language = models.CharField(max_length=3, choices=LANG_CHOICES, unique=True)
    def __unicode__(self):
        return 'Foo in %s' % self.get_language_display()

# common base class for attaching TinyMCE to several validator forms
class TinyMCEForm(forms.ModelForm):
    media = forms.Media(
        js = ['/site_media/js/tiny_mce/tiny_mce.js',
                '/site_media/js/add_editor.js'])

# a common validator form for all models with a 'language' field
class LanguageValidatorForm(TinyMCEForm):
    def clean_language(self):
        if 'language' not in self.cleaned_data:
            return
        lang = self.cleaned_data['language']
        model = self._meta.model
        if model.objects.filter(language = lang).exclude(pk=self.instance.pk):
            raise forms.ValidationError('%(obj_title)s already exists for '
                    'language %(lang)s. Only one %(obj)s is allowed for '
                    'each language.'
                    % { 'obj_title' : model._meta.verbose_name.title(),
                        'obj' : model._meta.verbose_name,
                        'lang' : admin_forms.get_lang_display(lang)})

class LanguageAdmin(admin.ModelAdmin):
    admin_form = LanguageValidatorForm
    save_on_top = True

admin.site.register(Foo, LanguageAdmin)
}}}

I.e. there is a class variable that specifies the form that brings in both validation and media."		closed	contrib.admin	newforms-admin		fixed			Unreviewed	1	0	0	0	0	0
