NOT NULL constraint failed on PUT request in Django

  Kiến thức lập trình

I’m new to Django and I’m having trouble handling form-data and raw data in PUT requests. I need to update records of a Person model via a PUT request. The Person model has several fields including fname, sname, age, and gender, all of which are required.

I have a view to handle the PUT request, and I’m trying to handle both JSON and form-data formats in the request body.

However, when I send a PUT request via Postman, I encounter the following error:
Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: api_person.fname

To handle different request formats, I first attempt to parse the request body as JSON. If JSON parsing fails, I fall back to handling form-data. Here’s the relevant part of my view:

`try:
# Attempt to parse request body as JSON
data = json.loads(request.body)
fname = data.get(‘fname’)
sname = data.get(‘sname’)
age = data.get(‘age’)
gender = data.get(‘gender’)
except json.JSONDecodeError:
# Handle form-data if JSON parsing fails
fname = request.POST.get(‘fname’)
sname = request.POST.get(‘sname’)
age = request.POST.get(‘age’)
gender = request.POST.get(‘gender’)

    # Update person object with received data
    person.fname = fname
    person.sname = sname
    person.age = age
    person.gender = gender
    person.save()`

I expected this approach to handle both request formats seamlessly and update the Person record correctly. However, I encountered a NOT NULL constraint failed: api_person.fname error, which indicates that the fname field is missing or empty.

Despite adding print statements and validation checks, I couldn’t figure out why fname is still missing. Any insights or suggestions to resolve this issue would be greatly appreciated!

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT