2014-05-13 11 views
9

Desidero personalizzare la risposta JSON quando si aggiunge un nuovo elemento al database, restituisce quanto segue.Come configurare Django Rest Framework per restituire errori con testo personalizzato

HTTP 400 BAD REQUEST 
Content-Type: application/json Vary: 
Accept Allow: POST, OPTIONS 

{ 
"nick": [ 
    "Users with this Nick already exists." 
    ] 
} 

e

{ 
"nick": [ 
    "Your username is empty" 
    ] 
} 

voglio per tornare (Questo nome utente esiste già, si prega di utilizzare uno diverso.)

o

"Username %s already exists", (self.nick) 

ho usato il seguente esempio ma non funziona se il valore è vuoto o non valido.

def validate_title(self, attrs, source): 
    """ 
    Check that the blog post is about Django. 
    """ 
    value = attrs[source] 
    if "django" not in value.lower(): 
     raise serializers.ValidationError("Blog post is not about Django") 
    return attrs 

questo è il JSON che viene inviato all'API.

{ 
    "name": "myname", 
    "nick":"", 
    "type_account":"1", 
    "email":"[email protected]", 
    "pass_field":"12345" 
} 

serializers.py

class userSerializer(serializers.ModelSerializer): 

    class Meta: 
     model = users 
     fields = ('nick', 'email', 'pass_field', 'type_account') 

    def validate_nick(self, attrs, source): 

     value = attrs[source] 
     if not value: 
      raise serializers.ValidationError('Username cannot be empty') 
     elif self.Meta.model.objects.filter(nick=value).exists(): 
      raise serializers.ValidationError("Username "+value+" is in use") 
     return attrs 

views.py

@api_view(['POST']) 
def user_add(request): 
    """ 
    Saves a new user on the database 
    """ 

    if request.method == 'POST': 

     serializer = userSerializer(data=request.DATA) 
     if serializer.is_valid(): 
      serializer.save() 
      return Response(serializer.data, status=status.HTTP_201_CREATED) 
     else: 
      return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
+0

potete inserire il vostro modello in cui 'nick' è un campo? – Fiver

risposta

0

credo che qualcosa di simile a quanto segue funziona:

def validate_nick(self, attrs, source): 
    """ 
    Check that 'nick' is not already used or empty. 
    """ 
    value = attrs[source] 
    if not value: 
     raise serializers.ValidationError("Nick cannot be empty!") 
    elif self.Meta.model.objects.filter(nick=value).exists(): 
     raise serializers.ValidationError("Username %s already exists", value) 
    return attrs 
+0

funziona per il secondo errore di validazione raise serializers.ValidationError ("username" + value + "esiste già") ma l'errore di validazione sopra mostra ancora "nick": ["questo campo è obbligatorio."] E dovrebbe dire "nick" : ["Nick non può essere vuoto"] – eddwinpaz

+0

@eddwinpaz: Sei sicuro che il campo nick sia fornito e vuoto e non solo assente (cioè null)? Puoi pubblicare il codice modello pertinente? – Fiver

+0

ha modificato la domanda in modo da poter vedere il mio codice. – eddwinpaz

2

la risposta a questa domanda aggiunge anche il seguente come @Fiver ha risposto

0

Dovrebbe essere possibile modificare i messaggi di errore a livello di modello, ma purtroppo REST Framework non lo supporta ancora. Here è un problema che si occupa del problema. Include un metodo suggerito per sovrascrivere il validatore nel serializzatore.

0

È necessario utilizzare il gestore errori personalizzato. Seguire here per l'installazione.

tuo gestore di errore personalizzato dovrebbe essere come questo:

def custom_exception_handler(exc, context): 
# Call REST framework's default exception handler first, 
# to get the standard error response. 
response = exception_handler(exc, context) 

# Now add the HTTP status code to the response. 
if response is not None: 
    for field, value in response.data.items(): 
     value = ''.join(value) 
    response.data = {} # Empty django's custom error 
    response.data['detail'] =value #customize it how you want 

return response 
Problemi correlati