Home > Software engineering >  form is not valid but Django didn`t return any error
form is not valid but Django didn`t return any error

Time:06-29

there is two attribute 'name' and 'slug' as you can see in code I send wrong data to 'slug' and 'name' is empty but validation didn`t work.

Models

class Tag (models.Model):
name = models.CharField(max_length=50,
    db_index=True)
slug = models.SlugField(unique=True,
    help_text='a label for url config')

class Meta:
    ordering = ['name']

def __str__(self):
    return self.name.title()

def get_absolute_url(self):
    return reverse('organizer:tag_detail', kwargs={'slug': self.slug})

forms

class TagForm (forms.Form):
class Meta:
    model = Tag
    fields = '--all--'

def clean_name (self):
    return self.cleaned_data['name'].lower()

def clean_slug (self):
    new_slug = (self.cleaned_data['slug'].lower())
    if new_slug == 'create':
        raise ValidationError('slug may not be "create".')
    else:
        return new_slug

shell

In [11]: from organizer.forms import TagForm

In [12]: tf = TagForm({'slug': 'create'})

In [13]: tf.errors
Out[13]: {}

CodePudding user response:

Your form class should have forms.ModelForm as it's base class to create a form from a model.

To include all model fields in the form you need to use fields = '__all__' not fields = '--all--'

class TagForm (forms.ModelForm):
    class Meta:
        model = Tag
        fields = '__all__'
  • Related