Django, rest api post ForeignKey


I am writing REST API in Django, I create model Member where is ForeignKey from User table (auth_user)… method GET work perfectly but with post I have problem… every time I saw error message that fk_id cannot be null.

class Member(models.Model):
valid_from = models.DateTimeField(null=True, blank=True)
valid_to = models.DateTimeField(null=True, blank=True)
online = models.IntegerField()
vpn_ip = models.CharField(max_length=20, unique=True)
created = models.DateTimeField(auto_now_add=True)
fk = models.ForeignKey(User, on_delete=models.CASCADE)

def username(self):

def password(self):

def email(self):

def status(self):

def admin(self):

def fk_id(self):

def __str__(self):
    return self.username

class MemberData(APIView):
serializer_class = MemberDataSerializer
permission_classes = [IsAuthenticated]

def get(self, request, format=None):
    Retrieves all Member from database
    data = Member.objects.all()
    serializer = MemberDataSerializer(data, many=True)
    return Response(

def post(self, request, *args, **kwargs):
    Put new member to database

    data = {

    serializer = MemberDataSerializer(data=data)
    if serializer.is_valid():
        return Response(, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class MemberDataSerializer(serializers.ModelSerializer):
class Meta:
    model = Member
    fields = ["id", "fk_id", "username", "password", "email", "status", "admin", "valid_from", "valid_to", "online", "vpn_ip", "created"]

and If I try post data as application/json then I saw this error…

data sending in postman like this..

    "fk_id": 1,
    "valid_from": null,
    "valid_to": null,
    "online": 0,
    "vpn_ip": ""

Exception Type: IntegrityError

Exception Value: (1048, "Column ‘fk_id’ cannot be null")

Asked By: Stepan Kutaj



Solved by myself. It’s easy….

Answered By: Stepan Kutaj
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.