How can I get current user in my ModelForm, using inlineformset?

1,270 views
Skip to first unread message

Fellipe Henrique

unread,
Oct 15, 2015, 3:05:24 PM10/15/15
to Django Users
Hello,

I have my ModelForm... and I need to filter my products with Current User..  if a change my modelform init, doesn't show me any error, but when I use in my inlineformset, show me on error..

Here is my code:

View:

ofertasinlineformset = inlineformset_factory(Assinatura, Ofertas,
form=OfertasEditForm(usuario=request.user),
max_num=ass_ativa.total_produtos_oferta,
# min_num=ass_ativa.total_produtos_oferta,
extra=ass_ativa.total_produtos_oferta,
exclude=(),
can_delete=False)

Form:
class OfertasEditForm(ModelForm):
class Meta:
model = Ofertas
exclude = []

def __init__(self, *args, **kwargs):
u = kwargs.pop('usuario', None)
super(OfertasEditForm, self).__init__(*args, **kwargs)
self.fields['produto'].queryset = Produto.objects.filter(usuario_id=u).filter(status='A')

and the error:
'OfertasEditForm' object has no attribute '__name__'

It's appears, when I use in my inlineformset only OfertasEditForm, work fine, because returns the class.. but when I use OfertasEditForm(usuario=reqquest.user)  returns the HTML not the class.

How can I do these? What's the better approach?

Regards 


T.·.F.·.A.·.     S+F
Fellipe Henrique P. Soares

e-mail: > echo "lkrrovknFmsgor4ius" | perl -pe \ 's/(.)/chr(ord($1)-2*3)/ge'
Twitter: @fh_bash

Mark Steadman

unread,
Oct 19, 2015, 6:18:55 PM10/19/15
to Django users
I think the answer you need is available through the docs, at https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#changing-the-queryset (I point to that because it does a much better job of explaining the answer than I can).

You're passing in an object - an instantiated form - into the inlineformset_factory function, when what I think it wants is a class, hence why you're getting the attribute error, because __name__ is a property of a class, not the object instantiated from that class.

You need to a little work to dynamically generate a FormSet class, via a custom factory function that can accept a user argument. It's that argument that you then pass to the FormSet's __init__ function. And again, I'm tying myself in knots.

Take a look at the docs above, and shout if it's still unclear, as I can probably give you an example if you're still stuck (as it's possibly one of those things that's easier to show rather than tell).
Reply all
Reply to author
Forward
0 new messages