Mixin add field to fields in forms

57 views
Skip to first unread message

sebasti...@gmail.com

unread,
Apr 18, 2021, 8:47:33 AM4/18/21
to Django users
Hello,


forms.py:

class Newsletterform(StandardMixin):
    class Meta:
        model = Newsletter
        fields = ['newslettername', 'from_link', 'to_list', 'email_subject', 'text_message', 'html_message' ]

Mixins.py:
class StandardMixin(forms.ModelForm):
    class Meta:
        abstract = True

    def __init__(self, *args, **kwargs):

        self.Meta.fields.append('owner')
        super(StandardMixin, self).__init__(*args, **kwargs)


i would append in Meta.Fields owner and after this super. But in Template this field are not shown. 

Why?

Shaheed Haque

unread,
Apr 18, 2021, 9:14:03 AM4/18/21
to django...@googlegroups.com
Try updating self.declared_fields instead. 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bb10dfa0-ed1e-459c-8e06-46af264a3b7en%40googlegroups.com.

sebasti...@gmail.com

unread,
Apr 18, 2021, 9:38:31 AM4/18/21
to Django users
Hello,

Thanks for your fast response. But i don't know how i can use  self.declared_fields and why this would help me...

Regards

Shaheed Haque

unread,
Apr 18, 2021, 12:17:35 PM4/18/21
to django...@googlegroups.com
On Sun, 18 Apr 2021 at 14:38, sebasti...@gmail.com <sebasti...@gmail.com> wrote:
Hello,

Thanks for your fast response. But i don't know how i can use  self.declared_fields and why this would help me...

The "how" is easy. Here is a fragment from my code where the problem is that every instance of FilesForm has content dependent on external factors (the "..." below):

  class FilesForm(forms.Form):
      def __init__(self, *args, **kwargs):
           self.declared_fields = OrderedDict()
           for name, field in ....items():
               self.declared_fields[name] = field
           super().__init__(*args, **kwargs)

The "why" is a deeper question, but in short, that's what the source code says the DeclarativeFieldsMetaClass for forms uses. Technically, I believe the code is a little ick because self.declared_fileds is a class member, not an instance member and so needs the funny-looking assignment so the instance has a value it can hack. You may need to copy the original dict as in "self.declared_fields = OrderedDict(self.declared_fields)" depending on your use case.

(Generally, the Django docs are amazing, but this is one area where I needed the source.)

Shaheed

 

Shaheed Haque

unread,
Apr 18, 2021, 12:34:48 PM4/18/21
to django...@googlegroups.com
Actually, looking again at the source, it might be generally belter to use self.base_fields. (Yes, my previous answer is not an exact copy of my code, so I got it wrong).
Reply all
Reply to author
Forward
0 new messages