Reputation: 609
I'm having a bit of trouble finding an answer on this:
Using Django forms, what's the proper way to provide the current/requesting user?
My form looks like this:
class NewProjectForm(forms.Form):
project_name = forms.CharField(max_length=100)
def save(self):
project = Project(name=self.cleaned_data[project_name])
project.status = 'Working'
#TODO project.created_by = ???
project.save()
return project
Do I need to pass a second argument of user into the save function and I get that from the request or?
Upvotes: 0
Views: 106
Reputation: 15526
Yes, you do. However, you could probably save yourself some time by turning your form into a ModelForm
and then handling the model save in your view:
class NewProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['name',]
And then in your view:
if form.is_valid():
new_project = form.save(commit=False)
new_project.created_by = request.user
new_project.save()
That way you don't have to worry about passing around your user
object, and the form itself will take care of setting the other properties for you (for project.status
, you might try a default
argument in your field definition).
Upvotes: 3