我正在使用crispy呈现我的表单,但是我遇到了在不影响其他字段的情况下呈现单个字段的问题。
此表单:
class SettingsUpdateForm(forms.ModelForm):
class Meta:
model = User
fields = ('about_text', 'github_name')
labels = {
'about_text': '',
'github_name': 'github.com/' # TODO make inline with field
}
widgets = {
'about_text': forms.Textarea(attrs={'placeholder': 'Describe yourself!'}),
'github_name': forms.TextInput(attrs={'placeholder': 'your_github_name'})
}
help_texts = {
'github_name': 'Showcase a project instead: <em>/username/fav_project</em>',
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self) # this is required to display the help_texts渲染方式如下:

我希望将github/标签与输入字段放在同一行。我该怎么做?
Horizontal Forms会让所有标签成为bootstraps网格模型的一部分--这是我不想要的。
我也尝试过使用Inline Forms,但也不起作用。
发布于 2021-02-28 07:42:15
在您的小部件中,您需要包含一个属性,该属性将使crispyforms知道如何呈现它。试试这个:
'github_name': forms.TextInput(attrs={'class': 'form-control',
'placeholder': 'your_github_name'})如果有效,请让我知道
发布于 2021-02-28 08:46:52
我能够用一个黑客自己解决它。这是我想出的解决方案:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper(self)
'''
hacky solution - replace the standard label with a fake label.
Wrap those 2 as columns of a Row - use col-auto on first to not have whitespace between.
Use g-0 to not have gutters between columns - padding and margin would else create whitespace
'''
self.helper.layout = Layout(
Div('about_text'),
Row(
# create a "fake" label with a HTML Column
Column(HTML('<em class="fab fa-github fa-2x"></em> github.com/'), css_class='col-auto'),
Column('github_name', css_class='col'),
css_class='row g-0'
)
)我也不得不去掉github_name的标签。但它现在看起来很好:

https://stackoverflow.com/questions/66404461
复制相似问题