首页 > 解决方案 > Django Form 填写时说该字段是必填项

问题描述

我从我的 git 中删除了一些无用的分支,现在我网站上的一个功能不起作用。当我尝试在每个字段都填满时以普通用户的身份添加食谱时,我按下“添加食谱”按钮,它显示成分字段是必需的,因此 Django 将这个字段视为空的......但事实并非如此。

看法:

def add_recipe(request):

     add_recipe = RecipeForm(request.POST)
     print(add_recipe['ingredients'].value())
     if add_recipe.is_valid():
          add_recipe.save()
          return redirect('success_added_recipe')

     return render(request, 'drinks/add_recipe.html', {'RecipeForm': add_recipe})

形式:

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        fields = ['recipe_name', 'preparation', 'ingredients', 'recipe_image']

调试日志

(0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=()
(0.001) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient" WHERE "drinks_ingredient"."id" IN (12); args=(12,)
(0.000) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient"; args=()
"POST /accounts/add_recipe/ HTTP/1.1" 200 1637
(0.002) 

模型:

class Recipe(models.Model):

  recipe_name = models.CharField(max_length=250)
  preparation = models.CharField(max_length=1000)
  ingredients = models.ManyToManyField(Ingredient)
  recipe_image = models.ImageField(upload_to='images/', default='')


  def __str__(self):
    return self.recipe_name

模板:

<h1>Add recipe</h1>

<form method="post" action="{% url 'add_recipe' %}">
{% csrf_token %}
<table>
{{RecipeForm}}
</table>
<input type="submit" value="Add recipe"/>
</form>

在此处输入图像描述

标签: djangoforms

解决方案


推荐阅读