上下文字典未在视图中传递

时间:2019-02-26 22:16:47

标签: django-templates django-views

好的,我一直在互联网上寻找解决方案,以解决一些明显的问题,尽管我很想念,但到目前为止还不好。

我目前无法通过我的视图将上下文词典传递给Django中的模板。到目前为止,除我要传递给模板的字典外,其他所有内容似乎都将返回。

def search_subjects(request):
"""
This is our search view, at present it collects queries relating to:
    - Subject ID
    - Study Name
    - Date Range Start
    - Date Range Start
Then validates these entries, after which it redirects to the search
results view.
:param request:
:return: Redirect to search results if search button is pressed and form fields
are valid or renders this view again if this request is not POST
"""

if request.method == 'POST':
    form = SearchForm(request.POST)
    if form.is_valid():
        search_dict = {}
        search = form.save(commit=False)
        search.subject_search = request.POST['subject_search']
        search.study_search = request.POST['subject_search']
        if request.POST['date_range_alpha'] and \
                dateparse.parse_datetime(request.POST['date_range_alpha']):

            search.date_range_alpha = request.POST['date_ranch_alpha']
        else:
            search.date_range_alpha = EPOCH_TIME
        if request.POST['date_range_omega'] and \
                dateparse.parse_datetime(request.POST['date_range_omega']):
            with_tz = dateparse.parse_datetime(request.POST['date_range_omega'])
            search.date_range_omega = with_tz
        else:
            search.date_range_omega = timezone.now()

        search.save()

        for k, v in form.data.items():
            search_dict[k] = v
        print(search_dict)
        return render(request, 'dicoms/search_results.html', search_dict)
else:
    form = SearchForm()

return render(request, 'dicoms/search.html', {'form': form})

还有我的模板在这里:

!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search Results</title>
</head>
<body>
Here's what you searched for:
<div>{{ search_dict }}</div>
</body>
</html>

我要返回的页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search Results</title>
</head>
<body>
Here's what you searched for:
<div></div>

</body>
</html>

我到底在这里想念什么?

1 个答案:

答案 0 :(得分:0)

好吧,所以我走了一点,设法解决了。我没有正确传递上下文字典。修复如下所示:

            search.save()
            context = {'search': search}
            return render(request, 'dicoms/search_results.html', context)

相应地调整模板:

Here's what you searched for:
<div>{{ search.subject_search }}</div>
<div>{{ search.study_search }}</div>
<div>{{ search.date_range_alpha }}</div>
<div>{{ search.date_range_omega }}</div>

结果:

Here's what you searched for:
<div>herp </div>
<div>herp </div>
<div>Jan. 1, 1970, midnight</div>
<div>Feb. 26, 2019, 11:05 p.m.</div>

如果我信任django,并且只是在一开始就通过了整个搜索对象,那我就不会在这里结束了。但是你生活和学习。