Как добавить поле с помощью POST, используя Fetch API в приложении Django?
Здравствуйте, я пытаюсь использовать fetch api для вызова POST запроса и создания/добавления нового элемента в таблицу с помощью vue. Я не уверен, где и как создать форму для ввода данных. У меня есть этот код до сих пор: У меня уже работают функции удаления и редактирования, мне нужна только функция POST.
countries.html
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Country</th>
<th scope="col">Code</th>
<th width="100" scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="(country, index) in countries">
<th scope="row">
[[ index ]]
</th>
<td>
<input v-if="country.editing" type="text" v-model="country.name" />
<a v-else :href="country.url">
[[ country.name ]]
</a>
</td>
<td>
<input v-if="country.editing" type="text" v-model="country.code" />
<span v-else>[[ country.code ]]</span>
</td>
<td class="d-flex justify-content-between">
<button v-if="!country.editing" @click="country.editing = true" class="btn btn-sm btn-secondary">
Edit
</button>
<button v-else @click="saveCountryChanges(country)" class="btn btn-sm btn-success">
Save
</button>
<button @click="deleteCountry(country)" class="btn btn-sm btn-danger">
Delete
</button>
</td>
</tr>
</tbody>
</table>
<script>
methods: {
async addCountry(country) {
let response = await fetch(country.api, {
method: "POST",
body: JSON.stringify({
name: country.name,
code: country.code,
}),
headers: {
"Content-Type": "application/json",
"X-CSRFToken": document.querySelector("[name=csrfmiddlewaretoken").value,
}
});
if (response.ok) {
country.adding = false;
}
else {
// country add failed
alert("Failed to add changes");
}
}
</script>
api.py
def country_api(request, country_id):
country = get_object_or_404(Country, id=country_id)
if request.method == "POST":
POST = json.loads(request.body)
country.name = POST['name']
country.code = POST['code']
country.save()
return JsonResponse({})
def countries_api(request):
return JsonResponse({
'countries': [
country.to_dict()
for country in Country.objects.all()
]
})
Любая помощь будет очень признательна! Спасибо!