I have a model UserProfile:
class UserProfile(models.Model):
class Meta:
db_table = 't_user_profile'
display_name = models.CharField(
max_length=20,
unique=True,
error_messages={
'unique': ("A user with that display name already exists."),
},
blank=True
)
I have a view function:
@csrf_exempt
def change_display_name(request):
data = json.loads(request.body.decode('utf-8'))
display_name = data.get('displayName')
try:
user_profile = UserProfile.objects.get(id=2)
except UserProfile.DoesNotExist:
return JsonResponse({'error': 'User does not exist.'}, safe=False)
user_profile.display_name = display_name
user_profile.save()
return JsonResponse({'status': 'SUCCESS'}, safe=False)
How do I try except the unique display_name and return in JSON the custom error message I setup in my model?
display_nameis your only input of user_profile model, you can catch integrity error send your response.