1
\$\begingroup\$

I built a small project using Django-Rest-Framework. Please comment on the best practice style for the code below, which will make it simpler.

class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if phone and password:
            user = authenticate(phone=phone, password=password)
            if user:
                if user.is_active:
                    data['user'] = user
                else:
                    raise exceptions.ValidationError('User is deactivated.')
            else:
                raise exceptions.ValidationError(
                    'Unable to login with given credentials.')
        else:
            raise exceptions.ValidationError(
                'Must provide username and password both.')
        return data

How I can make this more Pythonic?

\$\endgroup\$

closed as off-topic by πάντα ῥεῖ, yuri, pacmaninbw, esote, dfhwze Jun 18 at 7:50

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – πάντα ῥεῖ, yuri, pacmaninbw, esote, dfhwze
If this question can be reworded to fit the rules in the help center, please edit the question.

1
\$\begingroup\$
  • Returning early makes code not follow the arrow anti-pattern. And makes the flow of the code simpler.
  • There's otherwise not much to comment on.
class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if not (phone and password):
            raise exceptions.ValidationError('Must provide username and password both.')

        user = authenticate(phone=phone, password=password)
        if not user:
            raise exceptions.ValidationError('Unable to login with given credentials.')

        if not user.is_active:
            raise exceptions.ValidationError('User is deactivated.')

        data['user'] = user
        return data
\$\endgroup\$
  • \$\begingroup\$ Thank you so much! \$\endgroup\$ – PrefixEt Jun 16 at 17:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.