Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
88 views
in Technique[技术] by (71.8m points)

python - My view doesn't save the instance from Form in Djagno

I'm trying make a comment section for my Q&A project.I made the model for comment , the form part in question_detail.html an , also the QuestionCommentForm() in form.py .

model.py

class QuestionComment(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    question = 
    models.ForeignKey(Question,on_delete=models.CASCADE)
    created_date = models.DateTimeField(auto_now_add= True)
    body = models.CharField(max_length=200, null= True , 
    blank = True, default ='')
    def __str__(self):
    return str(self.body)

forms.py

          {%if c_form%}
    <form method="POST" action= "{% usl 'blog:question-commet' question.id  >{% csrf_token %}
    {{c_form.media}}
    {{ c_form.as_p}}
      <button type = "submit" , name = "question_id", value = "{{question.pk}}", class ="btn btn-secondary btn-sm">submit comment</button>

views.py

@api_view(['POST','GET'])
def question_comment(request, *args, **kwargs):
    form = QuestionCommentForm()
     print('finction comment started'*20)
     if request.method == 'POST':
        c_form = QuestionCommentForm(request.POST)
        if c_form.is_valid():        
            new_comment = c_form.save(commit=False)
            new_comment.refresh_from_db()
            c_form.instance.user = request.user
            question = Question.objects.get(id = request.POST.get('question_id')

            new_comment.question = question
            new_comment.bldy =c_form.cleaned_data.get('body')
            new_comment.save()
    context['c_form'] = c_form
    return render(request, 'blog/question_detail.html',context)

class QuestionDetail(DetailView):
    template_name = 'blog/question_detail.html'
    model = Question
    context_object_name = 'question'
    count_hit = True
    def get_queryset(self):
        return Question.objects.filter(id = self.kwargs['pk'])

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        c_form = QuestionCommentForm()
        context = super(QuestionDetail,self).get_context_data(**kwargs)
        self.obj= get_object_or_404(Question, id = self.kwargs['pk'])
        self.object.save()
        self.object.refresh_from_db()
        answers = Answer.objects.filter (question_id = self.obj.id).order_by('-created_date')
        liked =self.obj.like.filter(id =self.request.user.id).exists()
        print('liked in class question not checked still' *10)
        comments= QuestionComment.objects.filter(question = self.kwargs['pk'])
        context['comments']= comments
        context["answers"]=answers
        context["liked "] = liked
        context['c_form'] = c_form
        return context

    def post(request, *args, **kwargs):
        print('post started'*100)
        c_form = QuestionCommentForm()
        c_form = QuestionCommentForm(request.POST)
        if c_form.is_valid():        
            new_comment = c_form.save(commit=False)
            new_comment.refresh_from_db()
            new_comment.user = request.user
            new_comment.question = c_form.cleaned_data.get('question_id')
            new_comment.bldy =c_form.cleaned_data.get('body')
            new_comment.save()
            context['c_form'] = c_form
        else:
            c_form= QuestionCommentForm()
        return render(request, 'blog/question_detail.html',context)
    

url.py

...
path('question-comment/<int:pk>/', question_comment, name = 'question-comment'),

]

in my view, first I tried to use a another function to handle the comment, got no result and made a def post() in the class QuestionDetial() , and still the form shows up but when I type something and hit the button , it refresh the page and nothing saves . I have already saved a comment using admin and it appears in the question-detail page. used print to find the bug, but it seems the post() in class and the question_comment() not being recall. searched a lot but no answer. (BTW I get no error except the NoReverseMatch that I fixed)

question from:https://stackoverflow.com/questions/65540756/my-view-doesnt-save-the-instance-from-form-in-djagno

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You never save the model object (not by the form, nor by the view). Furthermore the name of the method is 'POST', not 'Post':

@api_view(['POST','GET'])
def question_comment(request, *args, **kwargs):
    form = QuestionCommentForm()
    print('finction comment started'*20)
    if request.method == 'POST':
        c_form = QuestionCommentForm(request.POST)
        if c_form.is_valid():        
            c_form.instance.user = request.user
            c_form.save()
    context = {'c_form': c_form }
    return render(request, 'blog/question_detail.html',context)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...