Tuesday, May 31, 2011

Re: Accessing request.user in formset validation

On Tue, May 31, 2011 at 2:21 PM, Carsten Fuchs <carsten.fuchs@cafu.de> wrote:
> Hi all,
>
> in some of my forms and formsets I need access to request.user in form
> validation.
>
> With an individual form, I pass request.user as a parameter to the
> constructor, using code like this:
>
> class ErfasseZeitraumForm(forms.Form):
>    von    = forms.DateField(widget=AdminDateWidget())
>    bis    = forms.DateField(widget=AdminDateWidget())
>
>    def __init__(self, User, *args, **kwargs):
>        super(ErfasseZeitraumForm, self).__init__(*args, **kwargs)
>        self.User = User
>
>
> How can I achieve the same for entire formsets?
>
> I'm still quite new to Python, and I'm unsure what to override where to make
> the formset factory pass the request.user to all form constructors, or even
> if that is the "best" and canonical way to this?
>
> Thank you very much!
>
> Best regards,
> Carsten

You need to define a class which inherits from BaseFormSet class,
override the __init__ method to accept the user as an argument,
override the _construct_form() method to add the additional user
argument to the form kwargs.
Then, define a form class which accepts the user argument in its
__init__ method.
Finally, specify to Django to use these forms by passing them as the
form and formset arguments to formset_factory or modelformset_factory
- the same technique applies to both.

Eg for some LogEntry model:

from django.forms.models import ModelForm, BaseModelFormSet,\
modelformset_factory
from models import LogEntry

class LogEntryBaseFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(LogEntryBaseFormSet, self).__init__(*args, **kwargs)
def _construct_form(self, i, **kwargs):
kwargs['user'] = self.user
return super(LogEntryBaseFormSet, self)._construct_form(i, **kwargs)

class LogEntryForm(ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user')
super(LogEntryForm, self).__init__(*args, **kwargs)
def clean(self):
# use self.user
return self.cleaned_data

LogEntryFormSet = modelformset_factory(LogEntry, form=LogEntryForm,
formset=LogEntryBaseFormSet, extra=3, can_delete=True)


Cheers

Tom

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

No comments:

Post a Comment