Search code examples
python-3.xdjangoattributeerror

when i click on submit forms then i got this error


I am getting attribute error in Django in forms, I got stuck after this please help me with this one

my views.py file

tasks=['sleep','drink','code']
class newforms(forms.Form):
    task=forms.CharField(label='new_task',max_length=100)

 
def add(request):
    if request.method=='POST':
        form=newforms(request.method)
        if form.is_valid():
            task=form.cleaned_data['task']
            tasks.append(task)
        else:
            return render(request,'add.html',{
            'form':form
            })

    return render(request,'add.html',{
    'form':newforms()

    })

and the error shows

attribute error


Solution

  • You should pass request.POST as data to the form (or request.GET, or another dictionary-like object), and not request.method:

    def add(request):
        if request.method == 'POST':
            form = newforms(request.POST, request.FILES)
            if form.is_valid():
                task = form.cleaned_data['task']
                tasks.append(task)
        else:
            form = newforms()
        return render(request,'add.html',{'form': form})

    That being said, using a list is not a good idea. You here introduce global state. This makes the program unpredictable, but furthermore it also means the data is not persistent when you restart the server. If you later use multiple workers, it would mean that one worker has another state than another worker.