是否可以在通用的“创建”视图表单中添加占位符?

时间:2018-08-25 20:52:41

标签: 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"]

我从模板中的模型添加通用的Create视图。 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)

我想在表单中添加一个占位符。是否可以在通用的“创建”视图表单中添加占位符?请为一个字段添加一个占位符,其余的我会做。

2 个答案:

答案 0 :(得分:2)

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

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 answerdocs 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'}),
        }

答案 1 :(得分:1)

谢谢@cyrlop,您的回答很好。但是,如果有人不想更改从模型本身获取的小部件的类型,我发现这种方法更合适

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.attrs ={'placeholder': 'Your placeholder','class':'someclass'}
        return form