Can I override __new__ in Django ModelForm?

15 views
Skip to first unread message

אורי

unread,
Jul 10, 2019, 10:44:17 AM7/10/19
to django...@googlegroups.com
Hi,

I have a ModelForm with Django 1.11, and I'm moving a few fields to another model. Calling make_migrations causes an error because these fields don't exist in the current model. I added some of the fields to the form, but one of the fields is a TranslatedField and therefore there are currently 2 fields, and in the future there might be more, depending on the number of languages. The name of the field is city, and currently I get an error message "Unknown field(s) (city_en, city_he) specified for SiteProfile" (because I'm using 2 languages - "en" and "he") - but I want to create all the fields dynamically with a for loop over the languages we use in the project. Can I override (and is it a good programming method) the __new__ method or is there another way? I prefer not to hard-code the specific field names (city_en and city_he) because they may change in the future, depending on how many languages we use.

You can see my current commit (not working) on GitHub:

And the current code of this branch:

I would like to know what is the best programming method to define a dynamic list of fields (which are all identical, and only one of them will be used, the other are removed in the __init__ method) in a ModelForm where the fields are saved in another model (there are 2 models but only one form).

I still didn't commit the migrations because of this error when running make_migrations.

(I defined a command make_migrations which only does makemigrations)

Thanks!

Jani Tiainen

unread,
Jul 10, 2019, 11:16:15 AM7/10/19
to django...@googlegroups.com
Hi.

You can add fields dynamically on model __init__ method and AFAIK that's best and recommended way to do it.

I'm not sure is that even in Django docs.


--
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 post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CABD5YeFv7HFCmFqvQeg5HdQLBs%3DYbxbRO4oukpdFX175exNSHA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages