I have written a django FormView to handle a formset, and I've recently been introduced to 'try except' syntax. I have the feeling that my code would be DRYer if I used a 'try except' block, but I'm having writers block. How would you re-format this block as a 'try except'?
def post(self, request, *args, **kwargs):
formset_post = self.formset(request.POST)
if 'url_fk_id' not in kwargs:
kwargs['url_fk_id'] = self.kwargs.get(self.url_fk_id)
form_fk_id = get_object_or_404(models.Fk, id=kwargs['url_fk_id'])
for form in formset_post:
form.instance.fk_id = form_fk_id
list_of_primary_entries = []
if form.instance.entry_is_primary is True:
if True not in Entry.objects.filter(fk_id=form_fk_id).values()
pass
else:
raise forms.ValidationError("there can only be one primary entry")
list_of_primary_entries.append('4')
if len(list_of_primary_entries) > 1:
raise forms.ValidationError("there can only be one primary entry")
if formset_post.is_valid():
for form in formset_post:
form.save()
else:
return self.form_invalid(formset_post)
print(self.request.POST)
return super().post(self, request, *args, **kwargs)
I don't think your code here gains anything from try/except blocks. Try/except blocks are a good shorthand for skipping some checks and just seeing what happens. For example:
inum = input('Enter a number:')
if inum.isdigit(): # check if inputted string looks valid BEFORE trying to convert
num = int(inum)
else:
num = -1
print('Oops!')
as compared to:
inum = input('Enter a number')
try: # just try to convert it and see what happens!
num = int(inum)
except:
num = -1
print('Oops!)
Also, try/except blocks are meant to catch thrown exceptions to allow your code to keep running even if an error occurs, to be more robust. You may want to throw questionable calls that can fail inside a try/except block. For example, you might want:
form_fk_id = get_object_or_404(models.Fk, id=kwargs['url_fk_id'])
to be:
try:
form_fk_id = get_object_or_404(models.Fk, id=kwargs['url_fk_id'])
except:
form_fk_id = None
print('Object not available right now')
and then handle the case where the call to get_object_or_404() fails. This can be helpful if you're making an Internet call or accessing some external resource that is not currently available. It's better for your code to catch it and handle it rather than failing. For example, if you're trying to access an external resource, if the call fails, you may want to try again after a certain amount of time, etc...
The above is just my two cents. Opinions vary... But I do find that good error checking is always good. It makes your code more robust and more readable.