简体   繁体   English

如何在提交表单后显示 div 或 html 元素并从 Django 中的视图中检索一些信息

[英]How can I show a div or html element after submitting a form and retrieve some information from a view in Django

Currently when the user introduces a string in an input field and clicks the submit button, this invokes a view that returns through return render(request, 'index.html', context) a context that it basically contains data that is displayed in a table.当前,当用户在输入字段中引入字符串并单击提交按钮时,这会调用一个视图,该视图通过return render(request, 'index.html', context)一个上下文,它基本上包含显示在表格中的数据.

I would like said table to be visible only after submitting the form and not before and that when it is visible it shows the information obtained from the view.我希望该表仅在提交表单后才可见,而不是之前可见,并且当它可见时,它会显示从视图中获得的信息。

The problem is that if through inline styling I make this table not visible, for example in the following way:问题是,如果通过内联样式使该表不可见,例如通过以下方式:

<div class="row" id="searchVariantTable" style="display: none;">
    <!-- SOME TABLE HERE-->
</div>

And then I use the onsubmit event for form or onclick for button, it doesn't work.然后我将onsubmit事件用于表单或onclick用于按钮,它不起作用。 (It works partially, I can see the tbody but thead is missing, so basically I can't display the retrieved data from the database). (它部分工作,我可以看到tbody但缺少thead ,所以基本上我无法显示从数据库中检索到的数据)。

Similarly, if I try something like this:同样,如果我尝试这样的事情:

$('document').ready(function() {
  $('#searchVariantTable').hide();
  $('form').submit(function(e) {
      $('#searchVariantTable').show();
      e.preventDefault();
  });
});

It doesn't work either.它也不起作用。

I think the last option, if I'm not mistaken, is AJAX, but I'm not quite sure how to do something like that with Django (it's my first time using Django)如果我没记错的话,我认为最后一个选项是 AJAX,但我不太确定如何用 Django 做类似的事情(这是我第一次使用 Django)

What am I doing wrong?我究竟做错了什么? Is there an option that I am missing?有没有我错过的选项?

You can try by using if else in django template:您可以尝试在 django 模板中使用 if else :

index.html
<form method="post">
<input type="submit">
</form>
{% if allowed == "yes" %}
<!-- your table code -->
{% endif %}


and in views.py
if request.method == "POST":
    return render(request, 'index.html',{'allowed':'yes'})

else:
    return render(request,'index.html',{'allowed':'no'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM