将占位符添加到 Django 中的表单字段

Adding placeholder to form field in Django

所以我见过很多不同的方法来做到这一点,但 none 适合我的设置方式。我想为表单中的文本字段添加占位符 ('user'、'title'、'comment')

forms.py

class RestroomForm(forms.ModelForm):
    class Meta:
        model = RestroomReview
        fields = (
            'user', 'public', 'rest_type', 
            'baby', 'needle', 'handicap', 
            'rating', 'title', 'comment'
            )

models.py

class RestroomReview(models.Model):
    ...
    ...
    ...
    venue = models.ForeignKey(Venue, blank=False, on_delete=models.CASCADE)
    user = models.CharField(max_length=200, blank=False)
    public = models.BooleanField(blank=False)
    rest_type = models.CharField(
        max_length=1, 
        choices=RESTROOM_TYPE_CHOICES, 
        default=MEN
    )
    baby = models.BooleanField('Changing Table')
    needle = models.BooleanField('Sharps Container')
    handicap = models.BooleanField('Handicap Accessible')
    rating = models.IntegerField(choices=RATING_CHOICES, default=1)
    title = models.CharField(max_length=200, blank=False)
    comment = models.TextField(max_length=1000, blank=False)
    posted_date = models.DateTimeField(blank=False)

    def publish(self):
        posted_date = datetime.datetime.today()
        self.save()
    
    def __str__(self):
        return f'Review for {self.venue.name} by {self.user}'

venue_detail.html

<!-- form to review restroom -->
<div class="container">
    <form method="POST" action="{% url 'venue_detail' venue_pk=venue.pk %}">
        {% csrf_token %}

        {% for field in restroom_form %}
            <div class="form-group">
                <label for="{{ field.id_for_label }}">{{ field.label }}</label><br>
                {{ field|add_class:'form-control' }}
            </div>
        {% endfor %}
        <input type="submit" value="Submit">
    </form>
</div>

有没有办法在models.py中设置占位符?我在 forms.py 中设置它时遇到问题,就像我在此处看到的建议一样。或者有什么地方可以将它添加到我的模板中?让我知道我是否可以提供更多 info/context。

这应该在您的 forms.py 中(以 'user' 为例。并非所有参数都是必需的):

from django.core.validators import RegexValidator

def My_TextField_Validator(self):
    return RegexValidator(r'^[-a-zA-Z0-9. ]+$',
    'Valid Input: Alphanumeric characters, dash, dot, space')

class RestroomForm(forms.ModelForm):
    user = forms.CharField(max_length=50, min_length=4, required=True,
                           help_text='My help text', label='My Label',
                           validators=[My_TextField_Validator],
                           widget=forms.TextInput(attrs={'class': 'form-control', 
                           'placeholder': 'User'}))
    class Meta:
        model = RestroomReview
        fields = (
            'user', 'public', 'rest_type', 
            'baby', 'needle', 'handicap', 
            'rating', 'title', 'comment'
            )