Django - 无法链接到新帖子

时间:2016-09-14 13:31:56

标签: django

我已经进行了广泛的搜索,沿途拾取了一些代码,但问题是不同的花絮可能无法转化为我想要的内容。基本上我有一个页面,我可以在/progresstracker/new创建新的博客文章,当我点击提交时,我希望新帖子在/progresstracker/<category>/<slug>处可用,我在/progresstracker有一个登录页面其中应包含所有帖子的摘要以及指向相应/<category>/<slug>网址的链接。我认为问题出在pk / slug上,但实际上可能存在一些错误。

URL:

urlpatterns = [
    url(r'^progresstracker/(?P<category>[\w\s]+),(?P<slug>[\w\s]+)/$', views.pt_detail, name='pt_detail'),
    url(r'^progresstracker/new/$', views.progresstracker_new, name='progresstracker_new'),
    url(r'^progresstracker/(?P<category>[\w\s]+),(?P<slug>[\w\s]+)/edit/$', views.post_edit, name='post_edit'),
    url(r'^progresstracker/', views.progresstracker, name='progresstracker'),
]

的观点:

def pt_detail(request, slug):
    ptpost = get_object_or_404(Post, slug=slug)
    return render(request, 'blog/pt_detail.html', {'ptpost': ptpost})

def progresstracker(request):
    posts = Post.objects.order_by('published_date')
    return render(request, 'blog/progresstracker.html', {'posts': posts})

def progresstracker_new(request):
    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            ptpost = form.save(commit=False)
            ptpost.author = request.user
            ptpost.published_date = timezone.now()
            ptpost.save()
            return redirect('pt_detail', slug=ptpost.slug)
    else:
        form = PostForm()
    return render(request, 'blog/post_edit.html', {'form': form})

def post_edit(request, slug):
    ptpost = get_object_or_404(Post, slug=slug)
    if request.method == "POST":
        form = PostForm(request.POST, instance=ptpost)
        if form.is_valid():
            ptpost = form.save(commit=False)
            ptpost.author = request.user
            ptpost.published_date = timezone.now()
            ptpost.save()
            return redirect('pt_detail', slug=ptpost.slug)
    else:
        form = PostForm(instance=ptpost)
    return render(request, 'blog/post_edit.html', {'form': form})

模型:

class Post(models.Model):
    title = models.CharField(max_length=100, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    body = models.TextField()
    posted = models.DateField(db_index=True, auto_now_add=True)
    category = models.ForeignKey('books.Category')
    ...     
    def get_absolute_url(self):
        return "/%s/%s/" % (self.category.slug, self.slug)

我现在没有模板代码,但“progresstracker.html”所有帖子的摘要有点正确链接到“progresstracker /(以%20为空格)/”

0 个答案:

没有答案