我想将表单中的数据插入数据库。以下是型号:
from django.db import models
from django.forms import ModelForm
# Create your models here.
class Recipe(models.Model):
title=models.CharField(max_length=200)
class User(models.Model):
fname=models.CharField(max_length=30)
lname=models.CharField(max_length=30)
class Recipe2User(models.Model):
user_id=models.ForeignKey(User)
recipe_id=models.ForeignKey(Recipe)
class Ingredient(models.Model):
recipe_id=models.ForeignKey(Recipe)
name=models.CharField(max_length=200)
class Prepration_step(models.Model):
recipe_id=models.ForeignKey(Recipe)
step=models.CharField(max_length=1000)
class RecipeForm(ModelForm):
class Meta:
model=Recipe
fields=['title']
我创建了一个包含食谱名称、成分和准备步骤的表格。
下面是处理帖子的视图:
def createRecipe_form(request):
c = {}
c.update(csrf(request))
return render_to_response('create.html',c)
def create_recipe(request):
if request.method == 'POST':
form=RecipeForm(request.POST)
if form.is_valid():
title=form.cleaned_data['recipe_name']
r=Recipe(title)
r.save()
return HttpResponseRedirect('display.html')
else:
form=RecipeForm()
return render(request, 'create.html', {
'form': form,
})
这是我创建的 html 表单
<html>
<head>
<title>Create-Recipe</title>
</head>
<body>
<h1>My Recipe-Create a recipe</h1>
<form action="/recipe/submit-recipe/" method="post">
{% csrf_token %}
{% if errors %}
<div id="errors">
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
</div>
{% endif %}
Title:
<input type="text" name="recipe_name" placeholder="Ex:Gobi Masala"><br>
Ingredient:
<textarea rows="4" name="recipe_ingredient" cols="50" placeholder="Ex: 2 cups rice,1/2 teaspoon oil"></textarea><br>
Preparation:
<textarea rows="4" name="recipe_preparation" cols="50" placeholder="Ex:Pour oil in frying pan,Fry onions till they turn light brown"></textarea><br>
<input type="submit" value="OK">
</form>
请告诉我如何在食谱、配料和 Prepration_step 表中插入食谱标题、配料和步骤,因为我是 django 的新手。谢谢