将表单数据插入django中的表

Com*_*er7 2 django

我是Django的新手,想知道一个非常基本的东西:

我有一个表格,其中包含一些下拉框和文本字段,在点击表单上的按钮时,我希望将数据插入到数据库表中.我已经使用model.py创建了表,但不知道插入代码的来源.

esp*_*akk 6

通常的方法是,如果要收集的数据映射到模型,则创建ModelForm.您将ModelForm放在应用程序内的forms.py中.

# forms.py
from django import forms
from someapp.models import SomeModel

class SomeForm(forms.ModelForm):
    class Meta:
        model=SomeModel


# views.py
from someapp.forms import SomeForm
def create_foo(request):

    if request.method == 'POST':
        form = SomeForm(request.POST)
        if form.is_valid():
             # form.save() saves the model to the database
             # form.save does only work on modelforms, not on regular forms
             form.save()

    ..... return some http response and stuff here ....
Run Code Online (Sandbox Code Playgroud)

在这里阅读更多 :