在用htm编写的textfield内呈现Django标记

2024-05-13 19:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django和一般编程的初学者,想问一个关于如何在textfield内保存html中呈现django模型字段的问题。在

我的代码段如下:

在模型.py在

class Recipe(models.Model):
    recipe_name = models.CharField(max_length=128)
    recipe_text = models.TextField()
    ingredients = models.TextField()

def __str__(self):
    return self.recipe_name

我有一个成分模型,其中包含对象的成分,例如糖或盐。在

^{pr2}$

例如,如果我创建的salt component对象的成分名为“salt”,我想在实例化的配方对象中调用component_name,components字段使用ul list html代码在其中保存,并使用autoescape或safe标记将代码传递到模板。但这似乎并不适用于这个领域。 html对ul列表有效,但内容似乎不起作用。例如,它将只加载{components.0.component_name}}字符串

我同时传递配方对象和配料对象视图.py在

还有别的办法吗?在


Tags: 对象djangonamepy模型selfmodelshtml
1条回答
网友
1楼 · 发布于 2024-05-13 19:31:58

您需要将配方与配料相关联:

class Ingredient(models.Model):
    ingredient_name = models.CharField(max_length=200)
    ingredient_text = models.TextField()

    def __str__(self):
        return self.ingredient_name

class Recipe(models.Model):
    recipe_name = models.CharField(max_length=128)
    recipe_text = models.TextField()
    ingredients = models.ManytoMany(Ingredient)

    def __str__(self):
        return self.recipe_name

然后,创造你的配料,像这样:

^{pr2}$

接下来,将其添加到配方中:

recipe = Recipe()
recipe.recipe_name = 'Salty Chips'
recipe.recipe_text = 'Great for parties'
recipe.save() # You have to save it first

recipe.ingredients_set.add(salt)
recipe.ingredients_set.add(chips)

recipe.save() # Save it again

现在,在你看来:

def show_recipe(request):
    recipes = Recipe.objects.all()

    return render(request, 'recipe.html', {'recipes': recipes})

最后,在模板中:

{% for recipe in recipes %}
   {{ recipe.recipe_name }}
   <hr />
   Ingredients:
   <ul>
   {% for ingredient in recipe.ingredients_set.all %}
      <li>{{ ingredient }}</li>
   {% endfor %}
   </ul>
{% endfor %}

这是因为您在RecipeIngredient模型之间创建了一个关系,使得每个Recipe可以有一个或多个{}对象链接到它。在

Django将为您跟踪关系,使用模型api,您可以向任何配方对象添加(或删除)成分。在

因为这些关系是为您管理的,所以每当您有一个Recipe对象时,它就会知道所有链接到它的Ingredient对象;我们可以轻松地打印正确的配方。在

相关问题 更多 >