Django - 将这些特定的模型对象传递给一个模板

时间:2016-03-22 06:33:39

标签: django django-views

模型

class Person( models.Model ):
    first_name = models.CharField( max_length=50 )
    last_name = models.CharField( max_length=50 )    

    def __str__(self): 
        return "{0} {1}".format( self.first_name, self.last_name )    

查看功能

def getPersonData(request):
    currPersonData = {}    

    # get current user
    currentUser = request.user
    # create a person object based on who is logged in. 
    person = Person.objects.create(first_name=currentUser.first_name,
                                   last_name=currentUser.last_name) 

    # getting front loaded personMeta, that user CANNOT provide                              
    personDetails = PersonMeta.objects.filter(legal_first_name=currentUser.first_name,
                                              legal_last_name=currentUser.last_name).values()
    # setting hash key for dict 
    currUserKey = "{0} {1}".format(currentUser.first_name, currentUser.last_name)

    # setting dictionary
    # data[currUserKey] = currentUser
    # if person details is not false
    if (personDetails):
        currPersonData[currUserKey] = personDetails    

    return currPersonData    

查看调用函数并将数据返回到模板。

def signup(request):
    currPersonData = getPersonData( request )
    return render( request, '/signup.html/', {'data': sorted( currPersonData.items( ) )}, )    

URL

    url(r'^signup/$', views.signup),    

模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SignUp</title>
</head>
<body>    

    {% for tuple in data %}
    <p>Tuple key: {{ tuple.0 }}</p>
    {% for key, value in tuple.1.0.items %}
        <p>Dict key, value: {{ key }}: {{ value }}</p>
    {% endfor %}
{% endfor %}    


    {% for values in eb %}
        <p>values</p>
    {% endfor %}    

</body>
</html>    

以上所有内容似乎都按照我的预期方式运作。我可以获取我追踪的数据并将其传递给模板。现在我想获取下面模型的所有对象,并将所有这些对象传递给我的'/signup.html/'以及上面传递的内容,这样我就可以开始进行表单处理了。

class Elective( models.Model ):
    elective_title = models.CharField( max_length=100 )
    elective_description = models.CharField( max_length=100 )    

    def __str__(self):
        return "{0}".format( self.elective_title )    

我试过以下 Django Pass Multiple Models to one Template

Refer to multiple Models in View/Template in Django

由于结果不成功,现在我已经在这方面工作了一段时间,我认为我的下一个最佳举措是寻求帮助。

1 个答案:

答案 0 :(得分:2)

您可以在视图的上下文中传递多个模型。在您的视图功能中,例如:

def signup(request):
    currPersonData = getPersonData( request )
    return render( request, '/signup.html/', {
        'data': sorted( currPersonData.items( ) ),
        'electives': Elective.objects.all(),
    })