Categories
Python Answers

How to highlight links in Python Django templates?

Sometimes, we want to highlight links in Python Django templates

In this article, we’ll look at how to highlight links in Python Django templates

How to highlight links in Python Django templates?

To highlight links in Python Django templates, we can create a tag.

For instance, we write

@register.simple_tag
def active(request, pattern):
    import re
    if re.search(pattern, request.path):
        return 'active'
    return ''

to create the active tag that returns 'active' if the current URL patches the path pattern for the link.

We use the @register.simple_tag tag to register the template tag.

Then in urls.py, we add some routes by writing

urlpatterns += patterns('',
    (r'/$', view_home_method, 'home_url_name'),
    (r'/services/$', view_services_method, 'services_url_name'),
    (r'/contact/$', view_contact_method, 'contact_url_name'),
)

And then in a template, we write

{% load tags %}

{% url 'home_url_name' as home %}
{% url 'services_url_name' as services %}
{% url 'contact_url_name' as contact %}

<div id="navigation">
    <a class="{% active request home %}" href="{{ home }}">Home</a>
    <a class="{% active request services %}" href="{{ services }}">Services</a>
    <a class="{% active request contact %}" href="{{ contact }}">Contact</a>
</div>

to use the active tag to set the class attribute to active if the link URL matches the current URL.

Conclusion

To highlight links in Python Django templates, we can create a tag.

Categories
Python Answers

How to create custom error messages with model forms with Python Django?

Sometimes, we want to create custom error messages with model forms with Python Django.

In this article, we’ll look at how to create custom error messages with model forms with Python Django.

How to create custom error messages with model forms with Python Django?

To create custom error messages with model forms with Python Django, we can add error_messages to Meta class of the form class.

For instance, we write

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        labels = {
            'name': _('Writer'),
        }
        help_texts = {
            'name': _('Some useful help text.'),
        }
        error_messages = {
            'name': {
                'max_length': _("This writer's name is too long."),
            },
        }

to create the AuthorForm class that has the Meta class that has the error messages.

In Meta, we add the error_messages static field that’s set to a dictionary with the field name as the keys and the validation error message dictionaries as the values.

Conclusion

To create custom error messages with model forms with Python Django, we can add error_messages to Meta class of the form class.

Categories
Python Answers

How to get the full URL of the image value of a Python Django REST framework Imagefield?

Sometimes, we want to get the full URL of the image value of a Python Django REST framework Imagefield.

In this article, we’ll look at how to get the full URL of the image value of a Python Django REST framework Imagefield.

How to get the full URL of the image value of a Python Django REST framework Imagefield?

To get the full URL of the image value of a Python Django REST framework Imagefield, we can get it from the image value’s url property.

For instance, we write

class CarSerializer(serializers.ModelSerializer):
    photo_url = serializers.SerializerMethodField()

    class Meta:
        model = Car
        fields = ('id','name','price', 'photo_url') 

    def get_photo_url(self, car):
        request = self.context.get('request')
        photo_url = car.photo.url
        return request.build_absolute_uri(photo_url)

to create the CarSerializer that get the URL of the car.photo image from car.photo.url.

And then we call request.build_absolute_uri with the URL to return the absolute URL.

Conclusion

To get the full URL of the image value of a Python Django REST framework Imagefield, we can get it from the image value’s url property.

Categories
Python Answers

How to generate a random hex color in Python?

Sometimes, we want to generate a random hex color in Python.

In this article, we’ll look at how to generate a random hex color in Python.

How to generate a random hex color in Python?

To generate a random hex color in Python, we can generate random numbers for rgb values.

For instance, we write

import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))

to call the random.randint method to generate numbers between 0 and 255.

We call that in a lambda function and we assign the lambda function to r.

Then we call r 3 times to generate the rgb values.

Conclusion

To generate a random hex color in Python, we can generate random numbers for rgb values.

Categories
Python Answers

How to convert datetime.timedelta to minutes, hours in Python?

Sometimes, we want to convert datetime.timedelta to minutes, hours in Python.

In this article, we’ll look at how to convert datetime.timedelta to minutes, hours in Python.

How to convert datetime.timedelta to minutes, hours in Python?

To convert datetime.timedelta to minutes, hours in Python, we can use the timedelta’s total_seconds method to get the datetime difference in seconds.

For instance, we write

seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

to call total_seconds on the duration timedelta object.

And then we get the hours, minutes, and seconds by calculating the values from the seconds.

Conclusion

To convert datetime.timedelta to minutes, hours in Python, we can use the timedelta’s total_seconds method to get the datetime difference in seconds.