[英]Make a POST request using Ajax & Django
I am following this documentation on how to make a post request using ajax and django:我正在关注有关如何使用 ajax 和 django 发出发布请求的文档:
https://dev.to/coderasha/how-to-send-django-form-with-ajax-4bpo https://dev.to/coderasha/how-to-send-django-form-with-ajax-4bpo
This is how far I got:这是我走了多远:
import.html导入.html
<form method="POST" id="solver_args-form">{% csrf_token %}
{% for field in form.visible_fields %}
<div class="form-group">
{{ field.label_tag }}
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
$(document).on('submit', '#solver_args-form',function(e){
$.ajax({
type:'POST',
url:'{% url "create" %}',
data:{
name:$('#id_name').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
action: 'post'
},
success:function(json){
document.getElementById("solver_args-form").reset();
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
});
views.py视图.py
def update_solverargs(request):
solver_args = SolverArgs.objects.all()
response_data = {}
if request.POST.get('action') == 'post':
name = request.POST.get('name')
response_data['name'] = name
SolverArgs.objects.create(
name = name,
)
return JsonResponse(response_data)
return render(request, 'import.html', {'solver_args':solver_args})
urls.py网址.py
urlpatterns = [
url(r'^create/$', update_solverargs, name='update_solverargs'),
]
No errors in console, the page does refresh when I submit the form and nothing gets stored into the database.控制台中没有错误,当我提交表单时页面确实刷新并且没有任何内容存储到数据库中。
Thank you for any help感谢您的任何帮助
Required
is a separate attribute. Required
是一个单独的属性。 When required
is present, input field must be filled out before submitting the form.当required
,必须在提交表单之前填写输入字段。 See here: https://www.w3schools.com/tags/att_input_required.asp Also from Django documentation:请参阅此处: https ://www.w3schools.com/tags/att_input_required.asp 同样来自 Django 文档:
Field.blank If True, the field is allowed to be blank. Field.blank 如果为 True,该字段允许为空。 Default is False.默认为假。 Note that this is different than null.请注意,这与 null 不同。 null is purely database-related, whereas blank is validation-related. null 纯粹与数据库相关,而 blank 与验证相关。 If a field has blank=True, form validation will allow entry of an empty value.如果一个字段有 blank=True,表单验证将允许输入一个空值。 If a field has blank=False, the field will be required.如果一个字段有 blank=False,则该字段将是必需的。 Blockquote块引用
You will need to specify blank = True
For example: field = models.CharField(max_length=8, default='', blank=True)
您需要指定blank = True
例如: field = models.CharField(max_length=8, default='', blank=True)
I changed:我变了:
if request.POST.get('action') == 'POST':
to:到:
if request.method == 'POST':
and now it works !!现在它起作用了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.