Bora
Bora

Reputation: 1858

How to access a ModelForm's fields in Django view

I would like to enter the fields' values after my ModelForm instance is posted. I have three forms and every step one form is posted. I would like to make a logging system to save data to database until the user saves finishes all three forms. One of the forms is a ModelForm.

In my forms.py file:

class StepOne(forms.ModelForm):
    class Meta:
        model = Article
        fields = ['name', 'difficulty', 'content']

I would like to access the form's field values after it has been posted in my view class, like this:

class MyView(views.View):
    def post(self, request):
        form = StepOne(request.POST)
        content = form.content
        difficulty = form.difficulty
        ....

Is there such thing possible?

Upvotes: 2

Views: 2357

Answers (1)

Shang Wang
Shang Wang

Reputation: 25539

You need to call form.is_valid() in order to access the form data:

form = StepOne(request.POST)
if form.is_valid():
    content = form.cleaned_data['content']
    difficulty = form.cleaned_data['difficulty']

django doc.

Upvotes: 6

Related Questions