首页 > 解决方案 > 在按钮单击时使 Django 函数在 HTML 上工作

问题描述

我正在尝试调用一个视图,以便它显示在我已经存在的页面上的 div 中,而不是链接到新页面以发表评论。到目前为止,我已经能够调出在单击按钮后显示并在再次按下时隐藏的 div。理想情况下,当它显示评论表单时,此时它应该只显示提交按钮。我想知道如何让这个表单像在其他 HTML 页面上一样显示在这个 div 中。如果还有更多需要的信息让我知道,只是不想给太多看。

视图.py:

class AddCommentView(CreateView):
model = Comment
form_class = CommentForm
template_name = 'storysharing/comment.html'

def form_valid(self, form):
    form.instance.story_id = self.kwargs['pk']
    return super().form_valid(form)

def get_success_url(self):
    return reverse('storysharing:story_details', kwargs={'story_id':self.kwargs['pk']})

网址.py:

app_name = 'storysharing'
urlpatterns = [
path('', views.index, name = 'index'),
path('<int:story_id>/', views.story_details, name = 'story_details'),
path('add_story/', views.add_story, name = 'add_story'),
path('thanks/', views.story_added, name = 'story_added'),
path('final_post/<int:pk>', UpdateStoryView.as_view(), name = 'final_post'),
path('review/', views.review, name = 'review'),
path('get_location/', views.get_location, name = 'get_location'),
path('<int:pk>/comment', AddCommentView.as_view(), name = 'comment'),
]

page.html,标签是链接通常链接到其他页面的地方,并在输入所需信息后成功添加评论。下面是“显示 div”按钮,我尝试制作的 div 包含与标签中所示相同的表单:

<a href="{% url 'storysharing:comment' story.id %}">Add Comment<a/>

                    <button type="button" name="answer" onclick="showDiv('toggle')">Add 
Comment</button>

<div id="toggle" style="display:none" class="comments">
<form action={% url 'storysharing:comment' story.id %} method ="POST">
{%csrf_token%}
{{form.as_p}}
<button>Submit</button>
</div>

有效的html页面图片:

在此处输入图像描述

页面上显示的图片:

在此处输入图像描述

另一方面,有没有办法删除 div 周围的线?任何进一步的信息可应要求提供,在此先感谢!

标签: pythonhtmlcssdjangodjango-views

解决方案


您可以利用 ajax 在客户端和服务器之间发送请求,而无需重新加载网页。看看下面这个一般例子:

模板.html

<!-- we will use js to send a post request when this button is clicked -->
<button id="my-button">Submit</button>

脚本.js


// using jquery, we will set the function that executes when the button is clicked
$('#my-button').click(function() {

  // launch an ajax request:
  $.ajax({
    type : 'POST',
    url : '<the-url>',
    data : {
      someKey : 'someValue'
    },
    success : function(response) {
      
      // this function executes when we receive a succesful response from the backend

      // unpack the response:
      result = response.result;

      // update html page:
      ...
 
   }
  }
});

视图.py

def my_view_function(request):

    """ this function executes when the ajax request is sent """

    # unpack the request
    some_value = request.POST.get('someKey')

    # do some logic:
    ...
  
    # pack the response:
    response = {
        "result" : "some result"
    }

    return JsonResponse(response)

使用此模式,您可以创建无需用户刷新即可自行更新的动态页面。


推荐阅读