1

When i try to add an attribute in an inline field, nothing added. I want a same class for each each select to add a javascript event on select change.

This is my models.py:

class Conversation(models.Model):
    conversation_name = models.CharField(verbose_name="Nom du conversation", 
max_length=255)
    group = models.ForeignKey(Group, verbose_name="Groupe")

class ConversationMessage(models.Model):
    conversation_title = models.ForeignKey(Conversation, 
                         verbose_name="Conversation")
    from_message = models.ForeignKey(MessageList, verbose_name="De", 
                   related_name="from_message")
    to_message = models.ForeignKey(MessageList, verbose_name="A", 
                 related_name="to_message")

my admin.py:

class ConversationMessageInline(admin.TabularInline):
    model = ConversationMessage`

class ConversationMessageAdmin(admin.ModelAdmin):
    form = ConversationMessageForm
    list_display = ['conversation_title', 'from_message', 'to_message']

class ConversationAdmin(admin.ModelAdmin):
    form = ConversationForm
    list_display = ['conversation_name']
    inlines = [
        ConversationMessageInline,
    ]

my forms.py:

class ConversationMessageForm(forms.ModelForm):
    model = ConversationMessage
    from_message = forms.ModelChoiceField(MessageList.objects.all(),
                                   widget=forms.Select(attrs=
                                     {"onChange":'refresh()'}))
    class Media:
        js = ('js/forms_event.js',)

class ConversationForm(forms.ModelForm):
    model = Conversation
    class Media:
        js = ('js/forms_event.js',)

my forms_event.js:

function refresh() {
    alert("salut la planete");
}

The event onchange didn't added when I'm at "Add Conversation":

enter image description here

1
  • "onChange" or "onchange" ? Commented Oct 25, 2017 at 15:14

2 Answers 2

1

You Just need to override the default form of the Inline class and add you new form to the TabularInline Class, as the following:

class ConversationMessageInline(admin.TabularInline):
    model = ConversationMessage
    form = ConversationMessageForm
Sign up to request clarification or add additional context in comments.

Comments

0

I would say it's a bad practice to mix python and javascript, so don't embed scripts in your forms.

Instead, you could just do something like this in your .js file:

var from_message_field = document.getElementById('<id of the field>');
from_message_field.addEventListener('change', refresh);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.