Home > Mobile >  change the label of a field in a django form
change the label of a field in a django form

Time:12-13

I am working on a blog website project. I am using Django crispy form to create blog posts. Users can post articles by clicking the post button. On the add post page, users have to provide title, content, image. User also have to select category.

blog/model.py

from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.urls import reverse

# Create your models here.
class Category(models.Model):
    cid = models.AutoField(primary_key=True, blank=True) 
    category_name = models.CharField(max_length=100)

    def __str__(self):
        return self.category_name


class Post(models.Model):
    aid = models.AutoField(primary_key=True)
    image = models.ImageField(null=True, blank=True, default='blog-default.png', upload_to='images/')
    title = models.CharField(max_length=200)
    content = models.TextField()
    created = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    cid = models.ForeignKey(Category, on_delete=models.CASCADE) 

    def __str__(self):
        return self.title

    
    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk':self.pk})

views.py

from django.shortcuts import render
from .models import Post
from django.views.generic import CreateView
from django.contrib.auth.mixins import LoginRequiredMixin


class UserPostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content', 'image', 'cid']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

post_form.py

{% extends 'users/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
    <div >
        <form method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <fieldset >
                <legend >Add Post</legend>
                {{ form|crispy }}
            </fieldset>
            <div >
                <button type="submit" > Post </button>
            </div>
        </form>
    </div>
   

{% endblock content %}

Here, the .html file in the browser shows that the label of the category is 'Cid'. But I want this label as 'Select Category'. How can I change this?

UI

Django form...........

CodePudding user response:

You can add a verbose_name to your field in the models.py. That is the value that is displayed when generating forms. Like this:

cid = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Select Category') 

CodePudding user response:

You can use this method in forms.py:

class form(forms.ModelForm):
class Meta:
    ....

    labels={
        'cid': 'Select Category',
    }
    ....

or

cid = forms.Select(label='Select Category')
  • Related