渲染django标签里面用html写的文本字段

时间:2016-07-14 03:31:21

标签: python html django

我是django和一般编程的初学者,想问一下有关如何在文本字段中保存html的django模型字段的问题。

我的代码段如下:

models.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

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

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

    def __str__(self):
        return self.ingredient_name

例如,如果我使用salt' salt的成分名称创建salt成分对象,我想在实例化的Recipe对象中调用ingredient_name,使用ul list html代码将成分字段保存在其中使用表单并传递使用autoescape或安全标记的模板代码。但它似乎不适合该领域。 用于ul列表的html工作,但内容似乎不起作用。它只会加载例如{{ingredients.0.ingredient_name}}

的字符串

我在views.py

中传递配方对象和成分对象

有没有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

您需要将配方链接到配料:

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

然后,创建你的成分,如下:

salt = Ingredient(ingredient_name='salt', ingredient_text='as per taste')
salt.save()

chips = Ingredient()
chips.ingredient_name = 'Chips'
chips.ingredient_text = 'Delicious, goes well with salt'
chips.save()

接下来,将其添加到食谱中:

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都可以有一个或多个Ingredient个对象链接到它

Django将跟踪您的关系,并使用模型api,您可以添加(和删除)成分到任何配方对象。

由于为您管理关系,因此只要您拥有Recipe对象,它就会知道链接到它的所有Ingredient个对象;我们可以轻松打印正确的食谱。