Django我对get_absolute_url有很多问题

时间:2017-06-08 09:02:58

标签: python django

第一个问题:

当我创建新帖子时,我会看到此消息(Reverse for 'details' with keyword arguments '{'pk': 1, 'slug': ''}' not found。尝试了1种模式:(['post/(?P<pk>\\d+)(?:/(?P<slug>[\\w\\d-]+))?/$'])

Secound问题:

当我在readmore botton中调用get_absolute_url时,我看到此消息('PostCreate' object has no attribute 'get_absolute_url')

两天我尝试解决这个问题我尝试了所有的解决方案,但我失败了

这是我的代码

views.py

class PostCreate(CreateView):
    model = Post
    template_name = "posts/create.html"
    query_pk_and_slug = True
    fields = ['title','body','category']
    def form_valid(self, form):
        form = form.save(commit=False)
        form.user = self.request.user
        return super(PostCreate, self).form_valid(form)

    def get_success_url(self):
        return self.get_absolute_url

models.py

class Category(models.Model):
    name = models.CharField(max_length=100, blank=True, null=True, default="")

    def __str__(self):
        return self.name

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100, blank=False, null=False, default="")
    body = models.TextField(max_length=1000,blank=False, null=False, default="")
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    slug  = models.SlugField(blank=True,default="-",unique=False)
    updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self,):
        return reverse('post:details', kwargs={'pk': self.id, 'slug': self.slug})

urls.py

from django.conf.urls import url
from .views import (PostList, PostDetail, PostCreate, PostUpdate, ArticleDetailRedirect)
from django.urls import reverse
urlpatterns = [
     url(r'^$', PostList.as_view(), name="index"),
     url(r'^create/$', PostCreate.as_view(), name="create" ),
     url(r'^(?P<pk>[0-9]+)/update/$', PostUpdate.as_view(), ),
     url(r'^(?P<pk>\d+)/$', PostDetail.as_view()),
     url(r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$', PostDetail.as_view(), name = 'details'),
     url(r'^(?P<pk>\d+)(?:/(?P<slug>[\w\d-]+))?/$', ArticleDetailRedirect.as_view(), name = 'article_details'),

的index.html

<a href="{{ list.get_absolute_url }}">
   <button type="button" class="btn btn-primary">
     <span class="btn btn-google">Read More
      <i class="fa fa-chevron-right"></i>
     </span>
  </button>
</a>

感谢

0 个答案:

没有答案