这是我定义的模型:
class Post(models.Model):
user = models.ForeignKey(MSUser)
upvote_count = models.IntegerField()
post_status = models.IntegerField(choices = POST_STATUS)
title = models.CharField(max_length=200,null = True,blank = True)
content = models.CharField(max_length=1000,null = False,blank = False)
created_at = models.DateTimeField(auto_now_add=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
def __unicode__(self):
return self.content
def get_user(self):
return self.user.__unicode__()
def save(self, **kwargs):
super(Post, self).save(**kwargs)
以下是观点:
class Post (View):
@method_decorator(csrf_exempt) # To be removed
def dispatch(self, request, *args, **kwargs):
# Placeholder for fine grained permission system to prevent unwarranted GET/POST/PUTS
# Check request.user properties (like group etc) and request.method
# return HttpResponseForbidden()
return super(Post, self).dispatch(request, *args, **kwargs)
def get(request):
pass
def post(self, request):
responseMessage = {}
user = request.user
if user.is_authenticated():
title = request.POST.get('title', None)
content = request.POST.get('content', None)
if title is None or content is None:
responseMessage['status'] = 'failure'
responseMessage['message'] = 'Mandatory data is missing.'
return HttpResponse(json.dumps(responseMessage))
else:
newPost = Post(user = user,
title = title,
content = content,
post_status = PS_CREATED,
upvote_count = 0)
newPost.save()
responseMessage['status'] = 'success'
responseMessage['message'] = 'Post created successfully'
responseMessage['server_id'] = newPost.id
return HttpResponse(json.dumps(responseMessage))
从Postman
发送请求时,我不断收到以下错误:
AttributeError: 'Post' object has no attribute 'save'
我做错了什么?
答案 0 :(得分:4)
您的视图类和模型类具有相同的名称,即Post
。
因此,当您在视图中执行Post(user=..)
时,它会尝试创建Post
视图对象,然后在其上调用.save()
,而它应创建Post
模型对象并保存它。
要解决您的问题,您需要将视图类名更改为其他名称。
尝试更改
class Post(View):
类似
class PostView(View):
答案 1 :(得分:2)
您有混合的名为Post
的重复对象。看起来您正在尝试保存View
对象而不是Model
对象。