我在我的程序中使用ajax调用。我收到的错误如下:
TypeError: __init__() got an unexpected keyword argument 'password'
我在模型中有以下内容:
class Student(models.Model):
name = models.CharField(max_length = 20 )
password = models.CharField(max_length = 100 )
email = models.CharField( max_length = 10 )
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__
现在,以下是我的模板:
`<form id = "post_submit" action="{% url "apply" %}" method="POST">
{% csrf_token %}
{% for field in form %}
<p>{{field.label}} : {{field}}</p>
{% endfor %}
<p><input type="submit" name="Submit"></p>
</form>
<p id="click_option">Click here.</p>
Ajax调用使用:
进行 $.ajax({
// using this for csrf handling
// alert(" i am in ajax");
// console.log(" iam ");
url : "/apply/",
type : "POST",
data :
{
csrfmiddlewaretoken:document.getElementsByName('csrfmiddlewaretoken')[0].value,
name : $('#id_name').val(),
email : $('#id_email').val(),
password : $('#id_password').val(),
},
success: function(json) {
alert("Congratulations! You scored: " + json['status']);
},
// error
})
});
后端的视图是:
def apply(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
student = StudentForm(name = name, email = email, password = password)
student.save()
data = {"status" : "success"}
return JsonResponse(data)
else:
data = {"status" : "failure"}
return JsonResponse(data)
答案 0 :(得分:2)
您不必手动从POST数据中提取值,表格会为您处理。
在检查表单是否有效后,您可以调用save()
来保存模型实例。
form = StudentForm(request.POST)
if form.is_valid()
student = form.save()
最后,您的Student
模型正在password
中存储CharField
。以纯文本格式存储密码是不安全的。 Django's authentication system为您处理哈希密码。使用它。