Django URL正则表达式复杂化

时间:2014-08-05 08:54:22

标签: python regex django url

我无法定义django应用的网址。

我想要它,以便在我输入时

http://example.com/post/3 ::我可以阅读帖子

http://example.com/post/3/edit ::我可以编辑帖子

目前,我将其定义如下:

url(r'^post/(?P<id>\d+)/edit/$',
    'board.views.edit_post',
    name='edit_post'),

url(r'^post/(?P<id>\d+)',
    'board.views.view_post',
    name='view_post'),

然而,这似乎不起作用,因为当我点击我的&#34;编辑&#34;链接到

的链接

&#34; / post / {{post.id}} / edit&#34;

我在地址栏中找到了预定的网址但未被带到编辑视图...

===================================

- 编辑 -

@login_required
def edit_post(request, id):
    if id:
        post = get_object_or_404(Post, id=id)
        if post.owner_user != request.user:
            return HttpResponseForbidden()
#     else:
#         post = Post(owner_user=request.user)

    if request.POST:
        form = PostEditForm(request.POST)
        if form.is_valid():
            form.save() 

            return HttpResponseRedirect('')
    else:
        form = PostEditForm()

    return (request,'edit_post.html', {
        'form': form})

并且

def view_post(request, id):   
    #context = RequestContext(request)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.owner = request.user
            form.parent_post = get_object_or_404(Post, id=id)
            form.comment_type = 0
            form.save()

            return HttpResponseRedirect('')
    else:
        form = CommentForm()

    return render(request,'view_post.html', {
        #'comment' : get_object_or_404(Comment, parent_post = id),
        'comment': Comment.objects.filter(parent_post=id),
        'form': form,
        'post': get_object_or_404(Post, id=id)
    })

1 个答案:

答案 0 :(得分:0)

嗯,我建议你开始使用基于类的视图,此外,为什么不呢。可以让你的生活更轻松,大部分时间,而你写得更少

class UpdatePost(UpdateView):
    model = Post # assuming you've made from your_app.models import Post call already
    fields = ['title', 'content', 'pub_date'] # for demonstration purposes
    template_name = 'post_form.html'

    @method_decorator(login_required) #Use login required on your dispatch method
    def dispatch(self, request, *args, **kwargs):
        pulled = Post.objects.get(id=kwargs['id']) 
        if pulled.created_by == request.user: #just to verify person making edit is rightly disposed to do so
            return super(UpdatePost, self).dispatch(request, *args, **kwargs)
        raise PermissionDenied

甜蜜地拦截你网址中的id

url(r'^app/edit/(?P<id>\d+)/$', views.UpdatePost.as_view(), name='edit'),

我是怎么做的。我从我的工作项目github.com/seanmavley/menpha.git中提取了这个,但还没有测试过这个经过调整的版本。但它应该有用。