I'm trying to get the user from the request in Django Admin. What I need is access to the request's user in the inline form's clean()
method. I've done a procedure similar to the one described below with a normal ModelForm
(i.e. not an inline one) and I was successful. However, with inlines I'm having a lot of issues.
I have:
class SaleFormset(BaseInlineFormSet):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(SaleFormset, self).__init__(*args, **kwargs)
def _construct_form(self, i, **kwargs):
kwargs['request'] = self.request
super(SaleFormset, self)._construct_form(i, **kwargs)
class SaleProductItemInlineForm(ModelForm):
"""
Custom form for the Sale Product Item Inline used by the
Sale Admin form.
"""
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(SaleProductItemInlineForm, self).__init__(*args, **kwargs)
class Meta:
model = SaleProductItem
fields = "__all__"
And in the admin.py, I have:
class SaleProductItemInline(admin.TabularInline):
"""
Tabular inline for a SaleProductItem used in the Sale Admin.
"""
model = models.SaleProductItem
form = SaleProductItemInlineForm
formset = SaleFormset
def get_formset(self, request, obj=None, **kwargs):
formset_class = super(SaleProductItemInline, self).get_formset(request, obj, **kwargs)
class Subset(formset_class):
def __new__(cls, *args, **kwargs):
kwargs['request'] = request
return formset_class(*args, **kwargs)
return Subset
However, I'm getting an error saying that 'NoneType' object has no attribute 'media'
because of this section:
@property
def media(self):
# All the forms on a FormSet are the same, so you only need to
# interrogate the first form for media.
if self.forms:
return self.forms[0].media
add_view()
would you be able to access theobject_id
to pass tochange_view()
– Wearing