Django 1.6
I have a working block of code in a Django form class as shown below. The data set from which I'm building the form field list can include an initial value for any of the fields, and I'm having no success in setting that initial value in the form. The if field_value:
block below does indeed populate the initial form dictionary attribute, but the initial value is not being displayed. Note that (in case you are wondering) the .initial
attribute does not exist until after the super()
call.
Can this be done?
If so, what I'm not doing right to make this work?
Thanks!
def __init__(self, *args, **kwargs): id = kwargs.pop('values_id', 0) super(LaunchForm, self).__init__(*args, **kwargs) # Lotsa code here that uses the id value # to execute a query and build the form # fields and their attributes from the # result set if field_value: self.initial[field_name] = field_value
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.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.
CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.
I had that exact same problem and I solved it doing this:
def __init__(self, *args, **kwargs): instance = kwargs.get('instance', None) kwargs.update(initial={ # 'field': 'value' 'km_partida': '1020' }) super(ViagemForm, self).__init__(*args, **kwargs) # all other stuff
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