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']
CodePudding user response:
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']
CodePudding user response:
You can also override the get_form_kwargs
method:
class ArticleCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'add_post.html'
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs.update({'initial': {'author': self.request.user}})
return kwargs
CodePudding user response:
Django forms allow you to set initial values, this is how you can pass in the current user in the view. You won't be able to do this directly in your forms.py file because it doesn't receive the request as an argument.
form = PostForm(initial={'author': self.request.user})
https://docs.djangoproject.com/en/4.0/ref/forms/api/#initial-form-values