Search code examples
djangodjango-formsuser-input

How shall I make this form automatically identify the user who is logged in as author


class ArticleCreateView(CreateView):
   model=Post
   form_class=PostForm
   template_name='add_post.html'


from operator import mod
from turtle import title
from django import forms
from .models import Post

class PostForm(forms.ModelForm):
    class Meta:
        model=Post
        fields=['title','body','author','category']

Solution

  • You can override the form_valid method of your CreateView. You probably don't want to include author in the form.

    class ArticleCreateView(CreateView):
       model = Post
       form_class = PostForm
       template_name = 'add_post.html'
    
       def form_valid(self, form):
            form.instance.author = self.request.user
            return super().form_valid(form)
    
    
    class PostForm(forms.ModelForm):
        class Meta:
            model = Post
            fields = ['title', 'body', 'category']