Home > Software engineering >  Auto populated form fields django
Auto populated form fields django

Time:04-21

I am working on my blog application and I added comment section now I want to auto populate two fields in forms.But i am getting error NOT NULL constraint failed: MainSite_comment.user_id.
Models.py

class Comment(models.Model):
    comment_text = models.TextField(("comment_text"))
    user = models.ForeignKey("account.User", related_name=("comment_user"), on_delete=models.CASCADE)
    #post = models.ForeignKey("Post", related_name=("comment_post"), on_delete=models.CASCADE)
    parent = models.ForeignKey('self',related_name=("replies"), on_delete = models.CASCADE , blank= True ,null=True)
    timestamp = models.DateTimeField(("Comment Timestamp"), auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.user.username

Forms.py

class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields =['comment_text']

        labels ={
            'comment_text':'',
        }

        widgets ={
            'comment_text': forms.Textarea(attrs = {'class':'form-control','rows':'5','cols':'50',
                'style' : 'background: #fff;',
                'placeholder':'Write a comment....'}),
            
        }

Views.py

class PostDetailView(FormMixin,DetailView):
    model = Post
    form_class = CommentForm
    template_name = 'MainSite/blogpost.html'
    
    def form_valid(self, form):
        form.instance.user_id = self.request.user.id
        return super().form_valid(form)

    def post(self,request,slug):
        print(request.user.id)
        if request.method == 'POST':
            form = CommentForm(request.POST)
            if form.is_valid():
                form.save()
                messages.success(request,"Comment added successfully")

    success_url = reverse_lazy('home')

I want auto populate both user and post field(I will change the post field in model later).I get error while auto populating user field in model.Currently I using slug in urls to show post.I dont know how this form_valid() works and what does it returns and what is this instance is.

Thanks for help and any advice is helpful.

CodePudding user response:

You should call the form_valid method, otherwise setting the user there makes no sense, so:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy

class PostDetailView(LoginRequiredMixin, FormMixin, DetailView):
    model = Post
    form_class = CommentForm
    template_name = 'MainSite/blogpost.html'
    success_url = reverse_lazy('home')
    
    def form_valid(self, form):
        form.instance.user_id = self.request.user.id
        form.save()
        messages.success(self.request, 'Comment added successfully')
        return super().form_valid(form)

    def post(self, request, slug):
        form = self.get_form()
        self.object = self.get_object()
        if form.is_valid():
            self.form_valid(form)
        else:
            self.form_invalid(form)
  • Related