Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django form creation on init

Tags:

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

like image 555
John Avatar asked Apr 08 '10 12:04

John


People also ask

What is initial in Django forms?

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.

What is ModelForm in Django?

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.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How can we make field required in Django?

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.


1 Answers

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 
like image 54
John Avatar answered Sep 25 '22 07:09

John