django - 是否可以从前端添加到模型字段而无需调用 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 汤匙糖”应该被添加到我的红茶食谱模型实例的成分字段中。
解决方案
好的,所以我已经找到了问题所在,虽然不是完全,但可能是 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')
推荐阅读
- r - RStudio,按列类应用函数
- qt - 为什么我抓不到OOM异常?
- sql - SQL - 错误:没有这样的列 - 加入表
- c++ - 使用 fmtlib,当值为负时,零填充数值更短,我可以调整这种行为吗?
- laravel - Laravel 8 Jetstream Inertia 没有渲染视图组件
- serialization - 嵌套序列化程序的创建方法中的非空约束失败
- flutter - 当路由到另一个页面时,我得到“有多个英雄在子树中共享相同的标签”
- elasticsearch - 无法访问 Kibana 站点
- flutter - Flutter - 如何在 Dart 中使用 HTTP 发送 POST 请求?
- python - 如果是元组,我有一个列表。如何将其转换为表格格式?