Overriding the admin media class

Given the admin media class that configures a text editor, for example:

class TutorialAdmin(admin.ModelAdmin): fields... class Media: js = ['/paths/to/tinymce.js',] 

I need the ability to selectively redefine js depending on the value of the field in the model that it refers to. I added the "use_editor" logic to the Tutorial model. The question is how to determine if the current instance has this bool set? I would like to get something like:

 class Media: if self.use_editor: js = ['/path/to/tinymce.js',] else: js = '' 

Ideas? Thank you

+4
source share
2 answers

Thanks a lot to Sam Lai from django users, I finally have a working solution for this. It turns out that this is more complicated than expected, because you cannot directly access the field values ​​in the instance from the Admin class - you need to do this by overriding the form used by the Admin class. In addition, you will need to use _ media , not the β€œMedia: class,” to set the media property.

The goal is to determine the current value of the use_visual_editor field instance and enable or disable JavaScript paths depending on its value (therefore, authors can disable the visual editor for each entry). Here's the final working solution:

models.py

 class Tutorial(models.Model): use_visual_editor = models.BooleanField() 

forms.py

 from django import forms from tutorials.models import Tutorial class TutorialAdminForm(forms.ModelForm): class Meta: model = Tutorial def _media(self): if self.instance.use_visual_editor == True: js = ['/paths/to/javascript',] else: js = [''] return forms.Media(js=js) media = property(_media) 

admin.py

 from django import forms .... class TutorialAdmin(admin.ModelAdmin): form = TutorialAdminForm 

Works great!

+3
source

An alternative approach that you use TinyMCE is to use an additional JS file that adds the mceNoEditor class to text fields that you do not want to convert to rich text.

eg,

 class fooAdmin(admin.Modeladmin) class Media: js = ['/path/to/admin-styling.js', '/paths/to/tinymce.js',] 

In your tinymce.js init you need to make sure that a class is specified to disable the editor, for example:

 editor_deselector : "mceNoEditor", 

and in the admin-styling.js file there is some jQuery call in the document handler that finds certain elements and adds this class before calling TinyMCE.

You can usually do this with id_foo. for example, if you have a model field called extra_signs:

 $('textarea#id_additional_notes').addClass('mceNoEditor'); 

It is also possible to use more complex jQuery selectors.

NTN

Steve

+1
source

Source: https://habr.com/ru/post/1304944/


All Articles