Thursday, January 31, 2013

Re: Can I set a "global" variable after user login, to use in my view?

On Tue, Jan 22, 2013 at 8:01 PM, Fellipe Henrique <fellipeh@gmail.com> wrote:
> The problem is, I need to pass this request.user to one form, using a
> inlineformset_factory..in these code:
>
> class PedidoItensForm(ModelForm):
> class Meta:
> model = ItensPedido
>
> def __init__(self, *args, **kwargs):
> profile = kwargs.pop('vUserProfile', None)
> super(PedidoItensForm, self).__init__(*args, **kwargs)
> self.fields["idproduto"].queryset =
> Produto.objects.filter(idempresa=profile.idempresa)
>
> I need to pass UserProfile to my form, to get works my filter.
>
> If I use inlineformset_factory, how can I pass the vUserProfile ?
>

You need to define a new base formset and form classes that take the
additional arguments when constructing form/formset, and to supply
them when the formset creates the forms, and supply these classes as
arguments to inlineformset_factory.

Eg, to accept an argument of 'profile' on each form:

from django.form.models import BaseInlineFormSet

class MyForm(Form):
def __init__(self, *args, **kwargs):
self.profile = kwargs.pop('profile')

class MyFormBaseFormSet(BaseInlineFormSet):
def __init__(self, profile=None, *args, **kwargs):
self.profile = profile
def _construct_form(self, i, **kwargs):
kwargs['profile'] = self.profile
return super(MyFormBaseFormSet, self)._construct_form(i, **kwargs)

MyFormSet = inlineformset_factory(MyModel, form=MyForm,
formset=MyFormBaseFormSet)

Cheers

Tom

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment