reza_khalafi
reza_khalafi

Reputation: 6554

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

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.

Upvotes: 0

Views: 198

Answers (2)

reza_khalafi
reza_khalafi

Reputation: 6554

I found it, Just like this:

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

Upvotes: 0

Alain Bianchini
Alain Bianchini

Reputation: 4191

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

Upvotes: 1

Related Questions