class CreatePosts(CreateView):
model = posts
fields = ['title','comments']
def post(self, request, *args, **kwargs):
current_inspectionfile = Inspectionfile.objects.get(pk = self.kwargs['pk'])
new_post = posts.objects.create(inspectionfile=current_inspectionfile,
title =request.POST.get("title"),
comments =request.POST.get("comments"))
return new_post
Models
class posts(models.Model):
inspectionfile = models.ForeignKey(Inspectionfile, on_delete=models.CASCADE, default=1)
title = models.CharField(max_length=120)
comments = models.TextField()
flag = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse('posts_form', kwargs={'pk': self.pk})
def __str__(self):
return self.title
form is a simple template:
<form class = "form_horizontal" action = "" method = "post">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Submit</button>
</form>
my url is:
url(r'^(?P<pk>[0-9]+)/$',views.CreatePosts.as_view(),name=='posts_form')
The error I am getting is
"posts" object has no attribute get.
I have tried seeing other blogs but nothing seems to work. I have overridden the post method in CreatePosts class to work in a certain way. Is this why I am getting this error or is it because of some URL mismatch. Once the user hits submit I want them to come back to the same form hence the URL.
Your post method is returning an instance of your model
return new_post
All views must return a HttpResponse so the simplest thing to return with your new post in the context would be render
return render(request, self.template_name, {'new_post': new_post })