【问题标题】:Create function is not working while using Django-crispy-forms使用 Django-crispy-forms 时创建功能不起作用
【发布时间】:2021-05-26 15:07:05
【问题描述】:

我的应用程序中有一个产品模型,我创建了一个 forms.py 文件以及一个视图函数,以便在其中创建一个对象。然后我在我的模板中使用它。填写完所有字段并按提交后,页面只会重新加载,并且不会创建产品对象。

models.py

class Product(models.Model):
    name = models.CharField(max_length=36)
    price = models.PositiveIntegerField()
    description = models.TextField()
    quantity = models.PositiveIntegerField()
    image = models.ImageField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

forms.py

from django import forms
from .models import *

class AddProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = '__all__'

views.py

def Addproduct(request):

    form = AddProductForm()
    if request.method == 'POST':
        form = AddProductForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, "Products Added Successfully")
            return redirect('product')

    context = {"form":form}

    return render(request, "core/addproduct.html", context)

添加产品.html

<form method="post">
{% csrf_token %}
<div class="form-row">
  <div class="form-group col-md-4 mb-0">
    {{ form.name|as_crispy_field }}
  </div>
  <div class="form-group col-md-4 mb-0">
    {{ form.price|as_crispy_field }}
  </div>
  <div class="form-group col-md-4 mb-0">
    {{ form.quantity|as_crispy_field }}
  </div>
</div>
{{ form.description|as_crispy_field }}
<div class="form-row">
  <div class="form-group col-md-6 mb-0">
    {{ form.image|as_crispy_field }}
  </div>
  <div class="form-group col-md-6 mb-0">
    {{ form.user|as_crispy_field }}
  </div>
</div>
<button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">Add Product</button>
</form>

【问题讨论】:

  • 在渲染模板之前尝试print(form.errors) 你会得到什么输出?您的表单输入很可能在某些方面无效。
  • 在处理表单中的文件时,应在 HTML 中的表单标签中添加enctype="multipart/form-data"
  • 谢谢先生,它解决了我的问题,但为什么甚至没有发送错误,所以我可以看到它。

标签: python django django-models django-views django-crispy-forms


【解决方案1】:

我可以通过将enctype="multipart/form-data" 添加到表单来解决此问题。

<form method="post" enctype="multipart/form-data">
  {% csrf_token %}
  <div class="form-row">
    <div class="form-group col-md-4 mb-0">
      {{ form.name|as_crispy_field }}
    </div>
    <div class="form-group col-md-4 mb-0">
      {{ form.price|as_crispy_field }}
    </div>
  </div>
  <button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">Add Product</button>
</form>

【讨论】:

    猜你喜欢
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2015-10-22
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    相关资源
    最近更新 更多