How to make fields required in django restframework
I build a blog API and the Post model is: the problem is when i want to create a post with no body content the error is
class Post(models.Model):
STATUS_CHOICES = [
('P', _('Published')),
('D', _('Draft')),
('R', _('reject'))
]
title = models.CharField(verbose_name=_("title"), max_length=255)
slug = models.SlugField(null=True, unique=True, allow_unicode=True)
lead = models.CharField(verbose_name=_(
"lead"), max_length=1024, blank=True, null=True)
body = models.TextField(verbose_name=_("context"))
thumbnail = models.ImageField(verbose_name=_(
"thumbnail"), upload_to='posts', blank=True, null=True)
author = models.ForeignKey(UserAccount, verbose_name=_(
"author"), on_delete=models.CASCADE)
status = models.CharField(
_("status"), max_length=1, choices=STATUS_CHOICES, default=STATUS_CHOICES[1][0])
publish_time = models.DateTimeField(
verbose_name=_("published at"), default=timezone.now)
created_at = models.DateTimeField(
verbose_name=_("created at"), auto_now_add=True)
updated_at = models.DateTimeField(
verbose_name=_("updated at"), auto_now=True)
category = models.ManyToManyField(
Category, verbose_name=_("Categorys"), related_name='Categorys')
like_count = models.IntegerField(verbose_name=_("like"), default=0)
dislike_count = models.IntegerField(verbose_name=_("dislike"), default=0)
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
class Meta:
ordering = ['-publish_time']
def __str__(self):
return self.title
class PostListSerializer(ModelSerializer):
dietale_url = HyperlinkedIdentityField(
view_name='api:Post_detail'
)
author = SerializerMethodField()
class Meta:
model = Post
fields = [
'title',
'author',
'lead',
'dietale_url',
]
def get_author(self, obj):
return obj.author.name
the problem is when i want to create a post it return the erorr:
{
"title": [
"This field is required."
]
}
There are more fields required like author body and ...
whay just the title is the required field what happens to other fields
Your title
cannot be blank
or null
in your django model and the serializer you use is the ModelSerializer
, so it will be automatically required.
You need to remove blank = True
and null = True
if you don't want your fields to be required (or override you fields in serializer)
If you're using Model Serializer default value will be False if you have specified blank=True or default or null=True at your field in your Model.