0

I am trying to pass the PK of a blog post but I am having difficulty with it. If possible I would like to pass the PK without putting it in the URL. I am trying to let my user edit their posts which are displayed in a list like below:

enter image description here

I need to make sure that when the user presses edit under a post, it allows them to edit that specific post. I believe where I am going wrong is in the get_object function when I try and get the PK. Any help with this would be much appreciated!

View

class EditPost(UpdateView):
    model = ProjectPost
    form_class = ProjectPostForm
    template_name = 'howdidu/edit_post.html'

    def get_object(self):
        return ProjectPost.objects.get(pk=self.request.Get.get('pk'))

    def get_success_url(self):
        project_username = self.request.user.username
        project_slug = self.object.project.slug
        return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})

model

class ProjectPost(models.Model):
    project = models.ForeignKey(UserProject)
    title = models.CharField(max_length=100)
    post_overview = models.CharField(max_length=1000)
    date_created = models.DateTimeField(auto_now_add=True)
    post_views = models.IntegerField(default=0)
    post_likes = models.IntegerField(default=0)

url

url(r'^edit_post/$', login_required(views.EditPost.as_view()), name='edit_post'),

link used for edit post template

<a href="{% url 'edit_post' %}">Edit post</a>
ollysmall
  • 633
  • 2
  • 7
  • 13
  • I don't understand why you don't want to pass `pk` to edit view? Also with your code you need to make the edit url to be something like `edit_post/?pk=10` to use the `GET` parameter in your edit view, which will show `pk` in url anyway. – Shang Wang Dec 03 '15 at 22:22
  • Hi @ShangWang , if possible I wanted to do it without passing the pk through the url. Am I able to do that? – ollysmall Dec 03 '15 at 22:24
  • Yea of course, you can pass whatever you like to the edit view, as long as it's unique to each `ProjectPost` object, because otherwise `objects.get` would throw an exception. But honestly, it's not the best practice. – Shang Wang Dec 03 '15 at 22:26
  • @ShangWang So whats the best way to get the pk? return ProjectPost.objects.get(pk=?????) – ollysmall Dec 03 '15 at 22:29
  • `Edit post` https://en.wikipedia.org/wiki/Query_string – Shang Wang Dec 03 '15 at 22:31
  • @ShangWang what else would I need to change to get that to work? I tried it but had no luck. do I need to change the get_object? – ollysmall Dec 03 '15 at 22:47
  • "No luck" is too vague. What error do you get? I would think that you should change `self.request.Get.get('pk')` to `self.request.GET.get('pk')`. – Shang Wang Dec 03 '15 at 23:07

0 Answers0