尝试使用create对象使用外键将数据插入到python模型中并获取'User'对象没有属性' getitem '
models.py
来自将来导入unicode_literals 来自django.db导入模型 来自..loginRegistration_app.models导入用户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'])
答案 0 :(得分: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'
),复数名称在语义上没有意义......