Django Compare UUID with String

Published 15 Nov, 2020


How to compare UUID field value with string in Django template

Introduction

I’ve below code that compare UUID with string variable in template.

{% ifequal request.GET.space_id space.id %}is-active{% endif %}

If you’re like me who thought this is easy with django template language then you’re wrong. When I was writing the if condition to check the string the expected behavior it not happend. Then after several quick search I finally found the way to do it. Here is the explantion of how I achived that.

Solution

First you need to convert UUID into the string format otherwise Django template language will not compare properly. So I’ve checked the template language documentation and found this stringformat is the way to do it.

stringformat This is helpful and I can convert UUID into string format and later I can check with the actual string. old-string-formatting And Python has the printf-style String Formatting options that we can use with Django template language stirngformat

request.GET.space_id|stringformat:"S"

Conclusion

Above code will convert the UUID into string. So the final code for checking the UUID with string like this.

{% ifequal request.GET.space_id|stringformat:"s" space.id %}is-active{% endif %}

This article published under development on django tags. Please support me by subscribing to my Newsletter. By subscribing you will not miss any future articles in this category.