Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django forms how to initialze only not required field instead of passing all required fields

class Student(models.Model):
    name = models.CharField(null=True, blank=True)
    fieldA = models.TextField(null=True, blank=True)
    fieldB = models.TextField(null=True, blank=True)
    fieldC = models.TextField(null=True, blank=True)
    fieldD = models.TextField(null=True, blank=True)

class Meta:
   model = Student
   fields = '__all__'

Based on the above example all fields are taken in UpdateView or CreateView.
If i need to take only required field i can change Meta to

class Meta:
   model = Student
   fields = ['name','fieldA',fieldB','fieldC']

So my question is how can add only fields that should not pass in the Meta.From above example ‘fieldD’ is not passed. Is there is any way to say ‘fieldD’ is not required instead on passing all required fields in Meta.So that the code can be reduced.

Above one is a small example. Consider I have 200 fields and only 1 field that I didnot want to pass so instead of passing 199 required fields in Meta is there is anyway to tell only the 1 field should not pass

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use Meta.exclude instead of Meta.fields to define only the fields that should not be present on the form

class StudentForm(forms.ModelForm):
    class Meta:
        model = Student
        exclude = ['fieldD']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading