Categories
Python Answers

How to rename a model and relationship fields with Python Django migrations?

Sometimes, we want to rename a model and relationship fields with Python Django migrations.

In this article, we’ll look at how to rename a model and relationship fields with Python Django migrations.

How to rename a model and relationship fields with Python Django migrations?

To rename a model and relationship fields with Python Django migrations, we can use the RenameModel and RenameField methods.

For instance, we write

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0001_initial'), 
    ]

    operations = [
        migrations.RenameModel('Foo', 'Bar'),
        migrations.RenameField('AnotherModel', 'foo', 'bar')
    ]

to create the Migration migration class that has the operations list.

We call RenameModel to rename a model field’s name from Foo to Bar.

And we call RenameField to rename the related fields from 'foo' to 'bar'.

Then we run manage.py makemigrations to run the migration.

Conclusion

To rename a model and relationship fields with Python Django migrations, we can use the RenameModel and RenameField methods.

Categories
Python Answers

How to change the header ‘Django administration’ text with Python Django admin?

Sometimes, we want to change the header ‘Django administration’ text with Python Django admin.

In this article, we’ll look at how to change the header ‘Django administration’ text with Python Django admin.

How to change the header ‘Django administration’ text with Python Django admin?

To change the header ‘Django administration’ text with Python Django admin, we set the admin.site.site_header property.

For instance, we write

from django.contrib import admin

admin.site.site_header = 'My project'          
admin.site.index_title = 'Features area'          
admin.site.site_title = 'HTML title from adminsitration'

in urls.py to set the admin.site properties to set the site header, index title, and site title.

site_header set the site’s title.

Conclusion

To change the header ‘Django administration’ text with Python Django admin, we set the admin.site.site_header property.

Categories
Python Answers

How to register users in Python Django REST framework?

Sometimes, we want to register users in Python Django REST framework.

In this article, we’ll look at how to register users in Python Django REST framework.

How to register users in Python Django REST framework?

To register users in Python Django REST framework, we can call objects.create_user on the user model.

For instance, we write

from rest_framework import serializers
from django.contrib.auth import get_user_model # If used custom user model

UserModel = get_user_model()


class UserSerializer(serializers.ModelSerializer):

    password = serializers.CharField(write_only=True)

    def create(self, validated_data):
        user = UserModel.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password'],
        )

        return user

    class Meta:
        model = UserModel
        fields = ( "id", "username", "password", )

to get the user model with get_user_model.

Then we create the UserSerializer model class that calls UserModel.objects.create_user to create a new user.

Conclusion

To register users in Python Django REST framework, we can call objects.create_user on the user model.

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.