AttributeError: 'Post' object has no attribute 'get_absolute_url'

1,390 views
Skip to first unread message

Mayur Pabari

unread,
Jul 18, 2016, 10:30:50 AM7/18/16
to Django users

Below is the code of views.py. I am getting error when calling HttpResponseRedirect in update and create method. So please let me know how can i solve this ?

from
django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from .forms import PostForm from . models import Post def post_create(request): #create Method form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) context = { "form" : form, } return render(request, "post_form.html", context) def post_list(request): #list method queryset = Post.objects.all() context = { "object_list": queryset, "title": "List" } return render(request, "index.html", context) def post_update(request, id=None): #update Method instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) #i am getting error here context = { "title": instance.title, "instance": instance, "form": form, } return render(request, "post_form.html", context)
error1.png

ludovic coues

unread,
Jul 18, 2016, 11:02:58 AM7/18/16
to django...@googlegroups.com
The code of your model would be more interesting. According to the
error, Post have no method get_absolute_url. That method isn't
provided by models.Model, you have to write it. A way to do it is like
that:

from django.db import models
from django.urls import reverse

class Item(models.Model):
name = models.CharField(max_length=32)

def get_absolute_url(self):
return reverse('app:item', kwargs={'pk':self.pk})


Also, I would suggest you to have a look at class based view,
especially those handling form [1]. That's unrelated to your problem
but might save you time in the future :)

[1] https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/
> --
> You received this message because you are subscribed to the Google Groups
> "Django users" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-users...@googlegroups.com.
> To post to this group, send email to django...@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-users.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-users/5486d915-3589-43c8-8d39-943b299f1a20%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.



--

Cordialement, Coues Ludovic
+336 148 743 42
Reply all
Reply to author
Forward
0 new messages