I have a django model like below
models.py
class Product(models.Model): name = models.CharField(max_length = 300) description = models.TextField(max_length = 2000) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) def __unicode__(self): return self.name
forms.py
class ProductForm(ModelForm): class Meta: model = Product exclude = ('updated', 'created')
product_form.py(just an example)
<form enctype="multipart/form-data" action="{% url 'add_a_product' %}" method="post"> <div id="name"> {{form.name}} </div> <div id="description"> {{form.description}} </div> </form>
Actually I want to display/render the html output like below
<input id="common_id_for_inputfields" type="text" placeholder="Name" class="input-calss_name" name="Name"> <input id="common_id_for_inputfields" type="text" placeholder="Description" class="input-calss_name" name="description">
So finally how to add attributes(id, placeholder, class)to the model form fields in the above code ?
To do this in Django currently, you have to do something like: comment = forms. CharField(max_length=200, widget=forms. TextInput({ "placeholder": "Text!"}))
In order to add a class or id attribute to a form in Django, we have to place a widget=form. TextInput (or widget= form. EmailInput, if email input) within the form field (because it's a text field). Inside of this widget, we then have to put, attrs={'class':'some_class'}.
In this article, we show how to add a placeholder to a Django form field. A placeholder is text that goes into a form field that can be used to tell the user information. This text disappears when a user clicks in the field and begins typing.
form. cleaned_data returns a dictionary of validated form input fields and their values, where string primary keys are returned as objects. form. data returns a dictionary of un-validated form input fields and their values in string format (i.e. not objects).
You can do the following:
#forms.py class ProductForm(ModelForm): class Meta: model = Product exclude = ('updated', 'created') def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['description'].widget = TextInput(attrs={ 'id': 'myCustomId', 'class': 'myCustomClass', 'name': 'myCustomName', 'placeholder': 'myCustomPlaceholder'})
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