I am following this documentation on how to make a post request using ajax and django:
https://dev.to/coderasha/how-to-send-django-form-with-ajax-4bpo
This is how far I got:
import.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
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
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. When required
is present, input field must be filled out before submitting the form. See here: https://www.w3schools.com/tags/att_input_required.asp Also from Django documentation:
Field.blank If True, the field is allowed to be blank. Default is False. Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required. Blockquote
You will need to specify blank = True
For example: 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 !!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.