Michael
Michael

Reputation: 1058

How to add an extra field to a Django ModelForm?

So I'm working on an admin page. I'm registering the form with admin.site.register. And I want to add an extra field to the form, which will let me populate a TextField with a file contents.

Therefore I need to add an extra FileInput to upload the file and populate the TextField with its contents. I am trying this:

class PersonForm(forms.ModelForm):

    extra_field = forms.FileInput()

    class Meta:
        model = Person
        fields = '__all__'

but the field is not showing. Any ideas? Also I have no clue where to access the file contents and populate the TextField with that before saving the model.

Thanks in advance.

Upvotes: 3

Views: 8225

Answers (4)

Michael
Michael

Reputation: 1058

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.

Upvotes: 3

Roman Yakubovich
Roman Yakubovich

Reputation: 903

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

Upvotes: 1

Ajay Banstola
Ajay Banstola

Reputation: 93

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

Upvotes: 0

Todor
Todor

Reputation: 16060

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.

Upvotes: 1

Related Questions