[Django]-How to add an extra field to a Django ModelForm?

3👍

My problem was in this line:

extra_field = forms.FileInput()

I solved the problem changing the line to:

extra_field = forms.FileField()

Thanks to all willing to help.

1👍

Try to do it in the constructor.

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(PersonForm, self ).__init__(*args, **kwargs)
        self.fields['extra_field'] = forms.FileInput()

And since you are using the django admin, you need to change the form in the admin too.

👤Todor

1👍

What you’ve done is ok according to the documentation, read note here – https://docs.djangoproject.com/en/2.0/topics/forms/modelforms/#overriding-the-default-fields

To register it in the admin you should add something like this to your admin.py:

from django.contrib import admin
from .forms import PersonForm

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
     form = PersonForm

Example from here – https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#admin-custom-validation

EDIT: it is necessary to actually register custom ModelAdmin, there are two equivalent ways: using decorator, as in the example above, or use admin.site.register(Person, PersonAdmin).

Documentation for ModelAdmin registration – https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#the-register-decorator
Registration source code – https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L85

0👍

Register the model in admin as

admin.site.register(UserProfile)

where UserProfile is a OnetoOnemodel that extends django’s builtin User Model then after every changes in models run

python manage.py makemigrations
python manage.py migrate

Leave a comment