用户可以创建帖子,但如何重定向到刚刚创建的帖子页面用户?

时间:2016-02-15 13:00:57

标签: python django

目前,在用户创建页面后,它会被重定向到索引页面,因为我设置了重定向('index'),但我想重定向到刚刚创建的帖子页面用户。我如何实现这一目标?

我尝试了什么:

def category(request, category_name_url):
    user = User.objects.get(username=request.user)
    category_name = decode_url(category_name_url)

    try:

                category = Category.objects.get(name=category_name)
                sort = request.GET["sort"].strip()
                sort_method = SortMethods[sort]
                page = request.GET["page"].strip()
    except KeyError:
                sort_method = SortMethods.score
                page = 1

    if sort_method == SortMethods.date:
                thread_list = Post.objects.filter(category=category).order_by("-pub_date")
    else:
                thread_list = Post.objects.filter(category=category)
                thread_list = sorted(thread_list, key=lambda x: x.get_score(), reverse=True)

    paginator = Paginator(thread_list, 30)

    try:
                posts = paginator.page(page)
    except PageNotAnInteger:
                posts = paginator.page(1)
    except EmptyPage:
                posts = paginator.page(paginator.num_pages)
    context = {
                "posts": posts,
                "pages": paginator.page_range,
                "sort": sort_method.name,
                "category":category,
                'user':user,
                "following" :following(request.user.id),


        }
    return render(request, "main/category.html", context)


@login_required
def add_category(request):
    category = Category.objects.get(name=category_name)

    if not request.user.is_superuser and Category.objects.filter(author=request.user).exists():
        return render(request,'main/category_already_exists.html')
    if request.method == 'POST':
        category = Category(author=request.user)
        form = CategoryForm(request.POST, request.FILES, instance=category)
        if form.is_valid():
            form.save(commit=True)
            return redirect('your_post_detail_view', category.name)

    else:
        form = CategoryForm()

    return render(request, 'main/add_category.html', {'form':form})

1 个答案:

答案 0 :(得分:2)

如果您尚未创建帖子页面的视图,然后传递创建的对象的ID。

post = form.save(commit=True)
return redirect('your_post_detail_view', post.id)