gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:09:02 26 4
gpt4 key购买 nike

这是我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com