4

如何将数据添加到我的数据库?

我的表格:

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']

如何将我的数据保存到数据库中?

4

2 回答 2

5

我认为对您来说更好的选择是使用 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,)
于 2012-09-19T07:14:10.993 回答
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()
于 2012-09-19T11:18:15.933 回答