简体   繁体   中英

Django form has no attribute 'cleaned_data'

This is the code I have, and when I run it on Django, I am met with this error: 'Title' object has no attribute cleaned_data

def new(request):
    
    form = Title(request.POST)
    if request.method == "POST":
        if form.is_valid:
           title = form.cleaned_data["title"]
           text = form.cleaned_data["text"]
           util.save_entry(title, text)
        else:
            return render(request, "encyclopedia/error.html",{
                "form":NewForm()
            })
        return redirect(reverse('page', args = [title]))
    
    return render(request, "encyclopedia/newpage.html",{
        "form1":Title(),
        "form": NewForm()
    }) 

You are probably getting the exception thrown in your return statement where you are instantiating a new Title object. This object only gets the cleaned_data attribute when is_valid method has been called upon. Hence you haven't called this on the new Title object and that is the reason why you are getting the error.

you use form = Title(request.POST) , but the line after you check whether the request.method equals POST or not. i think yo should move that line inside the if statement

is_valid() it's a function

def new(request):
    form = Title(request.POST)
    if request.method == "POST":
        if form.is_valid():
            title = form.cleaned_data["title"]
            text = form.cleaned_data["text"]
            util.save_entry(title, text)
       
        else:
            return render(request, "encyclopedia/error.html",{
            "form":NewForm()
        })
    return redirect(reverse('page', args = [title]))

return render(request, "encyclopedia/newpage.html",{
    "form1":Title(),
    "form": NewForm()
}) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM