Reputation: 5121
This is the model I've defined:
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)
Here is the view:
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))
When sending a request from Postman
I keep getting the following error:
AttributeError: 'Post' object has no attribute 'save'
What am I doing wrong?
Upvotes: 2
Views: 5463
Reputation: 47856
Your view class and the model class have the same name i.e. Post
.
So, when you do Post(user=..)
in your view, it tries to create the Post
view object and then call .save()
on it whereas it should have created the Post
model object and saved it.
To solve your problem, you need to change your view class name to something else.
Try changing
class Post(View):
to something like
class PostView(View):
Upvotes: 4
Reputation: 6834
You have duplicated objects named Post
which you got mixed. It looks like you are trying to save the View
object instead of the Model
object.
Upvotes: 2