开发者

django-comments preview on the current page

I use django-comment and want that preview, form errors show on item's page. I dec开发者_如何转开发ide that better use decorators, write this

def wrap(func):
    def wrapper(request, *args, **kwargs):
        item = Item.objects.get(url=kwargs['url'])
        form = get_form()(item)
        kwargs['form'] = form
            if request.method == 'POST':
            data = request.POST.copy()
            form = get_form()(item, data)
            if form.errors:
               kwargs['form'] = form
            else:    
                post_comment(request, next=None, using=None)
        return func(request, *args, **kwargs)
    return wrapper

but it seems to me not good... can somebody tell how to write better? thanks


The idea of using decorators is that you can avoid writing a lot of code that should mess with your data after it left the funcion. And in this case you're doing especific stuff like using the Item model, so I imagine you're going to use it just once. Anyway...

A way of improve the code its to always pass to kwargs['form'] your form, even if it doesn't has errors, like this:

def wrap(func):
    def wrapper(request, *args, **kwargs):
        item = Item.objects.get(url=kwargs['url'])
        if request.method == 'POST':
            data = request.POST.copy()
            form = get_form()(item, data)
            kwargs['form'] = form
            if not form.errors:
                post_comment(request, next=None, using=None)
        return func(request, *args, **kwargs)
    return wrapper
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜