這是我所定義的模型:模型對象有沒有屬性保存
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'
我在做什麼錯了?
真的,你應該使用的ModelForm。然後,您可以使用CreateView並擺脫這裏的大部分邏輯。 –