darkpool
darkpool

Reputation: 14651

Setting current user for required model field

I have a model where one of the required fields is the currently signed in user. I do the following when creating a new record for the model:

views.py

def post(self, request):
    bound_form = self.form_class(request.POST)
    if bound_form.is_valid():
        new_position = bound_form.save()

The problem is that this only works when the user has selected them self on the form. I need a way to set the current user automatically and simply don't display the user field on the form. I have tried this:

def post(self, request):
    bound_form = self.form_class(request.POST)
    if bound_form.is_valid():
        new_position = bound_form.save(commit=False)
        new_position.user = request.user
        new_position.save()

However this does not work because the bound_form is not valid because it is missing a user which is a required field on the model. Where else can the user be set before trying to save the form? In the template, or the get method of the view?

Upvotes: 0

Views: 34

Answers (1)

trantu
trantu

Reputation: 1089

You should use exclude=('user',) in class Meta: of your form. @Daniel Roseman is also right.

Upvotes: 2

Related Questions