# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from django.contrib.auth import get_user_model from django.db.models import Q from django import forms User = get_user_model() class LoanTransferForm(forms.Form): target_user = forms.CharField( max_length=100, label='Adhérent', help_text='email, pseudonyme ou numéro de l\'adhérent', ) def clean_target_user(self): value = self.cleaned_data['target_user'] result = User.objects.filter( Q(email__iexact=value) | Q(pk__iexact=value) | Q(nickname__iexact=value) | Q(username__iexact=value) ) if result.count() > 1: raise ValidationError( "La recherche retourne plus d'un adhérent") elif result.count() < 1: raise ValidationError( "Aucun adhérent ne correspond à cette recherche") return result.first()