0

我想在不刷新页面的情况下添加评论,但是当我提交表单时,我认为页面上的对象更改为评论对象而不是问题对象,因此它给了我一个

.NoReverseMatch:“question_detail”的反向参数“(”,)”未找到。尝试了 1 种模式:['question/(?P[-a-zA-Z0-9_]+)/$']错误

当我从页面中删除链接以查看会发生什么时,我得到一个

在 [{'True': True, 'False': False, 'None': None}, {}, {}, {'form': , 'view': <question.views. UserCommentForm 对象在 0x000001BF59A47310>}]

我的观点

class QuestionDetailView(DetailView):
    model = Question
    template_name = 'question/question_detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        comments = Comment.objects.filter(question=self.object)
        context['comments'] = comments
        context['form'] = CommentCreateForm
        return context

class UserCommentForm(LoginRequiredMixin, CreateView):
    template_name = 'question/question_detail.html'
    form_class = CommentCreateForm
    model = Comment

    def form_valid(self, form):
        form.instance.author = self.request.user
        # question = Question.objects.get(slug=self.kwargs.get('slug'))
        # form.instance.question = question

        result = form.cleaned_data.get('content')
        user = request.user.username
        return JsonResponse({'result':result, 'user':user})
        # return super().form_valid(form)

    def get_success_url(self):
        return reverse('question:question_detail', kwargs={'slug': self.object.question.slug})

class QuestionView(View):
    def get(self, request, *args, **kwargs):
        view = QuestionDetailView.as_view()
        return view(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        view = UserCommentForm.as_view()
        return view(request, *args, **kwargs)

我的网址

urlpatterns = [
    # All Questions
    path('', views.QuestionListView.as_view(), name='question_list'),
    # Search Page
    path('search/', views.question_search, name='question_search'),
    # Comment 
    path('<slug:slug>/add_comment/', views.UserCommentForm.as_view(), name='add_comment'),
    # Create / Update / Delete / Detail 
    path('create/', views.QuestionCreateView.as_view(), name='question_create'),
    path('<slug:slug>/', views.QuestionView.as_view(), name='question_detail'),
    path('update/<slug:slug>/', views.QuestionUpdateView.as_view(), name='question_update'),
    path('delete/<slug:slug>/', views.QuestionDeleteView.as_view(), name='question_delete'),
    # Category / User Questions
    path('user/<slug:slug>/', views.UserQuestionDetailView.as_view(), name='user_question_list'),
    path('category/<slug:slug>/', views.CategoryQuestionDetailView.as_view(), name='category_question_list'),
    ]

我的表格

class CommentCreateForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['content', 'question', 'parent']
        labels ={'content':'','parent':''}

    def __init__(self, *args, **kwargs):
        super().__init__(*args,**kwargs)

        self.fields['content'].widget.attrs.update({'placeholder':'Type Comment here', 'class':'text'})
        self.fields['parent'].widget.attrs.update({'class':'d-none'})

我的模板

                <form id="commentform" data-question="{{object.slug}}" class="commentform" method="post">
                    <legend class="border-bottom fw-bold">Add a Comment</legend>
                    {% csrf_token %}

                    <select name="question" id="id_question" class="d-none">
                        <option value="{{object.id}}" selected="{{object.id}}"></option>
                    </select>

                    <label>{{form.parent.label}}</label>
                    {{form.parent}}

                    {{form.content}}
                    <button type="submit" value="commentform" id="newcomment" class="newcomment btn btn-primary col-12 mt-1">Post</button>
                </form>
script>
    $(document).on('click', '#newcomment',' #newcommentinner', function(e){
    e.preventDefault();

    let button = $(this).attr("value");
    let slug = $('#commentform').attr("data-question") 
    let csrftoken = $('[name="csrfmiddlewaretoken"]').val();
    let patch = "{% url 'question:add_comment' 0 %}".replace(0, slug)
    console.log($("#commentform").serialize())

    $.ajax({
        type:'POST',
        url:patch, 
        data:{
            'data': $("#" + button).serialize(),
            'csrfmiddlewaretoken': csrftoken,
        },
        cache:false,
        success: function(json) {
            console.log(json)
        },
        error: function(xhr, errmsg, err){
        }
    })
});
</script>
4

0 回答 0