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)
potete inserire il vostro modello in cui 'nick' è un campo? – Fiver