Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't save a form in Django (object has no attribute 'save')

The following is my form:

class AdvancedSearchForm(forms.Form):
    valueofres = forms.ChoiceField (label="res", choices = ((0, 0),(2.2, 2.2)), required= False)

The following is my view:

def advancedsearch(request):
    if request.method == "POST":
        search = AdvancedSearchForm(request.POST, request.FILES)
        if search.is_valid():
            new_search = search.save(commit=False)

Why I'm getting the error 'AdvancedSearchForm' object has no attribute 'save'?

like image 691
user1328021 Avatar asked May 08 '13 14:05

user1328021


2 Answers

save is available only for ModelForm by default, and not for forms.Form

What you need to do is this. Either use:

class AdvancedSearchForm(forms.ModelForm):
    valueofres = forms.ChoiceField (label="res", choices = ((0, 0),(2.2, 2.2)), required= False)
    class Meta:
        model=Search #or whatever object

Or:

def advancedsearch(request):
    if request.method == "POST":
        search_form = AdvancedSearchForm(request.POST, request.FILES)
        if search_form.is_valid():
            cd = search_form.cleaned_data
            search = #populate SearchObject()
            search.save()
like image 120
karthikr Avatar answered Sep 21 '22 13:09

karthikr


Forms don't have a save() method.

You need to use a ModelForm (docs) as that will then have a model associated with it and will know what to save where.

Alternatively you can keep your forms.Form but you'll want to then extract the valid data from the for and do as you will with eh data.

if request.method == "POST":
    search_form = AdvancedSearchForm(request.POST, request.FILES)
    if search_form.is_valid():
        cd = search_form.cleaned_data

        search = Search(
            # Apply form data
        )
        search.save()
like image 21
rockingskier Avatar answered Sep 19 '22 13:09

rockingskier