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 ?

2
  • 1
    You need to pass request explicitly in init, which is not done by model admin. Commented Nov 4, 2013 at 9: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 Commented Nov 4, 2013 at 9:52

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Looked at the docs, the save_model method solved all my problems. Many thanks
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

2 Comments

Um. AirplaneEditForm(request=request) uses the value of request (if any) at the moment of class definition.
I think you are right @tzot. Perhaps I'll just delete my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.