【问题标题】:What is the right syntax for args in Django 1.10?Django 1.10 中 args 的正确语法是什么?
【发布时间】:2017-07-14 02:57:18
【问题描述】:

我开始研究 Django 1.10,但它使用了 1.6 上的示例。这就是我在新版本中遇到语法问题的原因。

这是我的功能:

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 中找不到任何解释。

【问题讨论】:

  • 尝试将@csrf_protect放在函数上方。
  • 你是对的,这是一个错误。谢谢
  • @AlexeyG 欢迎来到 StackOverflow!如果您的问题已解决,请选择一个答案以标记为已接受,并为您认为有帮助的任何内容点赞。这有助于后来的人知道哪些答案最有帮助,同时也奖励那些竭尽全力帮助你的人。

标签: python django


【解决方案1】:

@csrf_protect 是一个python 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)

【讨论】:

    【解决方案2】:

    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})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-26
      • 2014-04-19
      • 2018-11-14
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多