[Answer]-Django, best practice for associating model with author and how to do it

1๐Ÿ‘

I think the best place to associate a user with some model data is in the views.

In your specific example, you can use a model form for blog.

class BlogForm(forms.ModelForm):
    class Meta:
        fields = ['title', 'last_edited_by']

Do not include author in the form if you do not want to do any validation based on value of author. In case you have to do any validation based on author you will have the include it the form fields and also add the author id value in the form post data.

Now in your view you can use this BlogForm for creating a blog instance with:

....
form = BlogForm(data)
if form.is_valid():
    blog = form.save(commit=False)
    blog.author = request.user
    blog.save()
....

Now you have a blog with author.
Even if you really want to override the save method you can pass the author to the save method of Blog and associate it in the save method.

If you choose to include author in the form fields, to add the value of author in the post data you will have to make copy of the post data and then insert the value of author in the copied post data.

๐Ÿ‘คzaphod100.10

Leave a comment