Y
Y
YuriyCherniy2020-05-19 00:51:46
Python
YuriyCherniy, 2020-05-19 00:51:46

How to get rid of two identical return?

The code below returns the administrator to the page with the form in case of an invalid form and if the administrator tries to archive a product located on the main page. The same is used to handle both situations return, which violates the DRY principle. How to get rid of code duplication in this case?

if form.is_valid():
            if all([hasattr(item, 'itemonmainpage'), form.cleaned_data['is_archived']]):
                messages.warning(
                    request, 'Нельзя поместить в архив товар размещённый на главной странице'
                )
                return render(
                    request, 'showcase/item_update_form.html', {'form': form}
                )
            else:
                return super().post(request, *args, **kwargs)

        return render(
            request, 'showcase/item_update_form.html', {'form': form}
        )

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Shumov, 2020-05-19
@YuriyCherniy

Use the fail first principle and turn the condition to negative. I'm not a pythonist, but this is how it works - first throw out
return super().post(request, *args, **kwargs)
and for all other cases - the necessary logic

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question