Home > Software engineering >  Python (Django) how to assign a default value in case of error
Python (Django) how to assign a default value in case of error

Time:01-03

Hey I'm using django in a project, using a POST method, the view in Django receives data, it works fine if the data is received but if no data is received I want to assign a default value instead of getting an error here is my code. I tried to use the if assignement but it doesn't work.

@api_view(['POST'])
def getPacsPatients(request):
    data = json.loads(request.body.decode('utf-8'))
    if request.method == 'POST':
        PatientName = data["patientName"] if data["patientName"] else "*"
        #it works fine if data["patientName"] is present, but if not I get an error

CodePudding user response:

You can read values from a dictionary with the get() function.

data.get(key, default_value)

CodePudding user response:

@brukidm gives the correct answer, however as your question implies you might be pretty new to Python, I'd also like to point out that in similar scenarios you can try-except around code, which is aligned with Python's EAFP approach.

This would yield something like this:

@api_view(['POST'])
def getPacsPatients(request):
    data = json.loads(request.body.decode('utf-8'))
    if request.method == 'POST':
        try: 
            PatientName = data["patientName"]
        except KeyError: 
            PatientName = default_value

It executes the code in try block and if it runs across a KeyError executes an except block.

CodePudding user response:

Try This,

try data["patientName"] :
    PatientName = data["patientName"]
except Exception as E:
    PatientName = "*"
  • Related