How to apply placeholder to input when adding form using Django.

Asked 2 years ago, Updated 2 years ago, 53 views

I was studying alone through Jango Girls tutorial , and I wonder how to apply placeholder to the input/text area of the title and text attached below. If you share the code you are writing, it is as follows.

ps: self.fields['name'].They told me to apply widget.attrs.update({'class': 'special'}) but it's not easy because I have low basic understanding.

forms.py

from django import forms

from .models import Post

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text')

models.py

from django.db import models
from django.utils import timezone


class Post(models.Model):
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

python django

2022-09-21 15:21

1 Answers

I slowly looked at the other answers in the stackoverflow I attached and applied them one by one and solved them. When it didn't work, I was in a hurry and tried again after a day, and it just worked. I added the following code to the code below and it worked. :-) Thank you.

widgets = {
    'title': forms.TextInput(attrs={'placeholder': 'Name'}),
    'text': forms.Textarea(
        attrs={'placeholder': 'Enter description here'}),
}

forms.The full text of the py code.

from django import forms

from .models import Post

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title', 'text')

        widgets = {
            'title': forms.TextInput(attrs={'placeholder': 'Name'}),
            'text': forms.Textarea(
                attrs={'placeholder': 'Enter description here'}),
        }


2022-09-21 15:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.