7

I'm new in Django ,and I'm trying to develop a simple Django application which takes two numbers from the user with a form and do some operation with those numbers and print the result with a Http Response. My code is the following:

forms.py

class SimpleForm(forms.ModelForm):

    a = forms.IntegerField(label='first' )
    b = forms.IntegerField(label='second' )

    def result(self):
        return doSomething(self.a, self.b)

views.py

class MainPage(FormView):
    template_name = 'simple.html'
    success_url = '/result/'
    form_class = SimpleForm

    def form_valid(self, form):
        return HttpResponse(form.result())

However, when I run this code on my localhost, it gives the error like

SimpleForm object has no attribute 'a'

So, what can be the problem? How can I get the user input in order to use it in my "result" function?

Thanks in advance...

2 Answers 2

10

To access data, you need to use form.data:

def result(self):
    return doSomething(self.data['a'], self.data['b'])

If you called form.is_valid() before call result, you can also use cleaned_data. (Because OP is using FormView.form_valid, it is called automatically)

def result(self):
    return doSomething(self.cleaned_data['a'], self.cleaned_data['b'])
Sign up to request clarification or add additional context in comments.

4 Comments

He call result() in form_valid(), so form.is_valid() was already call. Here it is preferable to only use cleaned_data to be sure about data verification, no?
@Wilfried, You're right. I missed that. I'll mention that. Thank you for your comment.
What is the difference between self.data and self.cleaned_data? I mean which one should I prefer?
@qwerty, self.data returns raw data (strings), while self.cleaned_data returns converted data according to field type (int for the given case).
1

You form.a is an IntergerField(), not the result. You need to read cleaned_data dict of your form to access value of your form field. Cleaned_data documentation

class SimpleForm(forms.ModelForm):

    a = forms.IntegerField(label='first' )
    b = forms.IntegerField(label='second' )

    def result(self):
        return doSomething(self.cleaned_data['a'], self.cleaned_data['b'])

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.