【问题标题】:Django and crispy form, how to add id and name in the crispy LayoutDjango和crispy form,如何在crispy Layout中添加id和name
【发布时间】:2020-09-17 13:00:07
【问题描述】:

我正在尝试在我的模板中使用 Crispy Forms,但我无法让 nameidclass 在布局中正确呈现。 换句话说,我有以下模板:

 <div class="modal-body">
        <label for="conto">Conto</label>
        <input class="form-control" id="form-conto" name="formConto"/>
 </div>

所以我想删除输入行并添加脆性字段,例如输入字段上的id="form-conto" name="formConto"

我知道我必须在我的 Model.forms 中添加布局,但我不明白如何获取它。

这是我的表格:

class MaterialeForm(forms.ModelForm):

    class Meta:
        model = Materiale
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()

这里是我的模型:

class Materiale(models.Model):
    conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True)

【问题讨论】:

    标签: django django-models django-forms django-templates django-crispy-forms


    【解决方案1】:

    在模板的顶部,加载清晰的标签:

    {% load crispy_forms_tags %}
    

    然后,告诉 Crispy 使用 Crispy 标签呈现您的表单:

    <div class="modal-body">
      {% crispy materialeform materialeform.helper %}
    </div>
    

    在您的forms.py 中,您需要添加一个Layout

    from crispy_forms import FormHelper, Layout
    
    ... 
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.helper = FormHelper()
            self.layout = Layout(
                Field('conta', id="form-conto", css_class="form-control", title="Conto")
            )
    
    

    请参阅有关布局的文档:https://django-crispy-forms.readthedocs.io/en/latest/layouts.html

    然后,当对表单发出 GET 请求时,它将(或多或少)按照您的需要呈现。你可能需要调整一些东西。按照上面的布局文档到达那里。

    但是,除非您在模板中实际传递表单,否则这些都不起作用。也许您已经在这样做了,例如,使用通用 FormView,但如果没有,这就是您在视图中需要的:

    from .forms import MaterialeForm
    from django.template import RequestContext
    
    def materialeview(request, template_name):
        materialeform = MaterialeForm()
    
        # Form handling logic
        [...]
    
        return render_to_response(template_name, {'materialeform': materialeform}, context_instance=RequestContext(request))
    

    RequestContext,见https://docs.djangoproject.com/en/3.0/ref/templates/api/#using-requestcontext

    有关 Crispy Forms 的更多信息,请参阅 https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html

    最后,由于 Crispy Forms 在后台做了很多工作,您可以考虑通过大声告诉它失败来消除混乱。把它放在你的settings.py 文件中:

    CRISPY_FAIL_SILENTLY = not DEBUG
    

    顺便说一句,如果您还不太了解 Django Forms,Crispy Forms 可能会引起很多混乱。我会说先从 Django 的内置表单开始,然后当你想做更高级的事情时再变得酥脆。这里的文档应该会有所帮助:https://docs.djangoproject.com/en/3.0/topics/forms/

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 2021-09-24
      • 2013-08-01
      • 2021-05-25
      • 2020-08-04
      • 2020-03-10
      • 2022-10-12
      • 2015-08-29
      相关资源
      最近更新 更多