我试图在Django中创建一个简单的Web应用程序,并尝试使用Ajax,以便页面不会刷新。此应用程序的唯一目标是拥有一个表单,该表单需要一些用户输入,并且在提交表单时不会刷新。但是,由于某些原因,当我单击按钮时不会发生这种情况。这是“索引”页面:
<!DOCTYPE html>
<html>
<body>
<h2>Create product here</h2>
<div>
<form id="new_user_form">
<div>
<label for="name" > Name:<br></label>
<input type="text" id="name"/>
</div>
<br/>
<div>
<label for="email"> email:<br></label>
<input type="text" id="email"/>
</div>
<div>
<label for="password" > password:<br></label>
<input type="text" id="password"/>
</div>
<div>
<input type="submit" value="submitme"/>
</div>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type = "text/text/javascript">
$(document).on('submitme', '#new_user_form', function(e)){
e.preventDefault()
$.ajax({
type: 'POST',
url:'/user/create',
data:{
name:$('#name').val(),
email:$('#email').val(),
password:$('#password').val(),
}
success.function(){
alert('created')
}
})
}
</script>
</html>
这是我的主要urls.py文件:
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url
from testapp import views
import testapp
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', testapp.views.index),
url(r'^user/create/$', csrf_exempt(testapp.views.create_user))
]
我的views.py文件:
from django.shortcuts import render
from testapp.models import User
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request, 'index.html')
def create_user(request):
if request.method == 'POST':
name = request.POST['name']
email = request.POST['email']
password = request.POST['password']
User.objects.create(
name = name,
email = email,
password = password
)
return HttpResponse('')
最后是models.py文件:
from django.db import models
# Create your models here.
class User(models.Model):
name = models.CharField(max_length = 32)
email = models.EmailField()
password = models.CharField(max_length = 128)
这样做的目的是当单击按钮时,它应该向后端发送一个POST请求,该请求创建一个User类型的对象并将其保存到数据库。但是,由于某些原因,当我单击“提交”时,没有根据Chrome上的“网络”工具发送POST请求。有人可以帮我吗?
答案 0 :(得分:0)
def create_user(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password')
user = authenticate(username=username, password=raw_password)
auth_login(request, user)
return render(request, 'accounts/index.html')
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})
您的代码应更像这样。在这里,我使用默认的django身份验证系统,因此您的model.py
并没有真正的需求,至少目前还没有。还要看一下我添加的渲染-使用HttpReponse
可以重新加载页面。电子邮件将自动与form.submit()
SignUpForm应该简单:
class SignUpForm(UserCreationForm):
email = forms.EmailField(max_length=254, help_text='Required.')
答案 1 :(得分:0)
您的代码看起来不错,但我希望为您进行以下更改: 我编辑并更新了我的帖子,因为先前的建议中有很少一部分不适用于您的情况(因为ajax contentType在您的情况下还可以,依此类推...),因此我为您清除了答案目的:
1。
在 HTML表单中,应在输入字段中输入输入名称,因为这样可以更轻松地使用AJAX提交输入的HTML表单值:
<input type="text" name="name" id="name"/>
<input type="email" name="email" id="email"/>
<input type="password" name="password" id="password"/>
提交按钮应按以下方式更改:
<button type="button" name="submitme" id="submitme">Submit</button>
2。
您的 AJAX呼叫应这样重新编写(我认为您的 url 中缺少尾部斜杠,并且数据可能更简单格式,然后点击功能现在位于按钮ID上。代码中的右括号已清除:
<script type = "text/text/javascript">
var $ = jQuery.noConflict();
$( document ).ready(function() {
$('#submitme').on('click', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:'/user/create/',
data: $('form').serialize(),
success: function(){
alert('created');
}
})
})
});
</script>
您的视图应如下所示,以获取ajax提交的数据并保存为新用户(只需很小的修改):
def create_user(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
new_user = User.objects.create(
name = name,
email = email,
password = password
)
new_user.save()
return HttpResponse('')
这样,它现在必须可以工作。希望对您有所帮助。
答案 2 :(得分:0)
不确定此答案的相关性。但是未为您创建“ POST”请求的唯一原因是因为您是用JS while (resultSet.next())
而不是final String queryCheck = "SELECT * from usersdata WHERE email = ?";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
ps.setString(1, email);
final ResultSet resultSet = ps.executeQuery();
if (resultSet.next()) {
/* First, if we cannot find the user's email, we return this statement */
if(email.equals(resultSet.getString("email"))) {
/* Second, if we can find the email but the password do not match then we return that the password is incorrect */
String hashedPasswordInput = AES.doHash(password, resultSet.getObject("password").toString().split("\t")[1]);
if(hashedPasswordInput.equals(resultSet.getObject("password").toString().split("\t")[0])) {
// dont do it here
// returnStatement = "LoginFailure The password that you entered is incorrect. Please try again!";
// connection.close();
}
else {
returnStatement = "LoginSuccess You are logged in!";
}
}
else {
// don't do it here
// connection.close();
// returnStatement = "LoginFailure We cannot find any account associated with that email. Please try again!";
}
}
答案 3 :(得分:-1)
尝试将 method="POST" 和 action="{% url 'url_name' %}" 添加到 html 表单。还要将名称添加到 url 以创建用户。