I am using Django 2.0.6. My folder structure is like this:
mysite
mysite
polls
templates
polls
index.html
choice.html
Please consider that all the other files are present. I am not mentioning them here. I have designed a URL in the format of 'polls/question/choice'. Here question is a variable which I am passing as a argument. Now I have designed a Question class in models.py
from django.db import models
from datetime import timedelta
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
def recent_publish(self):
return self.pub_date >= timezone.now() - timedelta(days=1)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Now I have pointed my url mapping like this in polls/urls.py
:
path('<str:ques>/choice/',views.choice,name='choice')
And in the views file my choice function is like this
def choice(request,ques):
for q in Question.objects.all():
if q.question_text == ques:
break
return render(request,'polls/choice.html',{'q':q})
So here I am passing q which is a object of Question class to choice.html
Now here is choice.html
{% for e in q.choice_set.all() %}
<h1>{{e}}</h1>enter code here
And this is error I am getting
In template C:\Users\Nik\Desktop\mysite\polls\templates\polls\choice.html,
error at line 1
Could not parse the remainder: '()' from 'q.choice_set.all()'
1 {% for e in q.choice_set.all() %}
2 <h1>{{e}}</h1>
Is my syntax wrong or something else?
模板不允许方法调用(绝对不允许带参数)。这是故意这样做的,以防止程序员在模板中编写业务逻辑。
你当然可以这样写:
{% for e in q.choice_set.all %}
...
{% endfor %}
由于 Django 模板会自动调用一个可调用对象(注意没有括号)。但我建议你为此在模型层上定义一些东西。
您可以通过在数据库级别执行此操作来进一步增强搜索:
def choice(request,ques):
q = Question.objects.filter(question_text=ques).first()
return render(request,'polls/choice.html',{'q':q})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句