2017-02-26 153 views
1

嘗試使用的創建對象將數據插入到與外鍵的蟒蛇模型,得到一個「用戶」的對象沒有屬性「__getitem__」有沒有屬性「的GetItem「用戶」對象對創建對象

從django.db進口車型 從..loginRegistration_app.models

models.py

未來進口unicode_literals 導入用戶

class PostManager(models.Manager): 
    error_list = [] 
    def post_in(self, postData, user_id): 
     if len(postData['post']) < 1: 
      context = {'status':0} 
      return context 
     else: 
      curr_user = User.objects.get(id = user_id) 
      # print curr_user.last_name 
      self.create(secrets = postData['post'], users_id = curr_user['id']) 

class Like(models.Model): 
    like = models.BooleanField() 
    users = models.ForeignKey(User, related_name = 'user_likes') 
    created_at = models.DateTimeField(auto_now_add = True) 
    upated_at = models.DateTimeField(auto_now = True) 

class Secret(models.Model): 
    secret = models.TextField(max_length = 1000) 
    likes = models.ForeignKey(Like, related_name = 'all_likes') 
    users = models.ForeignKey(User, related_name = 'user_secrets') 
    created_at = models.DateTimeField(auto_now_add = True) 
    upated_at = models.DateTimeField(auto_now = True) 

    objects = PostManager() 

views.py

from django.shortcuts import render, redirect 
from .models import Secret 
from django.contrib import messages 

def index(request): 
    if 'user_id' not in request.session: 
     return redirect('main:home') 
    # put query to display most recent secrets 

    return render(request, 'dojo_secrets_app/index.html') 

def post_it(request): 
    post_this = Secret.objects.post_in(request.POST, request.session['user_id']) 
    return redirect('secrets:home') 

錯誤:

TypeError at /secrets/post_it 
'User' object has no attribute '__getitem__' 

self.create(secrets = postData['post'], users_id = curr_user['id']) 

回答

1

id是用戶實例的屬性,而不是一些dict關鍵:

def post_in(self, postData, user_id): 
    # ... 
    curr_user = User.objects.get(id = user_id) 
    self.create(..., users_id = curr_user.id) # id is an attribute 

但由於user_id是一個屬性您查看,爲什麼不使用它?

self.create(..., users_id = user_id) 

順便說一句,你ForeignKey領域要真有奇異的名字('like', 'user'),複數名沒有任何意義的語義...