2012-02-03 18 views
6

完全なtastypie djangoのサンプルサイトとセットアップはダウンロードできますか?私は一日中、頭を包み込むように取り組んできました。私は次のコードを持っています。基本的には、私はajaxで処理されるPOSTフォームを持っています。私のフォームで "submit"をクリックすると、ajaxリクエストが実行され、 "POST http://192.168.1.110:8000/api/private/client_basic_info/ 404(NOT FOUND)"という戻り値が返されます。私はhttp://192.168.1.110:8000/api/private/client_basic_info/?format=jsonにアクセスできます。いくつかの設定が欠落しているか、または私のメソッドに根本的な誤りがありますか?私の意図は、各ユーザーが1つの "クライアント基本情報"フォーム/モデルを記入/修正できることです。趣味の投稿と完全な例

ページ:

{% 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 NULL可能のユーザー・フィールドを作りました〜 d POSTが機能しているようです。私は今エントリを更新しようとします。 ajaxのURLにpkを追加するだけでしょうか?例:/ api/private/client_basic_info/21 /?私がそのフォームを提出すると、501 NOT IMPLEMENTEDメッセージが表示されます。私が実装していないものは何ですか?私はModelResourceをサブクラス化しています。これは、すべてのORM関連の関数がドキュメントに従って実装されている必要があります。

+0

APPEND_SLASHESに何か問題がありますか? http://192.168.1.110:8000/api/private/client_basic_info(スラッシュを付けずに)に投稿しましたか?ちょうど推測。 – nisc

+0

うーん、私はURLからスラッシュを取り、 "あなたはPOST経由でこのURLを呼び出しましたが、URLはスラッシュで終わらず、APPEND_SLASHを設定しました。" APPEND_SLASH = Falseを設定に適用しましたが、403禁止メッセージ(CSRF検証に失敗しました)が表示されます。私はビューcsrf_exemptを作ってそれを過ぎてしまった。今私は501実装されていないエラーを取得します。私はカスタム水和物の機能を追加し、それを過ぎた。オブジェクトを更新するためにフォームを送信しようとしましたが、別のエラーが発生します。エラー後のエラー、私はちょうどtastypieをあきらめるだろうと思う。 –

+0

私はTastyPieのエキスパートではないので、私はもっと推測できるだけです。異なる認証と認可のバックエンドを試したことがありますか?認証と認証にそれぞれtastypieの 'Authorization'クラスと' Authentication'クラスを使ってみてください。彼らは非常に寛大でなければなりません。それが問題かどうかを確認するだけです。 – nisc

答えて

3

さて、私はそれを理解しました。私は慎重ではなかった。 501の実装されていないエラー(私はアップデートを実行していました)を処理するために、AJAXリクエストタイプは "PUT"されている必要があります。 403エラーを処理するカスタム認証クラスも設定しました。

+0

D'oh:)8もっと見る... – nisc

関連する問題