我想知道在将help_text和其他硬编码的长行输入Python / Django时,行长度的约定是什么。我已经阅读了PEP-8,其中包含代码和注释的行长度,但是我不确定这对于长字符串文本是如何适用的。
这是字段' explanation_text'和help_text字段选项。
class Question(models.Model):
questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE)
title = models.CharField(max_length=150, blank=False)
category = models.CharField(max_length=20, blank=False)
created_date = models.DateTimeField(default=datetime.now, blank=True)
explanation_text = models.TextField(
blank=True,
help_text="Explanation text goes here. Candidates will be able to see this after they have taken a questionnaire. To change this, refer to the setting on questionnaire administration. Max length is 1000 characters.",
max_length=1000)
def __str__(self):
return self.title
答案 0 :(得分:5)
您可以使用三引号将help_text
字符串存储为多行字符串,如下所示:
help_text = """Explanation text goes here. Candidates will be able to see
this after they have taken a questionnaire. To change this,
refer to the setting on questionnaire administration. Max
length is 1000 characters."""
然而,它可能更常规:
将多行字符串存储在models.py
文件顶部的常量中:
HELP_TEXT = """Explanation text.....
..................
"""
class Question(...):
...
help_text = HELP_TEXT
将所有常量组合在一个constants.py
文件中。在models.py
中,您将拥有:
import constants
class Question(...):
...
help_text = constants.HELP_TEXT
答案 1 :(得分:2)
使用表单小部件显示额外的“帮助”文本。这很有用 用于文档,即使您的字段未在表单上使用。
请注意,此值在自动生成时不会进行HTML转义 形式。如果您愿意,这可以让您在help_text中包含HTML。对于 例如:
help_text =“请使用以下格式: YYYY-MM-DD 。”
或者你可以使用纯文本和django.utils.html.escape()来 转义任何HTML特殊字符。确保您逃避任何帮助 可能来自不受信任的用户以避免跨站点的文本 脚本攻击。
https://docs.djangoproject.com/en/1.9/ref/models/fields/#help-text
没有规则,因为它仅用于向用户/开发者提供额外信息(例如,移动设备和桌面上的线路长度要求不同)
答案 2 :(得分:2)
正如maazza所说,没有惯例。
就我而言,我喜欢使用python隐式字符串连接。
class Question(models.Model):
explanation_text = models.TextField(
blank=True,
help_text=(
"Explanation text goes here. Candidates will be able to see "
"this after they have taken a questionnaire. To change this, "
"refer to the setting on questionnaire administration. "
"Max length is 1000 characters."),
max_length=1000)
使用ugettext时干净利落:
from django.utils.translation import ugettext_lazy as _
class Question(models.Model):
explanation_text = models.TextField(
blank=True,
help_text=_(
"Explanation text goes here. Candidates will be able to see "
"this after they have taken a questionnaire. To change this, "
"refer to the setting on questionnaire administration. "
"Max length is 1000 characters."),
max_length=1000)
注意:顺便说一句,this his how django do。