0

Currently I have this form where the inputs are normal textfield (Basic look) and it works. But once i add in form control, it stop working.

In my HTML (One part of the text field): Workable

 <div class="col-md-5">
  <div class="form-group">
   <label for="{{form.hostname.id_for_label}}">Hostname</label>
    {{form.hostname}}
  </div>
 </div>

But if i change it to the following codes: Not workable

<div class="col-md-5">
 <div class="form-group">
  <label for="{{form.hostname.id_for_label}}">Hostname</label>
  <input class="form-control" type="text" id="{{form.hostname.id_for_label}}" name="{{form.hostname}}" 
   placeholder="" required>
 </div>
</div>

Am i doing something wrong? Appreciate if anyone could help

Calvin Lin
  • 59
  • 1
  • 1
  • 7

2 Answers2

1

You are not using braces and you are not specifying the name attribute of the field for the name. Something like this:

<input class="form-control" type="text" 
       id="{{ form.hostname.id_for_label }}" 
       name="{{ form.hostname.name }}" 
       {% if value %} value="{{ form.hostname.value }}"{% endif %} 
       placeholder="" 
       {% if form.hostname.field.required %}required{% endif %}>

Instead of manually rendering like this you may want to look into django crispy forms or django floppyforms.

jmcarson
  • 436
  • 2
  • 4
  • It doesnt not work even if i include braces – Calvin Lin Aug 04 '21 at 02:51
  • 1
    Did you change name="form.hostname" to name="{{ form.hostname.name }}" note the extra .name. – jmcarson Aug 04 '21 at 02:52
  • Oh! Got it. But i got questions. What is the value for? Because now i have the word 'None' in my forms when i refresh for a new page. And whats the purpose of the if behind? – Calvin Lin Aug 04 '21 at 03:12
  • Sorry, updated my answer to check for value's existence before setting the value. You didn't share your view but typically the form is submitted, you check whether if it is valid and if it is not you make them edit the form. Setting the value like that populates the fields with the previously entered data when it is re-rendered. The if at the end is setting the 'required' attribute only if the form field is defined as required in your django form model rather than hardcoding it in your html. Really you want to use one of the form rendering libraries that do all this work for you. – jmcarson Aug 04 '21 at 03:51
  • Oh, if im using django to check if the form is vaild then the checking in html is redundant right? – Calvin Lin Aug 04 '21 at 09:38
0

If you need to add custom class names, then you can overide your form like this

def __init__(self, *args, **kwargs):
        super(form_name, self).__init__(*args, **kwargs)
        
        self.fields['hostname'].widget.attrs.update({'class': 'form-control'})

Add these to your forms.py under the form which your using, this will add the custom class to the respective field

Arvindh
  • 600
  • 1
  • 10
  • 25