Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User current user on new Django class views forms

I am using the django 1.3 on trunk, and start learning about class views.

I had this:

class Project(models.Model):
    title = models.CharField(max_length=90)
    slug = models.CharField(max_length=90)
    description = models.TextField()
    owner = models.ForeignKey(User)

class ProjectForm(ModelForm):

    class Meta:
        model = Project
        exclude = ('owner',)
        widgets = {
            'description': Textarea(attrs={'cols': 40, 'rows': 20}),
        }

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

    def get(self, request, *args, **kwargs):
        return super(ProjectCreateView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return super(ProjectCreateView, self).post(request, *args, **kwargs)

I am trying, to get a form using model forms from django excluding the owner field, to get the field value after with the request.user property.

The form as it is, works. But how can make sure the ModelForm use request.user for the Project.owner field?

My first guess, was to override get_form_kwargs method from the view

class ProjectCreateView(CreateView):

    # .....

    def get_form_kwargs(self, **kwargs):
        self.initial['owner': self.request.user})
        kwargs = super(ProjectCreateView, self).get_form_kwargs(**kwargs)
        return kwargs

But seem to have no effect on the data used by the model form

like image 371
Mario César Avatar asked Dec 22 '10 18:12

Mario César


1 Answers

get_form_kwargs is supposed to return a dict of arguments for your form - you set self.initial, but you didn't attach it to kwargs:

def get_form_kwargs(self, **kwargs):
    kwargs = super(ProjectCreateView, self).get_form_kwargs(**kwargs)
    kwargs['initial']['owner'] = self.request.user
    return kwargs
like image 57
girasquid Avatar answered Sep 30 '22 08:09

girasquid