开发者

insert form data into tables in django

开发者 https://www.devze.com 2023-03-15 20:40 出处:网络
I am newbie in Django and wanted to know a very basic thing: I have a form which has some dropdown boxes and textfields and upon hitting the button on the form, I want the data to be inserted into da

I am newbie in Django and wanted to know a very basic thing:

I have a form which has some dropdown boxes and textfields and upon hitting the button on the form, I want the data to be inserted into database table. I have already开发者_StackOverflow中文版 created the table using model.py but dont know where the insert code would come.


The usual way to go about is to create a ModelForm if the data you are collecting is mapping to a model. You place the ModelForm in forms.py inside your app.

# 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 ....

Read more here:


Forms and ModelForms.

0

精彩评论

暂无评论...
验证码 换一张
取 消