フォームからデータベースにデータを挿入したい。モデルは次のとおりです。
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>
私はdjangoの初心者であるため、レシピ、材料、およびPrepration_stepテーブルにレシピのタイトル、材料、および手順を挿入する方法を教えてください。ありがとう