understanding try except python/django

I need your help with understanding try-except python/Django.

so I have this function:

def submit_dept_head_application(request, application_id):
cv = request.FILES['cv']
letter = request.FILES['letter']
candidate_id = request.data['candidateId']
rank_id = request.data['requestedRankId']
application_state = {
    'candidate_id': candidate_id,
    'rank_id': rank_id,
    'cv_filename': cv.name,
    'letter_filename': letter.name,
}

creator = Profile.objects.get(user=request.user.id)
department = creator.department
applicant = Profile.objects.get(user=candidate_id)
applicant_profile_id = applicant.id
rank = Rank.objects.get(id=rank_id)

try:
    application = Application.objects.get(id=application_id)
    # TODO - update application
except Application.DoesNotExist:
    application = None

if application is None:
    application = Application(creator=creator, applicant=applicant, desired_rank=rank,
                              application_state=application_state, department=department
                              )
    application.save()
    create_application_directory(application.id)

ApplicationStep.objects.update_or_create(
    application=application, step_name=Step.STEP_1,
    defaults={'can_update': True, 'can_cancel': True, 'currentStep': True}
)

copy_to_application_directory(cv, application.id)
copy_to_application_directory(letter, application.id)

send_email(settings.SENDGRID_SENDER, ['xxxxxx@gmail.com'], 'new application submitted',
           'new application submitted')

return Response(application.id, status=status.HTTP_200_OK)

right now what is happening is that if there is no open application I create a new one.
what I’m trying to do is to add another check, which is Application.objects.filter(applicant=applicant_profile_id) so if I have an opened application for this candidate it won’t get to the application.save() but it will send an error.
i don’t really know how to do so and that’s where i need your help please 🙂

>Solution :

Check first. This is what queryset.exists() is for.

if Application.objects.filter(applicant=applicant_profile_id).exists() :
    # tell applicant he's being naughty

#carry on as in the code you posted

Leave a Reply