2012-09-19 56 views
3

如何將數據添加到我的數據庫?如何將數據添加到數據庫?

我的形式:

from django import forms 

class DinnerForm(forms.Form): 
    name = forms.CharField(max_length=100) 
    text = forms.CharField(max_length=255) 

和型號:

class Dinner(models.Model): 
    name = models.CharField(max_length=100) 
    text = models.CharField(max_length=255) 

我的觀點:

def add_dinner(request): 
    if request.method == 'POST': 
     form = DinnerForm(request.POST) 
     if form.is_valid(): 
      name = form.cleaned_data['name'] 
      text = form.cleaned_data['text'] 

如何將我的數據保存到數據庫?

回答

3

我認爲更好的選擇是使用FormModels。要添加的東西到數據庫:

### example 
def add_dinner(request): 
    if request.method == 'POST': 
     form = DinnerForm(request.POST) 
     if form.is_valid(): 
      name = form.cleaned_data['name'] 
      text = form.cleaned_data['text'] 
      diner = Dinner.objects.create(
          name = name, 
          text = text,) 
+0

使用FormModel並不需要明確地創建對象,它可以通過完成只是'form.save()' –

0

,如果你不使用的ModelForm,只要你能做到某事像這樣:

def add_dinner(request): 
    if request.method == 'POST': 
     form = DinnerForm(request.POST) 
     if form.is_valid(): 
      name = form.cleaned_data['name'] 
      text = form.cleaned_data['text'] 
      query = Dinner(name = name , text = text) 
      query.save()