pythondjangodjango-modelsdjango-forms

Django - add widget option in form.py Meta class?


models.py

from django.db import models

class user(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100, unique=True)

forms.py

from django import forms
from second_app.models import user

class NewUserForm(forms.ModelForm):

    class Meta:
        model = user
        fields = '__all__'

In a normal forms.py that doesn't inherit from the models, you can use field = forms.CharField(widget=forms.HiddenInput) to specify how the input field will be displayed to the users. How can this be done, when my forms.py is inheriting the class defined in models.py?


Solution

  • You can use for this meta's widgets option:

    from django import forms
    from second_app.models import user
    
    class NewUserForm(forms.ModelForm):
    
        class Meta:
            model = user
            fields = '__all__'
            widgets = {
                'field_name': forms.HiddenInput(),
            }