我一直试图通过表单使用django和sqlite3保存模型。 以下是代码:
这是 /home/secure/secure_db/urls.py :
from django.conf.urls import url from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^create/$',views.create_db, name='create_db') ]
这是 /home/secure/secure_db/views.py
from django.http import HttpResponse from django.shortcuts import render from .models import Detail from passlib.hash import pbkdf2_sha256
def index(request):
template = 'index.html'
return render(request, template)
def create_db(request):
if request.method == 'POST':
id = request.POST['id']
name = request.POST['name']
enc_id = pbkdf2_sha256.encrypt(id, rounds=12000, salt_size=32)
Detail.objects.create(
id = enc_id,
name = name
)
return HttpResponse('')
这是 /home/secure/secure_db/models.py
from django.db import models
from passlib.hash import pbkdf2_sha256
class Detail(models.Model):
id = models.IntegerField(primary_key=True, unique=True)
name = models.CharField(max_length=100)
def verify_id(raw_id):
return pbkdf2_sha256.verify(raw_id, self.id)
这是 /home/secure/secure_db/templates/index.html
<html>
<head>
<script type="text/javascript" >
$(document).on('submit','#new_user_form',function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'/secure_db/create',
data:{
id:$('#id').val(),
name:$('#name').val(),
csrfmiddlewaaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:function () {
alert("Created New User");
}
});
});
</script>
</head>
<body>
<form id="new_user_form" method="post">
{% csrf_token %}
User ID:<br>
<input type="number" name="id" id="id"><br>
Name:<br>
<input type="text" name="name" id="name"><br>
<input type="submit" value="SUBMIT">
</form>
</body>
</html>
当我导航到http://localhost:8000/secure_db并输入ID和名称时,警报未显示且数据未存储到数据库中。如果我通过导航到管理面板存储数据,则数据将以普通格式存储,并且ID不会被加密。