2

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 created the table using model.py but dont know where the insert code would come.

2 Answers 2

6

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:

Sign up to request clarification or add additional context in comments.

Comments

2

Forms and ModelForms.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.