开发者

Django Forms - Proper way to validate user?

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?


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜