首页 > 解决方案 > 是否可以从前端添加到模型字段而无需调用 url 和模板?

问题描述

我有一个配方模型如下:

class Recipe(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE,related_name='recipe')
    title = models.CharField(max_length=255)
    subtitle = models.TextField(max_length=500)
    slug = models.SlugField(max_length=255)
    ingredients = models.TextField(blank=True, null=True)
    description = models.TextField(null=True, blank=True)
    image = models.ImageField(upload_to='uploads/', blank=True,null=True)
    thumbnail = models.ImageField(upload_to='uploads/', blank=True,null=True)
    date_added = models.DateTimeField(auto_now_add=True)

我通过包含所有字段的自定义表单创建此模型的实例。

我通过在 html 页面中执行以下操作,在名为 my_account 的页面中显示我的所有食谱模型。

 {% for recipe in recipes %}
                        <tr>
                            <td><a href="{% url 'recipe_details' recipe.category.slug recipe.slug %}" class='field'>{{recipe.title}}</a></td>
                            <td><a href="{% url 'update_recipe' recipe.slug %}" class='button is-dark'>Update</a></td>
                            <td><a href="{% url 'delete_recipe' recipe.slug %}" class='button is-light'>Remove</a></td>

我的问题基本上是,我可以在 my_accounts 页面中实现以下内容,当用户单击添加成分按钮时,用户输入的任何内容都会添加到该特定食谱的 recipe.ingredients 字段中。

例子:

如果用户在输入字段中输入“1 汤匙糖”并单击添加成分,对于红茶,那么“1 汤匙糖”应该被添加到我的红茶食谱模型实例的成分字段中。 在此处输入图像描述

标签: djangodjango-modelsdjango-viewsdjango-formsdjango-templates

解决方案


好的,所以我已经找到了问题所在,虽然不是完全,但可能是 50-60%。

首先,为了达到预期的效果,您必须创建另一个名为“Ingredient”的模型字段,该字段与配方模型相关联。

也来了,检索用户从前端输入的信息。

my_accounts.html 页面,您将添加以下内容。

 <td>
     <form action= "{% url 'add_ingredient' recipe.slug %}" method="POST">
     {% csrf_token %}
         <input type="text" value="Add Ingredient"  name="ingredient"><button type="submit">Add Ingredient</button>
     </form>
</td>

在 urls.py

path('add/<slug:recipe_slug>/', views.add_ingredient, name="add_ingredient"),

在views.py

def add_ingredient(request, recipe_slug):

    recipe = get_object_or_404(Recipe, slug=recipe_slug)
    ingredient = request.POST.get('ingredient')
  
    return redirect('my_account')

推荐阅读