Home > Enterprise >  Django forms: not adding attributes
Django forms: not adding attributes

Time:08-08

I'm aware that there is many post like this, but can you spot the typo or error in my code?

I'm adding custom classes to my forms but when I inspect the element on the web page there are none. The same goes for placeholder.

Code:

Views.py:

def render_main(request):
    form = AuthorForm()
    context = {
        'form' : form 
    }
    return render(request,'nglib/search.html', context)

Template file:

 {% csrf_token %}
 <div >
   {{form.name}}
 </div>
 <div >
  {{form.surname}}
</div>

Forms.py:

from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import SearchStats
from django import forms
import re


def isStandardized(value):
    if not re.compile(r'^[a-zA-Z ] $').match(value):
        raise ValidationError('Enter only english characters')
    return True
        
class AuthorForm(ModelForm):

    name = forms.CharField(validators=[isStandardized])
    surname = forms.CharField(validators=[isStandardized])

    class Meta:
      model   = SearchStats
      fields  = ['name', 'surname', 'author_id', 'amount']

      widgets = {
          'name': forms.TextInput(attrs={'class':'form-control',  'placeholder':'Name of an author'}),
          'surname': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Surname of an author'}),
          'author_id': forms.TextInput(attrs={'type':'hidden'}),
          'amount': forms.TextInput(attrs={'type':'hidden'})
      }

CodePudding user response:

I think, you already specified the fields name and surname in the class itself, so you should use inline widgets not Meta widgets, as they are used for overriding default widgets, so:


class AuthorForm(ModelForm):

    name = forms.CharField(validators=[isStandardized],widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Name of an author'}))
    surname = forms.CharField(validators=[isStandardized],widget=forms.TextInput(attrs={'class':'form-control','placeholder':'surname of an author' }))

    class Meta:
      model   = SearchStats
      fields  = ['name', 'surname', 'author_id', 'amount']

      widgets = {
          'author_id': forms.TextInput(attrs={'type':'hidden'}),
          'amount': forms.TextInput(attrs={'type':'hidden'})
      }
  • Related