Home > Mobile >  How to don't save null parameter in table if got parameter with null field in Django
How to don't save null parameter in table if got parameter with null field in Django

Time:11-17

I have table with some parameters like this:

class Education(models.Model):
    title = models.CharField(default=None, max_length=100)
    content = models.TextField(default=None)

In Django request from client maybe content field equals to NULL. So i want to when content parameter is NULL Django does not save it in database but does not show any errors. Maybe already this field has data and in the Update request client just want to change title field.

CodePudding user response:

In your form / serializer sets the content field as not required, so if the client doesn't want to update that field, it simply doesn't pass a value.

from django.forms import ModelForm
from .models import Education


class EducationForm(ModelForm):
   class Meta:
      model = Education
      fields = ('title', 'content')

   def __init__(self, *args, **kwargs):
      super().__init__(*args, **kwargs)
      self.fields['content'].required = False

CodePudding user response:

I found it, Just like this:

class EducationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Education
        fields = ['title', 'content')
        extra_kwargs = {'content': {'required': False}} 
  • Related