在Django中为表单字段添加占位符



所以我看到了很多不同的方法来实现这一点,但没有一种适合我的设置方式。我想为我的表单中的文本字段添加占位符("用户"、"标题"、"注释"(

表单.py

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

型号.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中(带一个"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'
)

相关内容

  • 没有找到相关文章

最新更新