无法使用方法渲染Django模板

时间:2015-04-09 01:14:30

标签: python html django

我创建了一个名为getData的函数,以便在userInfo方法中减少4个嵌套的“if”语句。结果是毁灭性的。我被页面没有进入我的success.html模板这一事实感到羞辱。如果我将getData方法中的所有内容移回userInfo函数,一切都恢复正常。有没有一个技巧让它工作,所以我可以恢复我的耻辱?

views.py

def userInfo (request):

    # Set maximum to avoid default of 1000 forms.
    UserFormSet = formset_factory (UserForm, formset = BaseUserFormSet, extra = 2, max_num = 5)

    if request.method == 'POST':

        formset = UserFormSet (request.POST)

        if formset.is_valid ():
            location = request.POST ['site']
            data = formset.cleaned_data
            getData (request, data, location)    # ====> Created a function to cut down nested if statement    
    else:
        formset = UserFormSet ()
...


def getData (request, data, location):

    validUser = []
    for form in data:
        username = form.get ('user_name')
        userID = form.get ('user_ID')

        if username and userID:
            n = register (username, userID, location)
            if n.checkDataBase ():
                validUser.append (username)
    if validUser:
        context = {'validUser': validUser}
        return render (request, 'userform/success.html', context)

HTML

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Successfully Added</title>
</head>
<body>
    <h1>User Information:</h1>
    <ul>
        {% for user in validUser %}
            <li>{{ user }}</li>
        {% endfor %}
    </ul>
    <a href="{% url 'adduser' %}">Add more users</a>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

尝试

return getData (request, data, location)

(添加return声明)。

答案 1 :(得分:0)

如果您将getData()更改为:

,是否有效
if validUser:
        context = {'validUser': validUser}
        return request, 'userform/success.html', context

和您的userInfo()

if formset.is_valid ():
            location = request.POST ['site']
            data = formset.cleaned_data
            request, template, context = getData (request, data, location)    # ====> Created a function to cut down nested if statement
            return render (request, template, context)