Opened 14 years ago

Closed 14 years ago

#14940 closed (wontfix)

New generic class view CreateView execute form.save() with no arguments

Reported by: Mario César Owned by: nobody
Component: Generic views Version: 1.2
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Using the new django class views it's needed to override methods to extends functionality, this of course is awesome. django.views.generic.CreateView has been specially useful for me.

For my purpose I had a Model for Projects and a Form for this model, and I override the save method. However, there was no possibility to use the save method of my form, as CreateView extends from ModelFormMixin and this execute the method form.save() without arguments

I made a simple patch, to made this easy as it was when using old generic views.

Here it's the code working with my tiny patch.

class ProjectForm(ModelForm):
    
    class Meta:
        model = Project
        exclude = ('owner', 'members', 'followers', 'hosted', 'last_commit',
                    'last_release', 'related_projects')
        widgets = {
            'description': Textarea(attrs={'cols': 40, 'rows': 20}),
        }

    def save(self, owner, commit=True, *args, **kwargs):
        project = super(ProjectForm,self).save(commit=False,*args, **kwargs)
        project.owner = owner
        if commit:
            project.save()
        return project

class ProjectCreateView(CreateView):
    model = Project
    form_class = ProjectForm

    def form_valid(self, form):
        return super(ProjectCreateView, self).form_valid(form, owner=self.request.user)

Attachments (1)

use_arguments_on_save.diff (580 bytes ) - added by Mario César 14 years ago.

Download all attachments as: .zip

Change History (3)

by Mario César, 14 years ago

Attachment: use_arguments_on_save.diff added

comment:1 by Matt McClanahan, 14 years ago

I've found this sort of use case to work better by giving the form constructor additional arguments, rather than save(). It has the benefit of allowing your whole form object to know who the owner is (Often useful for validation) and FormMixin already has a get_form_kwargs method for passing additional arguments to a form's constructor.

comment:2 by Russell Keith-Magee, 14 years ago

Resolution: wontfix
Status: newclosed

@mattmcc - I agree; arguments like "owner" should be passed in to the form constructor, not the save method.

There are other arguments to form.save() -- commit being the most notable example. However, these tend to be behavior modifying, so I'd argue that in those cases, you'd need to override form_valid() anyway.

Closing wontfix, since there are better ways to skin this cat.

Note: See TracTickets for help on using tickets.
Back to Top