views:

30

answers:

1

How do i pre-populate the exclude fields in a ModelFormSet. AuthorFormSet below doesn't take an instance argument here, only queryset. So how do i force the empty forms coming in not to have a NULL/None user attribute. I want to be able to set that user field to request.user

models.py

class Author(models.Model):
    user = models.ForeignKey(User, related_name='author')
    # assume some other fields here, but not relevant to the discussion.

forms.py

 class AuthorForm(forms.ModelForm):
     class Meta:
         model = Author

 class BaseAuthorFormSet(BaseModelFormSet):
     """will do some clean() here"""
     pass

 AuthorFormSet = modelformset_factory(Author,\
                                    form=AuthorForm, \
                                    formset=BaseAuthorFormSet, extra=1,\
                                    exclude=('user',)
                                    )

views.py

def my_view(request):
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST)
        if form.is_valid(): 
            form.save() # This will cause problems
                        # for the empty form i added,
                       # since user can't  be null.

EDIT

This is what i ended up doing in my view. Wogan's answer is partly correct, i think it's just missing the iterating over all the forms part.

for form in formset.forms: 
    form.instance.user = request.user
formset.save()
+1  A: 

You can exclude fields in the model form, these will then be excluded from the formset created by modelformset_factory.

class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        exclude = ('user',)

In your view, pass commit=False to the form's save() method, then set the user field manually:

def my_view(request):
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST)
        if formset.is_valid(): 
            for author in formset.save(commit=False):
                author.user = request.user
                author.save()
            formset.save_m2m() # if your model has many to many relationships you need to call this
Wogan