0

我有一个

class Questions(models.Model):
    question = models.CharField(max_length=150)
    created_by = models.CharField(max_length=30)
    def __unicode__(self):
        return self.question

现在我需要这样的输出(所以我可以像 djangos 一样使用它{{ form.as_p }}):

<div id="question-1">The string in question"</div>
<div id="question-2">The string in another question"</div>
...

随着loq = Questions.objects.filter(created_by=user)[<Questions: My first question!>,...]进去str(loq)

有比使用搜索更简单的方法str(loq).find()

编辑:

以这种方式解决它(感谢Samuele Mattiuzzo):

模型.py:

class Questions(models.Model):
    question = models.CharField(max_length=150)
    created_by = models.ForeignKey(User)
    def __unicode__(self):
        return self.question

视图.py:

def ViewQuestions(request):
    if request.user.is_authenticated():
        loq = Questions.objects.filter(created_by=request.user)

        return render(request, "main/questions.html", {'loq': loq})
    else:
        return HttpResponseRedirect("/")

问题.html:

{% for q in loq %}
<div id="question-{{ forloop.counter }}">{{ q.question }}</div>
{% endfor %}
4

1 回答 1

1

像这样创建一个模板文件(比如 questions.html):

{% for q in loq %}
    <div id="question-{{ forloop.counter }}">{{ q.question }}</div>
{% endfor %}

在你的views.py中,你必须返回你的查询集(这是你的loq)

def view_questions(response, user):
    loq = Questions.objects.filter(created_by=user)
    return render_to_response(
        'questions.html',
        locals(),
        context_instance=RequestContext(request)
    )

locals() 是包含你的 loq 的字典。在这里我假设你已经知道 django 是如何工作的。我真的不明白你所说的“.find()”声明是什么意思。

您可能还想将 created_by 字段从 CharField 更改为 ForeignKey 指向 User 类

检查有关查询集视图的文档以获取有关该主题的更多知识。

如果这没有回答,请提供更多解释,我将更新答案

于 2012-12-12T10:23:43.153 回答