从表单django将数据插入表中

时间:2013-02-16 09:08:05

标签: django django-models django-views

我想将表格中的数据插入数据库。以下是模型:

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的新手。 感谢

1 个答案:

答案 0 :(得分:0)

<强> forms.py

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe

<强> views.py

def create_recipe(request):
    if request.method == 'POST':
        form=RecipeForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('app_name:url_name'))
    return  render(request, 'create.html', {
        'form': RecipeForm(),
    })

<强> HTML

<form action="/recipe/submit-recipe/" method="post">
    {% csrf_token %}
    {{form.as_p}}
    <input type="submit" value="OK">
</form>