错误:通过POST方法通过AJAX提交表单时发生Method Not Allowed (POST): / 405
。最终,这应采用所有提交的值(first_name,last_name,电话,电子邮件),并将它们分别保存到带有外键的适当模型中。我目前正在使用基于类的视图,并且在def post中,我必须通过简单的验证来保存对象,但是几个小时我不知道该怎么做。
urls.py
urlpatterns = [
path('', views.AddressView.as_view()),
path('add/', views.AddressPost.as_view()),
path('delete/<int:pk>/', views.AddressDelete.as_view()),
]
views.py
class AddressView(generic.ListView):
model = Person
template_name = 'address_book/main.html'
def get_context_data(self, *, object_list=None, **kwargs):
context = super(AddressView, self).get_context_data(**kwargs)
context.update({
'people_list': Person.objects.all(),
'phones_list': Phone.objects.order_by('person_id'),
'email_list': Email.objects.all(),
})
return context
class AddressDelete(APIView):
def get_object(self, pk):
try:
return Person.objects.get(pk=pk)
except Person.DoesNotExist:
raise NotFound
def delete(self, request, pk, format=None):
self.get_object(pk).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class AddressPost(APIView):
def post(self, request, *args, **kwargs):
pass
add_contact.js
$(document).ready(function () {
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$("#addContactForm").submit(function(event){
var next_id = parseInt($("#addressTab tbody tr:last-child td:first-child").html())+1;
var first_name = $("#first_name").val();
var last_name = $("#last_name").val();
var phone = $("#phone").val();
var email = $("#email").val();
if (first_name != "" && last_name != ""){
var markup = "<tr><td id='person-id'>" + next_id + "</td><td id='person-first_name'>"
+ first_name + "</td><td id='person-last_name'>" + last_name + "</td><td id='person-phone'>"
+ phone + "</td><td id='person-email'>" + email + "</td><td id='person-delete'></td></tr>";
$.ajax({
url: "add/",
type: 'POST',
data: $("#addContactForm").serialize(),
contentType:'application/json',
dataType: 'text',
error: function(result){
M.toast({html: 'Kontakt niepoprawnie dodany', classes: 'red rounded', displayLength:3000})
},
success: function(result) {
$("#addressTab tbody").append(markup);
$("form").trigger('reset');
M.toast({html: 'Kontakt poprawnie dodany', classes: 'green rounded', displayLength:3000})
}
)};
}else{
M.toast({html: 'Proszę wpisać imię i nazwisko dla nowego kontaktu.', classes: 'red rounded', displayLength:3000})
}
return false;
});
});
models.py
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=40)
lastname = models.CharField(max_length=50)
@property
def phones(self):
return list(Phone.objects.filter(person=self).values_list('phone', flat=True))
@property
def emails(self):
return list(Email.objects.filter(person=self).values_list('email', flat=True))
class Phone(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE, editable=False)
phone = models.CharField(max_length=50)
class Email(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE, editable=False)
email = models.EmailField(max_length=100)