我是django的新手,我想将我输入的数据存储到我的html文本标签中以存储在我的SQLite数据库中,我知道我错过了一些代码所以请建议我。
的index.html
<html>
<head>
<header style="background-color:blue;">
<h1 >Test template</h1></header>
<script>
function myfunc()
alert("data saved")
</script>
</head>
<body style="background-color:#FFD700">
<p>
<form>
question: <input type="text" name="question"><br>
answer: <input type="text" name="answer"><br>
<button type="button" onclick="myfunc()">save</button>
</form>
</p>
</center>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render_to_response
def Index(request):
return render_to_response('Index.html')
models.py
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
answer = models.CharField('max_length=200')
def __unicode__(self):
return self.question
答案 0 :(得分:0)
你可以这样试试。 在模板中:
<form action="/url" method="post">
{% csrf_token %}
question: <input type="text" name="question"><br>
answer: <input type="text" name="answer"><br>
<button type="button" onclick="myfunc()">save</button>
</form>
在views.py中:
def Index(request):
new_poll= Poll() #call model object
d= request.POST
new_poll.question= d['question']
new_poll.question= d['answer']
new_poll.save()
return render_to_response('Index.html')