Python (Django) how to assign a default value in case of error
Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Python (Django) how to assign a default value in case of error on this date .
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
Answer
You can read values from a dictionary with the get()
function.
data.get(key, default_value)