Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom form fields for model fields in the Django admin?

I want to have the Django admin use a custom form field for the input of some fields.

Until now I made a custom model field that has the form field bound to it which works great but it introduces an unecessary model field that does not add any benefit.

I guess it can be done somehow using a custom admin form (see http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin) but I couldn't figure out how to do it.

like image 232
Semmel Avatar asked Jul 05 '11 15:07

Semmel


People also ask

How do I link models and forms in Django?

models import User class InputUserInfo(forms. Form): phone = forms. CharField(max_length=20) instagram = forms. CharField(max_length=20) facebook = forms.

How do I add a model field in Django?

To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.

Can I add fields to Django user model?

The user detail view will have username, password, first name, last name, email address, active, staff status, superuser status, groups, user permissions, last login, and date joined. To add your new fields to the detail view, you'll need to use fieldsets.


1 Answers

class MyModelForm(forms.ModelForm):
    my_field = MyCustomFormField()

    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
like image 89
Chris Pratt Avatar answered Oct 26 '22 07:10

Chris Pratt