2017-02-23 48 views
-4

我开始学习Django 1.10,但它使用1.6中的例子。这就是为什么我在新版本中遇到语法问题。在Django 1.10中,args的正确语法是什么?

这是我的函数:

def article(request, article_id=1): 
    comment_form = CommentForm 
    @csrf_protect 
    args = {} 
    args['article'] = Article.objects.get(id=article_id) 
    args['comments'] = Comments.objects.filter(comments_artile_id=article_id) 
    args['form'] = comment_form 
return render (request, 'articles.html', args) 

而且我回溯:

File "/home/goofy/djangoenv/bin/firstapp/article/views.py", line 30 

args = {}  
    ^
SyntaxError: invalid syntax 

请告诉我什么是正确的语法或者在哪里可以找到答案,因为我无法找到任何Django Docs中的解释。

+1

试着把'@ csrf_protect'放在函数的上面。 – flowfree

+0

你是对的,这是一个错误。谢谢 –

+1

@AlexeyG欢迎来到StackOverflow!如果您的问题已解决,请选择标记为已接受的答案,并向您发现任何您认为有用的答案。这有助于后来知道哪些答案是最有帮助的人,也可以奖励那些竭尽全力帮助你的人。 –

回答

0

默认情况下,CSRF Protect处于开启状态,如果要使用装饰器,则需要将其放在documentation say之类的方法之前。

CommentForm是在你的forms.py对象(我想)你需要给他打电话就像CommentForm()

@csrf_protect 
def article(request, article_id=1): 
    comment_form = CommentForm() 
    args = {} 
    args['article'] = Article.objects.get(id=article_id) 
    args['comments'] = Comments.objects.filter(comments_artile_id=article_id) 
    args['form'] = comment_form 
    return render (request, 'articles.html', args) 

但是你可以做很容易,Django的创建与相关的名称例如字典: {{ article }}在template.html中的名称和对象/变量在您的wiews.py a(谁是Comments.objects.filter(comments_artile_id=article_id))。

@csrf_protect 
def article(request, article_id=1): 
    form = CommentForm() 
    a = Article.objects.get(id=article_id) 
    c = Comments.objects.filter(comments_artile_id=article_id) 
    return render (request, 'articles.html', { 
       'article': a, 
       'comments': c, 
       'comment_form': form}) 
1

@csrf_protectpython decorator。把它放在方法定义的上面以便工作。 另外,return行必须像方法体的其余部分一样缩进。

@csrf_protect 
def article(request, article_id=1): 
    comment_form = CommentForm() 
    args = {} 
    args['article'] = Article.objects.get(id=article_id) 
    args['comments'] = Comments.objects.filter(comments_artile_id=article_id) 
    args['form'] = comment_form 
    return render (request, 'articles.html', args) 
相关问题