html:
{% extends 'base.html' %}
{% block content %}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Create a Recipe</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'title' : $('input[name=T]').val(),
'tags' : $('select[name=tags]').val(),
'ingredients' : $('select[name=ingredients]').val(),
'time_minutes' : $('input[name=Time]').val(),
'price' : $('input[name=P]').val(),
'link' : $('input[name=link]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/api/recipe/recipes/', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
</head>
<body class="">
<form method="POST">
{% csrf_token %}
<br>
<label for="T">Title: </label>
<input type="text" name="T" value="">
<br>
<label for="Ingr">Ingredients: </label>
<select multiple name="ingredients">
{% for ing in Ing %}
<option value="{{ing.pk}}">{{ing}}</option>
{%endfor%}
</select>
<br>
<label for="Tag">Tags: </label>
<select multiple name="tags">
{% for tag in Tag %}
<option value="{{tag.pk}}">{{tag}}</option>
{%endfor%}
</select>
<br>
<label for="Time">Time: </label>
<input type="text" name="Time" value="">
<br>
<label for="P">Price: </label>
<input type="text" name="P" value="">
<br>
<label for="link">Link: </label>
<input type="text" name="link" value="">
<br>
<input type="submit" name="submit" value="Post">
</form>
</body>
</html>
{%endblock%}
this is my HTML I am posting this form to my rest API all the form is posting except the arrays/select are posting as null/0 here is what's getting posted/data console:
id: 57 ingredients: Array(0)
length: 0
proto: Array(0)
link: "recipe.com"
price: "3.00"
tags: Array(0)
length: 0
proto: Array(0)
time_minutes: 20
title: "oOao"
proto: Object
as you can see the ingredients and tags which are arrays aren't posting even if I choose a option.