我正在使用Django 2.0,并使用基于类的视图和Django表单。当某人写帖子时,所有空白都被剥去。我了解这是django自1.9起就一直在做的事情。但是,我想保留空白,因为当前正在将帖子的详细视图呈现为单个页面,特别是为了便于阅读。我发现Stack Exchange Post部分地解决了这个问题,但是我还没有设法使它起作用。如果作为检查打印到控制台,则包括所有空格(\ n和\ r):
[23/Apr/2019 10:26:02] "GET /microblog/18/update/ HTTP/1.1" 200 9235
{'category': <Category: Other>, 'name': 'Me', 'title': 'Just a refactoring test', 'body': 'This site has been refactored quite massively so, here is a test blog to reflect that.\r\n\r\n\r\n\r\nTrying to add whitespace', 'url': 'http://127.0.0.1:8000/microblog/create/'}
在“详细信息视图”页面中查看时,该页面为空白。我怀疑表单中的多余代码实际上无法正常工作。这是我的表格:
class BlogModelForm(forms.ModelForm):
# this is the extra method added to strip whitespace
def __init__(self, *args, **kwargs):
super(BlogModelForm, self).__init__(*args, **kwargs)
self.fields['body'].strip = False
class Meta:
model = Blog
fields = [
'category',
'name',
'title',
'body',
'url',
]
这是我的观点:
class BlogCreateView(CreateView):
template_name = 'microblog/create_blog.html'
form_class = BlogModelForm
queryset = Blog.objects.all()
def form_valid(self, form):
print(form.cleaned_data)
return super().form_valid(form)
是否可以在详细视图中呈现空白?