Getting "IntegrityError" in Django models when trying to create

Question:

I am working on an app with Django backend and I am currently developing the signup page. Here’s my code:
models.py

from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from datetime import date
from .countries import COUNTRIES
from .hobbies import HOBBIES


class Hobbies(models.Model):
    hobby = models.CharField(max_length=255, choices=HOBBIES)


class Profile(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def username(self):
        usern = User.objects.get(id=self.user.id)
        usern = usern.username
        return usern

    setup = models.BooleanField(default=False)
    gender = models.CharField(max_length=100, blank=True)
    dob = models.DateField(blank=True)

    def age(self):
        today = date.today()
        age = today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
        return age

    orgin = models.CharField(max_length=300, choices=COUNTRIES, blank=True)
    lives = models.CharField(max_length=300, choices=COUNTRIES, blank=True)
    bio = models.CharField(max_length=150, blank=True)
    email = models.CharField(max_length=255, blank=True)
    image = models.ImageField(upload_to='images', blank=True)
    hobbie = models.ManyToManyField('Hobbies', blank=True)
    

views.py-

from django.shortcuts import render
from rest_framework import viewsets, status
from .serializers import UserSerializer, ProfileSerializer
from .models import Profile
from django.db import IntegrityError
from rest_framework.response import Response
from rest_framework.decorators import action
from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication 
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.permissions import IsAuthenticatedOrReadOnly, BasePermission
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
from django.contrib.auth import authenticate
# Create your views here.
#.....

@csrf_exempt
def signup(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        username = data.get("username", "")
        password = data.get("password", "")
        
        try:
            user = User.objects.create_user(username, '',password)
            user.save()
            created = True
            
            profile = Profile.objects.create(user=user)
            profile.save()
            

        except IntegrityError:
            created = False
        return JsonResponse(created, safe=False)

Everything works when I try to create a new user without creating a new profile. But when I try to create a Profile when I am creating the User I get an "IntegrityError.": "NOT NULL constraint failed: home_profile.dob" .How can I fix this?

Asked By: Itay Lador

||

Answers:

Your problem lies here:

dob = models.DateField(blank=True)

DateFields, if empty, are rendered as null in the database, so you need to add

dob = models.DateField(blank=True, null=True)

As a rule of thumb, blank=True says the field need not be filled in for forms. null=True says the database can accept a null value. The exception is for string types, eg CharField and TextField, which only use blank=True as django saves an empty string, "", rather than a null value.

Answered By: SamSparx