python - 是否可以在通用创建 View 表单中添加占位符?

标签 python django python-3.x django-models django-forms

这是我的 models.py 文件

class Report_item(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    title = models.CharField(max_length=255)
    item_type = models.CharField(default="", max_length=100)
    location = models.CharField(max_length=60)
    city = models.CharField(max_length=60)
    date = models.DateTimeField(default=timezone.now)
    Description = models.TextField(blank=True,null=True)
    publish = models.BooleanField(default=False)

    image = models.ImageField(default="add Item image")

    def __str__(self):
        return self.title + "      " + str(self.publish)

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

    class Meta:
        ordering = ["-date"]

我在模板中添加了从模型创建通用 View 。 views.py 文件如下:

class ReportCreate(generic.CreateView):
    model = Report_item
    fields = ['title', 'item_type', 'location', 'city', 'image', 'Description']

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.owner = self.request.user
        self.object.save()
        return FormMixin.form_valid(self, form)

我想在我的表单中添加一个占位符。是否可以在通用创建 View 表单中添加占位符?请为一个字段添加一个占位符,剩下的我会做。

最佳答案

对于通用 View ,您可以这样做:

class ReportCreate(generic.CreateView):
    model = Report_item
    fields = ['title', 'item_type', 'location', 'city', 'image', 'Description']


    def get_form(self, form_class=None):
        if form_class is None:
            form_class = self.get_form_class()

        form = super(ReportCreate, self).get_form(form_class)
        form.fields['field_to_add_placeholder'].widget = forms.TextInput(attrs={'placeholder': 'Your placeholder'})
        return form

    # rest of the class...

参见this answer并参见docs on widgets .

对于 ModelForm,请参阅 this part文档的。您可以通过添加占位符属性来覆盖默认字段(在本例中为小部件):

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'placeholder': 'Enter your name here'}),
        }

关于python - 是否可以在通用创建 View 表单中添加占位符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52021136/

相关文章:

python - 读取非常大的一行文本文件

python - 从十六进制字符串表示创建原始 unicode 字符/输入单个反斜杠

python - nginx.service : Failed to read PID from file/run/nginx. pid:无效参数

Django 一对多模型和管理内联

python - 如何更新 Google 应用程序脚本中的 mailgun 路由

python - 使用 HTTPS 提供安全的 Django 页面

django - 创建 CustomUser 时 Syncdb 错误

python - 如何解决 "Invalid use of Function(<built-in function abs>)"

python - 如何上下移动 Sprite ?

python - 替换一系列 Pandas 中的值