Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: "Form object has no attribute..." error

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

like image 203
Enes Altuncu Avatar asked Jul 25 '26 15:07

Enes Altuncu


2 Answers

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'])
like image 114
falsetru Avatar answered Jul 27 '26 04:07

falsetru


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'])
like image 28
Wilfried Avatar answered Jul 27 '26 05:07

Wilfried



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!