0

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?

2
  • as display_name is your only input of user_profile model, you can catch integrity error send your response. Commented Feb 14, 2019 at 11:52
  • 1
    You should use a form for this. Or, since you're dealing with JSON, you should use Django REST Framework and its serializers to manage the whole thing. Commented Feb 14, 2019 at 11:57

2 Answers 2

0

Do You want to handle UNIQUE intergrityError? See this question

Sign up to request clarification or add additional context in comments.

Comments

0

You need to run validation before saving. Here is an example based on the documentation:

from django.core.exceptions import ValidationError

user_profile.display_name = display_name

try:
    user_profile.full_clean()
except ValidationError as e:
    # Do something based on the errors contained in e.message_dict.
    return JsonResponse({'error': 'Some error message.'}, safe=False)

user_profile.save()

If, for some reason, you don't want to do full validation, you can check just the uniqueness constraints with user_profile.validate_unique() instead of full_clean(). Read more here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.