insert form data into tables in django
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.
精彩评论