2017-02-23 47 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) 
相關問題