Reputation: 1623
I am new to Django, Let say I have a view like follow with form
class DepartmentCreateView(LoginRequiredMixin,CreateView):
form_class = DepartmentForm
template_name = os.path.join(TEMPLATE_FOLDER, "create/index.html")
def get_success_url(self):
position_id = self.kwargs.get('position_id')
return reverse_lazy('departments_list', kwargs = { 'college_id' :
college_id })
def get_initial(self):
initial = super(DepartmentCreateView, self).get_initial()
initial.update({ 'college' : self.kwargs.get('college_id'),
'code' : 1 })
return initial
my form looks like
class DepartmentForm(forms.ModelForm):
class Meta:
model = Department
fields = ('name', 'college', 'code')
when I display form I am setting some default values to some fields(college) using get_initial()
, it works as expected, but when I submit the form if the form is invalid(for example code is required but value is null) it shows error message as expected in the code field, but form fails to set default value to college again.
what mistake i made here?
Upvotes: 2
Views: 5842
Reputation: 311
Django have a method get_initial_for_field
for form, and in your case correct write that:
def get_initial_for_field(self, field, field_name):
"""
field_name: string = name of field in your model (college, code, name)
field = class of this field
return: value to initial, string, int or other (example: datetime.date.today())
"""
if field_name == 'college':
return self.kwargs.get('college_id')
elif field_name == 'code':
return '1'
Upvotes: 0
Reputation: 568
you can override the get_form
to set the value of the input to your initial value
def get_form(self, form_class=None):
form = super(CreatePost, self).get_form(form_class)
form.fields['your_input'].widget.attrs.update({'value': 'new_value'})
return form
Upvotes: 2
Reputation: 731
You can use the initial= your_value
for each field as found in Django Docs.
This should be in your forms.
OR
You can populate it key value pair like initial= {'your_key', your_value}
when you init your form.
Upvotes: 2