Django Crispy形式没有显示bootstrap / css或按钮

时间:2017-07-13 12:49:35

标签: python django django-crispy-forms

我的模型使用了松脆的形状,虽然表单看起来很简单,并且没有显示引导程序,但似乎没有按钮。即使添加按钮并单击它(刷新),也没有数据保存到数据库中。我尝试了很多方法。什么似乎是错的?任何帮助都将受到高度赞赏。

forms.py

   class PlotForm(forms.ModelForm):
    helper = FormHelper()
    helper.form_tag = False
    helper.form_method = 'POST'

    class Meta:
        model = Plot
        fields = '__all__'

的观点:

def plot_form(request):
    return render(request, 'plot_form.html', {'form': PlotForm()})

html:

{% load crispy_forms_tags %}
    <form action="" method="POST">
   {% crispy form %}
        <input type="submit" class="btn btn-default" value="save">

2 个答案:

答案 0 :(得分:1)

首先缺少{% csrf_token %}。第二,如果我记得它是正确的,你需要使用{{ form|crispy }}加载表格。

第三,我建议使用Widget Tweaks

<form method='POST' action="/" enctype='multipart/form-data'>
 {% load widget_tweaks %}
 {% csrf_token %}
 {{ form.first_name |add_class:"customCSS1 customCSS2" }}
 {{ form.second_name |add_class:"customCSS3 customCSS4" }}
</form>
{{ form.media.js }}

使用此插件,您可以根据需要设置表单样式。所有Css课程都有效。 Crispy很不错,但是你已经进入了文档,当你想要为表单设置样式时,总是需要做一些变通办法。使用Widget Tweaks,您可以简单地应用任何CSS类。如果你真的知道你的方式与脆皮你可以做很多,但要达到这一点.... 我换了一点,现在一切都像魅力一样

希望如果不发表评论会有所帮助:)

  

修改

我刚刚在你的views.py中看到了一些东西。据我所知,您没有引用正确的表单。

from appName.forms import PlotForm

def plot_form(request):
  form = PlotForm(request.POST or None, request.FILES or None) #request files is only required when you want to upload a file
  if form.is_valid():
    instance = form.save(commit = False)
    ...
    instance.save()
    #messages.success(request, 'form was saved') #optional
  context = {
  'form':form,
  }
  return render(request, 'AppName/plot_form.html', context)

也许这会成功。您没有表单验证,我不确定&#34;()&#34;在{'form': PlotForm()}会破坏代码。

答案 1 :(得分:0)

我也遇到了同样的问题。通过在 Firefox 而不是谷歌浏览器上测试它来解决它。显然,Chrome 不会为一些本地网络应用加载 CSS 样式。遵循此 hack 后,它就可以工作了。 https://css-tricks.com/new-in-chrome-css-overview/