Reputation: 23
Im developing a social website I have problem in creating new post I don't know how set author name as default of logged in user it always give option for all the previously logged in users I want to make it default for the logged in user I don't know how to set default value for that author field
views.py
class CreatePostView(LoginRequiredMixin,CreateView):
login_url = '/login/'
redirect_field_name = 'blog/post_detail.html'
form_class = PostForm
model = Post
forms.py
class PostForm(forms.ModelForm):
class Meta():
model = Post
fields = ('author','title','text','Post_image')
widgets = {
'title':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea postcontent '})
}
modesls.py
class Post(models.Model):
author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
Post_image= models.ImageField(upload_to='media' ,blank=True ,editable=True)
created_date = models.DateTimeField(default=timezone.now())
published_date = models.DateTimeField(blank=True,null=True)
Upvotes: 1
Views: 537
Reputation: 546
you could try define get_initial.
def get_initial(self, *args, **kwargs):
initial = super(CreatePostView, self).get_initial(**kwargs)
initial['author'] = 'default author'
return initial
Upvotes: 1