0

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 ?

user2919162
  • 69
  • 10
  • 1
    You need to pass `request` explicitly in init, which is not done by model admin. – Rohan Nov 04 '13 at 09:47
  • can you write a code example please ? I try to do that, but Django tolds me, that he don't know the **request** object in admin.py – user2919162 Nov 04 '13 at 09:52

2 Answers2

2

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.

uranusjr
  • 1,380
  • 12
  • 36
0

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

Anupam
  • 14,950
  • 19
  • 67
  • 94
  • Um. `AirplaneEditForm(request=request)` uses the value of `request` (if any) at the moment of _class definition_. – tzot Nov 16 '17 at 11:48
  • I think you are right @tzot. Perhaps I'll just delete my answer – Anupam Nov 17 '17 at 07:10