我刚刚开始使用Django Rest Framework为我正在开发的应用程序开发API,我需要能够使用它的AJAX请求。我已经按照文档进行了操作,并且能够使用可浏览的api执行任何操作而没有任何问题,但是,我的AJAX请求无法正常工作。正在发出请求,但发送的所有值均为null
。
我很难过为什么它不能正常工作。希望你们中的一个好伙伴可以帮助我。
我的views.py:
from django.shortcuts import render
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import Http404
from manager.models import UserProfile, Project
from manager.serializers import UserProfileSerializer, ProjectSerializer
class UserProfileList(generics.ListCreateAPIView):
"""
Returns a list of all UserProfiles
"""
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
class UserProfileDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a UserProfile instance.
"""
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
class ProjectView(generics.ListCreateAPIView):
"""
Returns a list of all Projects
"""
queryset = Project.objects.all()
serializer_class = ProjectSerializer
class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
"""
Retrieve, update or delete a Project instance
"""
queryset = Project.objects.all()
serializer_class = ProjectSerializer
我的serializers.py:
from rest_framework import serializers
from manager.models import UserProfile, Project
class UserProfileSerializer(serializers.ModelSerializer):
"""
Serializer for UserProfile objects
"""
class Meta:
model = UserProfile
fields = ('user', 'job_title', 'company', 'is_manager')
class ProjectSerializer(serializers.ModelSerializer):
"""
Serializer for Project objects
"""
class Meta:
model = Project
fields = ('created_by', 'name', 'description', 'date_created', 'icon')
我的forms.py:
from django import forms
class NewProjectForm(forms.Form):
name = forms.CharField(max_length=155, widget=forms.TextInput(
attrs={
'placeholder': 'Assign a name to your project',
'class': 'text-input m-b-5',
}
))
description = forms.CharField(max_length=140, widget=forms.TextInput(
attrs={
'placeholder': 'Give some details about the project',
'class': 'text-input m-b-2'
}
))
相关的JS代码:
function create_project() {
var csrftoken = getCookie('csrftoken');
$.ajax({
url: "/api/v1/projects/",
type: "POST",
data: {
name: $('#id_project_name').val(),
description: $('#id_project_description').val(),
csrfmiddlewaretoken: csrftoken
},
success: function(json) {
$('#id_project_name').val('');
$('#id_project_description').val('');
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
};
答案 0 :(得分:0)
Woops。输入ID不正确。它应该是#id_name
和#id_description
而不是#id_project_name
和#id_project_description
。
我想当您在更改内容时未更新所有代码时会发生什么。