Home > Mobile >  Adding foreign key data through django rest framework serializer
Adding foreign key data through django rest framework serializer

Time:12-12

I am new to django, I have two models User and Todo. User can have multiple todos, while creating the todos I want to pass user_id with request.data, but while including user_id or user field along with request.data I am getting validation error for Todo fields. Here is the User model and Todo model:

class User(AbstractUser):
  email = models.EmailField(unique=True)
  password = models.CharField(max_length=128)
  username = None
  name = models.CharField(max_length=128)
  is_email_verified = models.BooleanField(null=True)
  mobile = models.CharField(max_length=13, validators=[RegexValidator(regex=r'^(\ \d{1,3})?,?\s?\d{8,13}', message="Enter a valid mobile number")], default=' 911234567890')

  USERNAME_FIELD = 'email'
  REQUIRED_FIELDS = ['mobile']
class Todo(models.Model):
  title = models.CharField(null=False, blank=False, max_length=100)
  description = models.TextField(max_length=500)
  user = models.ForeignKey(User, on_delete=models.CASCADE, default=0)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

  def __str__(self):
    return self.title

  class Meta:
    indexes = [
      models.Index(fields=['created_at']),
      models.Index(fields=['updated_at'])
    ]

Here is the Todoserializer:

from rest_framework.serializers import ModelSerializer, CharField
from todos.models import Todo
from users.models import User

class TodoSerializer(ModelSerializer):
  class Meta:
    model = Todo
    fields = '__all__'
    read_only_fields = ['id', 'created_at', 'updated_at']

Here is the view for creating todos:

@api_view(['POST'])
def create(request):
  user = request.user
  todo = TodoSerializer(data={ **request.data, 'user': user.pk })
  todo.is_valid(raise_exception=True)
  todo.save()
  return Response(status=status.HTTP_200_OK, data={'todo': todo})

The serializer doesn't get validated any time enter image description here

CodePudding user response:

In your view try :

@api_view(['POST'])
def create(request):
  request.data['user'] = request.user
  todo = TodoSerializer(data=request.data)
  todo.is_valid(raise_exception=True)
  todo.save()
  return Response(status=status.HTTP_200_OK, data={'todo': todo.data})
  • Related