user2919162
user2919162

Reputation: 69

Django. 'request' object is None in ModelForm

I want to override the bahaviour of saveas button - i need after pushing it to redirecrt me not in list of objects, but in a new object directly.

So i need to override the standart save method of ModelForm and get in there the request object - to check if saveas button was pressed:

*admin.py
class AirplanesAdmin(admin.ModelAdmin):
    form = AirplaneEditForm


forms.py
class AirplaneEditForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    super(AirplaneEditForm, self).__init__(*args, **kwargs)

def clean(self):
    print self.request
    return self.cleaned_data

def save(self, force_insert=False, force_update=False, commit=True,):
    plane = super(AirplaneEditForm, self).save(commit=False)

    print self.request

    if commit:
        plane.save()

    return plane

class Meta:
    model = Airplanes

But in both prints request is None... Did I do something wrong ?

Upvotes: 0

Views: 1681

Answers (2)

Anupam
Anupam

Reputation: 15610

Request object is not being passed to forms.py from admin.py

So, in admin.py:

class AirplanesAdmin(admin.ModelAdmin):
    form = AirplaneEditForm(request=request)

See another example here

Upvotes: 0

uranusjr
uranusjr

Reputation: 1459

Django forms are something between models and views, which means they are context-agnostic. You generally should not do things that depend on request objects inside your form.

What @Rohan means is that AirplanesAdmin does not pass in request objects when your form is initialized, so when you kwargs.pop('request', None) the is actually an internal KeyError and the default value (the second argument, None) is returned. Nothing is really popped from kwargs. To override this behavior, you will need to override rendering methods of ModelAdmin.

Read the doc for methods you can use.

Upvotes: 2

Related Questions