使用过滤器 Django/python 查询数据
Posted
技术标签:
【中文标题】使用过滤器 Django/python 查询数据【英文标题】:Query data using filter Django/python 【发布时间】:2021-12-19 19:07:05 【问题描述】:我对 Django 后端框架还很陌生。我已经能够轻松地查询数据,但现在我正在尝试过滤该数据。当我运行应用程序时,它将加载登录页面和其他页面,但是当我尝试导航到 FRReports 页面时,我得到了
"模板渲染时出错 在模板 C:\Users\n9177d\webdart\DjangoWebProject1\DjangoWebProject1\webdart\templates\webdart\base.html 中,第 16 行出错
'webdart' 不是注册的命名空间"
有什么想法或指导吗?
urls.py
from django.urls import path, include
from . import views
from webdart.views import AboutView
from django.contrib import admin
admin.autodiscover()
# Use '' to default to the home page
urlpatterns = [
path('', views.landing, name='webdart-landing'),
path('admin/', admin.site.urls),
path('home/', views.home, name='webdart-home'),
path('data/', views.data, name='webdart-data'),
path('data/stationData/', views.data_stationData, name='webdart-data_stationData'),
path('data/obscura/', views.data_obscura, name='webdart-data_obscura'),
path('data/tiz/', views.data_tiz, name='webdart-data_tiz'),
path('data/mcv/', views.data_mcv, name='webdart-data_mcv'),
path('data/viewer/', views.data_viewer, name='webdart-data_viewer'),
path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'),
path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'),
path('FRReports/', views.DocRepositoryListView.as_view(), name='webdart-documents_FRReports'),
path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports'),
#path('FRReports/', views.documents_FRReports, name='webdart-documents_FRReports'),
path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'),
。 . .
views.py
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, DetailView
from webdart.models import Person, DocRepository
from webdart.filters import DocRepositoryFilter
class DocRepositoryListView(ListView):
model = DocRepository
template_name = 'webdart/FRReports.html'
def get_context_data (self, **kwargs):
context = super().get_context_data(**kwargs)
context['filter'] = DocRepositoryFilter(self.request.GET, queryset=self.get_queryset())
return context
class documents_FRReports(DetailView):
model = DocRepository
template_name = 'webdart/FRReports.html'
# Create your views here.
def landing(request):
return render(request, 'webdart/landing.html')
def home(request):
fname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('fname').get()
lname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('lname').get()
phone = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('phone').get()
pdfPath = DocRepository.objects.all()
return render(request, 'webdart/home.html', 'fname': fname, 'lname': lname, 'phone': phone, 'pdfPath': pdfPath, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository")
#return render(request, 'webdart/home.html')
def data(request):
return render(request, 'webdart/data.html')
def data_stationData(request):
return render(request, 'webdart/stationDataHTML.html');
def data_obscura(request):
return render(request, 'webdart/obscuraHTML.html');
def data_tiz(request):
return render(request, 'webdart/tizHTML.html');
def data_mcv(request):
return render(request, 'webdart/mcvHTML.html');
def data_viewer(request):
return render(request, 'webdart/viewerHTML.html');
def data_multiSiteReport(request):
return render(request, 'webdart/multiSiteReport.html');
def documents_antennaBias(request):
pdfPath = DocRepository.objects.all()
viewsPerPage = int(13)
antennaBiasDocs = []
for file in pdfPath:
if file.file_location.split("/")[0] == "RTS Range Bias":
antennaBiasDocs.append(file)
paginator = Paginator(antennaBiasDocs, 13)
page = request.GET.get('page')
contacts = paginator.get_page(page)
test = "reversed"
return render(request, 'webdart/antennaBias.html', 'pdfPath': pdfPath,'test': test, 'contacts': contacts, 'viewsPerPage': viewsPerPage, 'antennaBiasDocs': antennaBiasDocs, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository")
#def documents_FRReports(request):
# return render(request, 'webdart/FRReports.html')
。 . .
filters.py
import django_filters
from webdart.models import DocRepository
class DocRepositoryFilter(django_filters.FilterSet):
class Meta:
model = DocRepository
fields = ('file_location',)
models.py
class DocRepository(models.Model):
doc_repository_id = models.FloatField(primary_key=True)
doc_definition = models.ForeignKey(DocDefinition, models.DO_NOTHING, blank=True, null=True)
upload_date = models.DateField()
title = models.CharField(max_length=255, blank=True, null=True)
date_on_doc = models.DateField()
file_location = models.CharField(max_length=255)
destination_src = models.FloatField(blank=True, null=True)
datetimelu = models.DateField()
useridlu = models.CharField(max_length=255, blank=True, null=True)
is_restricted = models.CharField(max_length=3, blank=True, null=True)
is_deleted = models.CharField(max_length=3, blank=True, null=True)
def __str__(self):
return self.file_location
class Meta:
managed = False
db_table = 'doc_repository'
base.html
% load static %
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link rel="stylesheet" href="% static 'css/main.css' %" />
<meta charset="utf-8">
<title>% block title %WeB DARt% endblock %</title>
<link rel="icon" href="% static 'media/wd.png' %" type="image/x-icon">
<link href="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js"></script>
<div class="CUI_banner_top">CUI</div>
</head>
<body class="test_margin" % block data_status %% endblock %>
<nav class="navbar navbar-expand-md bg_home ">
<div class="container-fluid ">
<div class="">
<div class="row aaa">
<a href="% url 'webdart-home' %"><img src="% static 'media/logo.png' %"></a>
<!-- WeB DARt
<p class="nav_logo ">Web Based Data Analysis and Repository</p>
</div>
-->
</div>
</div>
<button class="navbar-toggler bg-light btn-sm py-0" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="text-dark bg-light h6">Menu</span>
</button>
<div class="collapse navbar-collapse px-4 nav_center" id="navbarSupportedContent">
<ul class="navbar-nav me-auto">
<li class="">
<a class="nav-link bg_home px-4 dropdown_hover" aria-current="page" href="% url 'webdart-home' %">Home</a>
</li>
<li class="nav-item">
<a class="nav-link bg_home px-4 dropdown_hover" href="% url 'webdart-data' %">Data</a>
</li>
<div class="collapse navbar-collapse px-4 dropdown show ">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_documents()">Documents</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="% url 'webdart-documents_antennaBias' %">Antenna Bias</a>
<a class="dropdown-item" href="% url 'list' %">F&R Reports</a>
<a class="dropdown-item" href="% url 'webdart-documents_IERSBulletinA' %">IERS Bulletin A</a>
<a class="dropdown-item" href="% url 'webdart-documents_IERSBulletinB' %">IERS Bulletin C</a>
<a class="dropdown-item" href="% url 'webdart-documents_NRF' %">NRF</a>
<a class="dropdown-item" href="% url 'webdart-documents_OCNBandwidth' %">OCN Bandwidth Limits</a>
<a class="dropdown-item" href="% url 'webdart-documents_ONDLC' %">ONDLC</a>
<a class="dropdown-item" href="% url 'webdart-documents_ORL' %">ORL</a>
<a class="dropdown-item" href="% url 'webdart-documents_RAPID' %">RAPID</a>
<a class="dropdown-item" href="% url 'webdart-documents_SystemAvail' %">System Availability</a>
</div>
</div>
<div class=" collapse navbar-collapse px-4 dropdown show">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_schedule()">Schedule</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="% url 'webdart-schedule_launch' %">Launch Schedule</a>
<a class="dropdown-item" href="% url 'webdart-schedule_maintenance' %">Maintenance Schedule</a>
</div>
</div>
<div class=" collapse navbar-collapse px-4 dropdown show test">
<a class="text-light nav-link dropdown-toggle dropdown_hover" href="dev.html" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="overlay_support()">Support</a>
<div class="dropdown-menu navDrop" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="% url 'webdart-support_help' %">Help</a>
<a class="dropdown-item" href="% url 'webdart-support_contact' %">Contact</a>
<a class="dropdown-item"href="% url 'webdart-support_networkRequest' %">Network Request</a>
</div>
</div>
</ul>
</div>
文件
天线偏置
F&R 报告
IERS 公告 A
IERS 公告 C
NRF
OCN 带宽限制
ONDLC
奥尔
迅速的
系统可用性
FRReports.html
% extends 'webdart/base.html' %
% load static %
% block title % WeB DARt - Home % endblock %
% block content %
<div class="container " >
<div class="row" >
<div class="col-md-6 offset-md-4 my-5 ">
<h1 class="text-decoration-underline">
F&R Report Documents
<h1>
</div>
</div>
</div>
<div class="container shadow rounded" >
<div class="row" >
<table id="customers">
<tr>
<th>Title</th>
<th>Upload Date</th>
</tr>
</table>
</div>
filter.form
<ul>
% for element in filter.qs %
<li>
<a href="% url 'webdart:detail' element.id %">a element.file_location </a>
</li>
% endfor %
</ul>
</div>
% endblock %
【问题讨论】:
这会有所帮助,***.com/questions/41883254/… 【参考方案1】:很遗憾,我无法让它与最初使用的代码一起工作。我能够在 views.py 中进行过滤:
"""
Views for webdart.
"""
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView, ListView, DetailView
from webdart.models import Person, DocRepository
from webdart.filters import DocRepositoryFilter
def docRepo(request):
pdfPath = DocRepository.objects.all().order_by('-date_on_doc')
if request.method == "GET" and len(request.get_full_path().split("?")) > 1 and "page" not in request.get_full_path().split("?")[1]:
if "choice=date_newToOld" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("?"))
pdfPath = DocRepository.objects.all().order_by('-date_on_doc')
elif "choice=date_oldtoNew" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("?"))
pdfPath = DocRepository.objects.all().order_by('date_on_doc')
elif "choice=date_range" in request.get_full_path().split("?")[1]:
print(request.get_full_path().split("&"))
greaterThanDate = request.get_full_path().split("&")[1].split("=")[1]
lessThanDate = request.get_full_path().split("&")[2].split("=")[1]
print("----------------" + greaterThanDate + lessThanDate)
pdfPath = DocRepository.objects.all().filter(date_on_doc__lte=lessThanDate)
pdfPath = pdfPath.filter(date_on_doc__gte=greaterThanDate)
pdfPath = pdfPath.order_by("-date_on_doc")
viewsPerPage = int(13)
antennaBiasDocs = []
for file in pdfPath:
if file.file_location.split("/")[0] == "F and R Reports":
antennaBiasDocs.append(file)
paginator = Paginator(antennaBiasDocs, 13)
page = request.GET.get('page')
contacts = paginator.get_page(page)
return render(request, 'webdart/FRReports.html', 'pdfPath': pdfPath, 'contacts': contacts, 'viewsPerPage': viewsPerPage, 'antennaBiasDocs': antennaBiasDocs, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository")
# Create your views here.
def landing(request):
return render(request, 'webdart/landing.html')
def home(request):
fname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('fname').get()
lname = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('lname').get()
phone = Person.objects.filter(lname='Johnson').filter(fname='Daniel').values('phone').get()
pdfPath = DocRepository.objects.all()
return render(request, 'webdart/home.html', 'fname': fname, 'lname': lname, 'phone': phone, 'pdfPath': pdfPath, 'docPath': "C:/oracleas/j2ee/as_wdintAFTB/AintRepository")
#return render(request, 'webdart/home.html')
def data(request):
return render(request, 'webdart/data.html')
def data_stationData(request):
return render(request, 'webdart/stationDataHTML.html');
def data_obscura(request):
return render(request, 'webdart/obscuraHTML.html');
def data_tiz(request):
return render(request, 'webdart/tizHTML.html');
然后我能够在模板中操作该视图(我在下面创建了一个名为 document_static.html 的模板,因此我可以将它包含在其他文档页面中:
% load static %
<div class="container no_margin" >
<div class="row" >
<div class="pagination d-flex flex-row-reverse">
<span class="step-links ">
% if contacts.has_previous %
<a class="page_button" href="?page=1"><<</a>
<a class="page_button" href="?page= contacts.previous_page_number "><</a>
% endif %
<span class="current">
Page contacts.number of contacts.paginator.num_pages
</span>
% if contacts.has_next %
<a class="page_button" href="?page= contacts.next_page_number ">></a>
<a class="page_button" href="?page= contacts.paginator.num_pages ">>></a>
% endif %
<div class="show filter_div dropup">
<a class="filter_button" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">⩸</a>
<div class="dropdown-menu navDrop filter_drop" aria-labelledby="navbarDropdown">
<p>Sort by:</p>
<form method="GET">
<input type="radio" id="date_newToOld" name="choice" value="date_newToOld" checked/>
<label class="" for="date_newToOld">Date - New to old</label>
<br />
<input type="radio" id="date_oldtoNew" name="choice" value="date_oldtoNew" />
<label for="date_oldtoNew">Date - Old to new</label>
<br />
<input type="radio" id="date_range" name="choice" value="date_range" />
<label class="" for="date_range">Date range</label>
<div class="date_range">
<label class="" for="date_range">Start date</label>
<input type="date" id="start" name="date" value="% now "Y-m-d" %" min="2000-01-01" max="% now "Y-m-d" %">
<label class="" for="date_range">End date</label>
<input type="date" id="start" name="date" value="% now "Y-m-d" %" min="2000-01-01" max="% now "Y-m-d" %">
</div>
</select>
<div class="filter_button_submit_center">
<input class="filter_button_submit" type="submit" value="Filter">
</div>
</form>
</div>
</div>
</span>
</div>
</div>
</div>
<div class="container shadow rounded" >
<div class="row" >
<table id="customers">
<tr>
<th>Title</th>
<th>Upload Date</th>
<th>Comments</th>
</tr>
<tr>
% for o in contacts %
% if 0 < forloop.counter and forloop.counter < viewsPerPage %
<td><a id="open" class="p-0 m-0 fw-bold doc_link"> o.title </a></td>
<td> o.date_on_doc </td>
<td>
<button type="button" class="doc_comments_btn" data-toggle="modal" data-target="#antennaCommentBoxTest forloop.counter0 ">Comments</button>
<div class="modal fade document_comment_modal" id="antennaCommentBoxTest forloop.counter0 ">
<div class="modal-dialog">
<div class="modal-content">
<div style="justify-content: center; display: block;" class="modal-header">
<button type="button" class="doc_comment_close_btn" data-dismiss="modal">×</button>
<h3 id="antennaCommentBoxTest forloop.counter0 "><b style="font-size: 75%;"> o.title - Comments</b></h3>
</div>
<div class="modal-body">
<p class="doc_comment_feed" id="commentFeed">This document has no comments yet.</p>
<form>
<textarea id="newCommentBlock" rows="5" class="doc_comment_textarea" placeholder="Add a Comment" required></textarea>
<br><button type="button" class="doc_comment_submit_btn" onclick="postComment()">Post</button><br>
</form>
</div>
</div>
</div>
</div>
</td>
</tr>
% endif %
% endfor %
</table>
</div>
</div>
这是一个文档页面(IERSBulletinA.html):
% extends 'webdart/base.html' %
% load static %
% block title % WeB DARt - Home % endblock %
% block content %
<div class="container " >
<div class="row " >
<div class="col-md-6 offset-md-4 my-5">
<h1 class="text-decoration-underline">IERS Bulletin A Documents<h1>
</div>
</div>
</div>
% include "webdart/document_static.html" %
% endblock %
这里是任何感兴趣的人的 urls.py:
"""
Definition of urls for webdart.
"""
from django.urls import path, include
from . import views
from webdart.views import AboutView
from django.contrib import admin
from django.views.generic import ListView, DetailView
from django.views import View
from .models import DocRepository
from django.http import HttpResponse
admin.autodiscover()
# Use '' to default to the home page
urlpatterns = [
path('', views.landing, name='webdart-landing'),
path('admin/', admin.site.urls),
path('home/', views.home, name='webdart-home'),
path('data/', views.data, name='webdart-data'),
path('data/stationData/', views.data_stationData, name='webdart-data_stationData'),
path('data/obscura/', views.data_obscura, name='webdart-data_obscura'),
path('data/tiz/', views.data_tiz, name='webdart-data_tiz'),
path('data/mcv/', views.data_mcv, name='webdart-data_mcv'),
path('data/viewer/', views.data_viewer, name='webdart-data_viewer'),
path('data/multiSiteReport/', views.data_multiSiteReport, name='webdart-data_multiSiteReport'),
path('antennaBias/', views.documents_antennaBias, name='webdart-documents_antennaBias'),
path('FRReports/', views.docRepo, name='webdart-documents_FRReports'),
path('IERSBulletinA/', views.documents_IERSBulletinA, name='webdart-documents_IERSBulletinA'),
path('IERSBulletinB/', views.documents_IERSBulletinB, name='webdart-documents_IERSBulletinB'),
path('NRF/', views.documents_NRF, name='webdart-documents_NRF'),
path('OCNBandwidth/', views.documents_OCNBandwidth, name='webdart-documents_OCNBandwidth'),
path('ONDLC/', views.documents_ONDLC, name='webdart-documents_ONDLC'),
path('ORL/', views.documents_ORL, name='webdart-documents_ORL'),
path('RAPID/', views.documents_RAPID, name='webdart-documents_RAPID'),
path('SystemAvail/', views.documents_SystemAvail, name='webdart-documents_SystemAvail'),
path('launch/', views.schedule_launch, name='webdart-schedule_launch'),
path('maintenance/', views.schedule_maintenance, name='webdart-schedule_maintenance'),
path('help/', views.support_help, name='webdart-support_help'),
path('contact/', views.support_contact, name='webdart-support_contact'),
path('networkRequest/', views.support_networkRequest, name='webdart-support_networkRequest'),
path('accountDetails/', views.user_accountDetails, name='webdart-user_accountDetails'),
path('signOut/', views.user_signOut, name='webdart-user_signOut'),
path('timeOut/', views.user_timeOut, name='webdart-user_timeOut'),
path('accountRequest/', views.user_accountRequest, name='webdart-user_accountRequest'),
path('', AboutView.as_view(template_name="data-stationData")),
]
还有来自 models.py 的摘录,因为为什么不呢:
class DocRepository(models.Model):
doc_repository_id = models.FloatField(primary_key=True)
doc_definition = models.ForeignKey(DocDefinition, models.DO_NOTHING, blank=True, null=True)
upload_date = models.DateField()
title = models.CharField(max_length=255, blank=True, null=True)
date_on_doc = models.DateField()
file_location = models.CharField(max_length=255)
destination_src = models.FloatField(blank=True, null=True)
datetimelu = models.DateField()
useridlu = models.CharField(max_length=255, blank=True, null=True)
is_restricted = models.CharField(max_length=3, blank=True, null=True)
is_deleted = models.CharField(max_length=3, blank=True, null=True)
class Meta:
managed = False
db_table = 'doc_repository'
【讨论】:
【参考方案2】:我认为您的错误出现在您的模板标签% url 'webdart:detail' element.id %
中。我相信当你使用% url %
时,你给它的第一个参数是你的urlpatterns 中的路径名。如果您的链接试图进入您的路径:
path('<int:pk>', views.documents_FRReports.as_view(), name='webdart-documents_FRReports')
那么你的模板标签应该是这样的:
% url 'webdart-documents_FRReports' element.id %
【讨论】:
以上是关于使用过滤器 Django/python 查询数据的主要内容,如果未能解决你的问题,请参考以下文章
在ASP.NET Core中通过EF Core实现一个简单的全局过滤查询