How can I add a field in the form init function? e.g. in the code below I want to add a profile field.
class StaffForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): if user.pk == 1: self.fields['profile'] = forms.CharField(max_length=200) super(StaffForm, self).__init__(*args, **kwargs) class Meta: model = Staff
I know I can add it just below the class StaffForm.... line but I want this to be dynamic depending on what user is passed in so can't do it this way.
Thanks
initial is used to change the value of the field in the input tag when rendering this Field in an unbound Form. initial accepts as input a string which is new value of field. The default initial for a Field is empty. Let's check how to use initial in a field using a project.
Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.
Just need to switch the init function round so that super is called before adding anymore fields.
class StaffForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(StaffForm, self).__init__(*args, **kwargs) if user.pk == 1: self.fields['profile'] = forms.CharField(max_length=200) self.fields['profile'].initial = 'whatever you want' class Meta: model = Staff
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With