tastypie发布和完整的例子

时间:2012-02-03 10:26:16

标签: django api tastypie

是否有完整的tastypie django示例网站和设置可供下载?我一直在挣扎着整天缠着它。我有以下代码。基本上,我有一个用ajax处理的POST表单。当我在表单上单击“提交”并运行ajax请求时,调用将返回“POST http://192.168.1.110:8000/api/private/client_basic_info/ 404(未找到)”我认为我已将URL配置为正常。我可以访问http://192.168.1.110:8000/api/private/client_basic_info/?format=json就好了。我错过了一些设置或在我的方法中出现了一些基本错误吗?我的意图是每个用户可以填写/修改一个且仅修改一个“客户基本信息”表单/模型。

一页:

{% extends "layout-column-100.html" %}
{% load uni_form_tags sekizai_tags %}

{% block title %}Basic Information{% endblock %}

{% block main_content %}

    {% addtoblock "js" %}
        <script language="JavaScript">

        $(document).ready( function() {

            $('#client_basic_info_form').submit(function (e) {

                form = $(this)

                form.find('span.error-message, span.success-message').remove()
                form.find('.invalid').removeClass('invalid')
                form.find('input[type="submit"]').attr('disabled', 'disabled')

                e.preventDefault();
                var values = {}

                $.each($(this).serializeArray(), function(i, field) {
                    values[field.name] = field.value;
                })


                $.ajax({
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(values),
                    dataType: 'json',
                    processData: false,
                    url: '/api/private/client_basic_info/',
                    success: function(data, status, jqXHR) {
                        form.find('input[type="submit"]')
                            .after('<span class="success-message">Saved successfully!</span>')
                            .removeAttr('disabled')
                    },
                    error: function(jqXHR, textStatus, errorThrown) {

                        console.log(jqXHR)
                        console.log(textStatus)
                        console.log(errorThrown)

                        var errors = JSON.parse(jqXHR.responseText)
                        for (field in errors) {
                            var field_error = errors[field][0]
                            $('#id_' + field).addClass('invalid')
                                .after('<span class="error-message">'+ field_error +'</span>')
                        } 
                        form.find('input[type="submit"]').removeAttr('disabled')
                    }
                }) // end $.ajax()

            }) // end $('#client_basic_info_form').submit()

        }) // end $(document).ready()

        </script>
    {% endaddtoblock %}


{% uni_form form form.helper %}


{% endblock %}

资源

from residence.models import ClientBasicInfo
from residence.forms.profiler import ClientBasicInfoForm

from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.validation import FormValidation
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

class UserResource(ModelResource):

    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        fields = ['username']
        filtering = {
            'username': ALL,
        }
        include_resource_uri = False
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

    def dehydrate(self, bundle):
        forms_incomplete = []

        if ClientBasicInfo.objects.filter(user=bundle.request.user).count() < 1:
            forms_incomplete.append({'name': 'Basic Information', 'url': reverse('client_basic_info')})

        bundle.data['forms_incomplete'] = forms_incomplete
        return bundle


class ClientBasicInfoResource(ModelResource):
    user = fields.ForeignKey(UserResource, 'user')


    class Meta:
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        include_resource_uri = False
        queryset = ClientBasicInfo.objects.all()
        resource_name = 'client_basic_info'
        validation = FormValidation(form_class=ClientBasicInfoForm)
        list_allowed_methods = ['get', 'post', ]
        detail_allowed_methods = ['get', 'post', 'put', 'delete']

编辑:

我的资源文件现在是:

from residence.models import ClientBasicInfo
from residence.forms.profiler import ClientBasicInfoForm

from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authentication import BasicAuthentication
from tastypie.authorization import DjangoAuthorization, Authorization
from tastypie.validation import FormValidation
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User

class UserResource(ModelResource):

    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        fields = ['username']
        filtering = {
            'username': ALL,
        }
        include_resource_uri = False
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()

    #def apply_authorization_limits(self, request, object_list):
    #    return object_list.filter(username=request.user)

    def dehydrate(self, bundle):
        forms_incomplete = []

        if ClientBasicInfo.objects.filter(user=bundle.request.user).count() < 1:
            forms_incomplete.append({'name': 'Basic Information', 'url': reverse('client_basic_info')})

        bundle.data['forms_incomplete'] = forms_incomplete
        return bundle


class ClientBasicInfoResource(ModelResource):
    # user = fields.ForeignKey(UserResource, 'user')

    class Meta:
        authentication = BasicAuthentication()
        authorization = DjangoAuthorization()
        include_resource_uri = False
        queryset = ClientBasicInfo.objects.all()
        resource_name = 'client_basic_info'
        validation = FormValidation(form_class=ClientBasicInfoForm)
        #list_allowed_methods = ['get', 'post', ]
        #detail_allowed_methods = ['get', 'post', 'put', 'delete']

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)

我使ClientBasicInfo的用户字段可以为空,POST似乎有效。我想尝试立即更新条目。那只是将pk附加到ajax网址吗?例如/ api / private / client_basic_info / 21 /?当我提交该表格时,我收到了501 NOT IMPLEMENTED消息。究竟我没有实现什么?我是ModelResource的子类,它应该根据文档实现所有与ORM相关的函数。

1 个答案:

答案 0 :(得分:3)

好的,我明白了。我不小心。 AJAX请求类型应该是“PUT”来处理501未实现的错误(我正在执行更新)。我还设置了一个自定义身份验证类来处理403错误。