【问题标题】:How to refer to variables inside the html template?如何在 html 模板中引用变量?
【发布时间】:2019-11-10 19:20:15
【问题描述】:

我有一个初学者问题。 我遵循了一个关于如何将框架中的数据输入数据库的快速教程 (http://www.learningaboutelectronics.com/Articles/How-to-insert-data-into-a-database-from-an-HTML-form-in-Django.php)

<html>
<head>
<title>Create a Post </title>
</head>

<body>
<h1>Create a Post </h1>
<form action="" method="POST">
{% csrf_token %}
Title: <input type="text" name="title"/><br/>
Content: <br/>
<textarea cols="35" rows="8" name="content">
</textarea><br/>
<input type="submit" value="Post"/>
</form>
</body>

</html>

在上面的 HTML 中 - 我在 views.py 中使用了 name="title" 和 name="content"

def createpost(request):
        if request.method == 'POST':
            if request.POST.get('title') and request.POST.get('content'):
                post=Post()
                post.title= request.POST.get('title')
                post.content= request.POST.get('content')
                post.save()

                return render(request, 'posts/create.html')  

        else:
                return render(request,'posts/create.html')

效果很好,数据被输入到数据库中。

现在我想使用在互联网上找到的免费模板。我已经编辑了 HTML 文件的其他部分,剩下的部分是 使用下面的联系表格。不同之处在于他们使用“this.value”来传递字段的内容。以前我可以区分标题和内容,但现在它只是一个变量。如何在我的 views.py 中引用该变量? 我感兴趣的代码副本如下。

<div class="services_dark sj" id="signup">
       <div class="container">
            <h3 class="m_3"><center>Interested to join us?</center></h3>
            <div class="contact-form">
               <form method="post" action="contact-post.html">
                 <input type="text" class="textbox" value="First Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'First Name';}">
                 <input type="text" class="textbox" value="Last Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Last Name';}">
                 <input type="text" class="textbox" value="Email address" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email address';}">
                 <input type="submit" value="Join">
               </form>
            </div>
        </div>
    </div>

【问题讨论】:

  • 但是 this.content 只是一些用于编辑占位符的 JavaScript(尽管使用 placeholder="First Name" 可能会更好)。
  • 您需要为这些输入元素提供name 属性,就像您在原始模板中所做的那样。

标签: html django forms


【解决方案1】:

this.value = ''; 确实引用视图中的值。它用于从&lt;input&gt; 字段中删除占位符(并将其放回去,因为输入字段失去焦点并且用户没有输入任何内容)。因此,它是一些 JavaScript 来“动画”网页。

话虽如此,在这里使用placeholder="..." field [html.com] 更具声明性,例如:

<input type="text" class="textbox" placeholder="First Name">
<input type="text" class="textbox" placeholder="Last Name">
<input type="text" class="textbox" placeholder="Email address">

但是也有一些缺点。例如,大多数翻译软件不会翻译占位符,以免破坏某些 JavaScript 函数。

【讨论】:

  • 谢谢,我如何从views.py中的函数访问“名字”变量中的值,以便输入落在数据库表中?
  • 你应该给&lt;input&gt;s 一个name="...",然后是handle the POST request
猜你喜欢
  • 2015-12-08
  • 2020-04-01
  • 1970-01-01
  • 2014-08-09
  • 2018-02-05
  • 2019-03-12
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
相关资源
最近更新 更多