2017-03-19 2 views
0

私はdjango authバックエンド、Django RESTフレームワークAPIとバックボーンをプロジェクトに使用しています。 console.log(currentUser)バックボーンモデルから属性を取得してDjango認証バックエンドAPIを取得する方法

attributes:Objectを読み取る方法
attributes: Object 
    email: "y****@*****m" 
    first_name: "" 
    id: 1 
    is_staff: true 
    last_name: "" 
    url: "http://127.0.0.1:8000/api/users/1/" 
    username: "yorsant" 

ため

var User = Backbone.Model.extend({ 
    urlRoot: host + 'api/users/' 
}); 

// django auth response 
var isAuthenticated = {{ request.user.is_authenticated|yesno:"true,false" }}; 
if (isAuthenticated){ 
    var userID = {{ request.user.id }}; // django user id 
    console.log(userID); // checking value 
    var currentUser = new User({id: userID}); 
    currentUser.fetch(); 
    var username = currentUser.get('username'); 
    console.log(currentUser); // checking value 

結果?

+0

ちょっとYordan、私はあなたがDjango Rest Frameworkを使用していると仮定していますか? APIがどのように働いているのか投稿できますか?現在のレスポンスが返すものと同様に、views.pyが役立ちます。 – leemac

+0

'{ " url ":" http://127.0.0.1:8000/api/users/1/ "、 " username ":" yorsant "、 " email ":" y ***** @ * *** m "、 " first_name ":" "、 " last_name ":" "、 " is_staff ":true }' api results。私は質問を編集し、モデルがフェッチしている、私は値を取得する方法がわからない。 –

+0

ModelViewSetとHyperlinkedModelSerializerを使用しています –

答えて

0

Eric saidと同様に、fetchは非同期です。

オブジェクトを探索するのに十分な時間があるため、APIへのラウンドトリップが完了したため、コンソールにデータが表示されます。

Object initial appearance in the consoleObject after being evaluated by the console

クロムDEVツールコンソールが記録されているオブジェクトへの参照を保持し、その後、ユーザはそれを操作したとき(クリックでオブジェクトを崩壊)、オブジェクトの横に少し!が示されているとあなたは読むことができます:

以下の値は今評価されました。

バックボーンModel fetch functionは、successコールバックのように、異なるオプションを渡すことができます。属性は使用する準備ができたら、これを知っ

currentUser.fetch({ 
    success: function() { 
     console.log("username:", currentUser.get('username')); 
    } 
}); 

、バックボーンビューで、あなたが知っているBackbone's eventsを使用することができます。

var View = Backbone.View.extend({ 
    initialize: function() { 
     this.listenTo(this.model, 'sync', this.render); 
     this.model.fetch(); 
    }, 

    // this is called when the model's sync event is fired, so 
    // when the model's attributes are ready. 
    render: function() { 
     this.$el.html(this.template(this.model.toJSON())); 
     return this; 
    } 
}); 

"同期"(model_or_collection, response, options) - モデルや 収集が正常にサーバーと同期されています。

+1

ありがとう@EmileBergeron、私は今よく分かります。 –

関連する問題