我希望你一切都好。您知道如何将其添加到按钮中吗?
<img src="{{user.userprofile.image.url}}" width="22px" height="22px" style="border-radius: 90px;background: #ffffff38;">
我已经尝试过,但是在我的页面上始终将其翻译为“评论”。
class CreateCommentForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super(CreateCommentForm, self).__init__(*args,**kwargs)
self.helper = FormHelper()
self.helper.form_method="post"
self.helper.layout = Layout(
Field("content",css_class="form-control",style="margin-bottom:10px",rows="1"),
)
self.helper.add_input(Submit('submit','<img src="{{user.userprofile.image.url}}" width="22px" height="22px" style="border-radius: 90px;background: #ffffff38;"> Comment',css_class="btn btn-sm",style="background-color: #0d6ec5;border-color: #0d6ec5;"))
class Meta:
model = Comment
fields = [
'content'
]
看来您正在尝试解决两个难题:在表单按钮(userprofile.image
)中包含动态信息,然后具有带有图像/ HTML内容的提交按钮。
init
方法中添加kwarg / parameter ,以便在视图中创建表单对象时可以将用户传递给它。Submit
按钮(创建一个input
元素),不如使用StrictButton
它创建一个button
元素的方法,并且可以用任何想要的HTML填充。我会注意到的文档StrictButton
位于一个怪异的地方:https : //django-crispy-forms.readthedocs.io/en/latest/layouts.html,与各个按钮上的文档分开。还值得注意的是,您可以简单地Button
以类似的方式使用该类,但是StrictButton类具有一些装饰,可以使使用Bootstrap的人更轻松。(查看该crispy_forms.bootstrap
模块以了解更多信息。)这是我如何更新您的代码:
# View function:
def my_view(request):
...
comment_form = CreateCommentForm(user=request.user)
...
# Forms:
from crispy_forms.bootstrap import StrictButton
class CreateCommentForm(forms.ModelForm):
# Adding the user kwarg here:
def __init__(self, user, *args, **kwargs):
super(CreateCommentForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = "post"
# Set up the HTML content for the StrictButton:
button_content = f'<img src="{user.userprofile.image.url}" width="22px" height="22px" ' \
f'style="border-radius: 90px;background: #ffffff38;"> Comment'
self.helper.layout = Layout(
Field("content", css_class="form-control", style="margin-bottom:10px", rows="1"),
# Add the button to the layout:
StrictButton(button_content, type='submit', css_class='btn btn-primary btn-block', id='save'),
)
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句