我想让用户从列表中选择一个courseName并显示该目录下的所有文件,我该如何实现?我正在努力寻找一种方法来显示特定课程的所有文件。这是我到目前为止所做的:
views.朋友
def showDocuments(request):
if request.POST:
if Document.objects.filter(courses__exact=request.POST["course"]).exists():
print(request.POST["course"])
else:
print("there is no files for this course yet!")
documents = Document.objects.all()
courses = Course.objects.all()
context = {
"documents" : documents ,
"courses" : courses,
}
return render(request , 'dashboard.html' , context )
models.朋友
class Document(models.Model):
#to do : enum class !
DB = "data structure"
SF = "software enginering"
DS = "discrete structure "
WD = "web dev"
OPTIONS = "options"
courseChoices = (
(DB , "data structure"),
(SF , "software enginering "),
(DS , "discrete structure"),
(WD , "web dev"),
(OPTIONS , "options"),
)
courses = models.CharField(max_length=50, choices=courseChoices, default=OPTIONS)
description = models.TextField(help_text="A little description can be very helpful for others!")
document = models.FileField(upload_to=content_file_name)
uploaded_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return "{}".format(self.document)
def content_file_name(self, courses):
file_path = "documents/{courses}/{filename}".format(
courses=self.courses, filename=courses)
return file_path
dashboard.html
<div class="col-sm-4">
<select id="crs" class="custom-select custom-select-sm" name="course">
<option selected>option</option>
{% for obj in courses %}
<option value="{{ obj.courseName }}">{{ obj.courseName }}</option>
{% endfor %}
</select>
</div>
所以这是我如何解决它
def showDocuments(request, *args, **kwargs):
""" shows all the files of the requested course """
crs_names = CoursesNames.objects.all()
context = {
"crs_names": crs_names,
"files": [],
"not_found" : "",
}
if request.POST:
file_name = request.POST["course"]
not_found = "There are no files for {0} yet!".format(file_name)
documents = Document.objects.all().filter(course_name__courses__iexact=file_name)
context["documents"] = documents
context["filename"] = file_name
documentObjectList = Document.objects.all().values_list("document").filter(course_name__courses__iexact=file_name)
queryset = CoursesNames.objects.filter(courses__exact=file_name).exists()
if queryset:
while len(context["files"]) > 0: context["files"].pop()
for i in documentObjectList:
context["files"] = i
print(context["files"])
if len(context["documents"]) == 0: context["not_found"] = not_found
return render(request, 'dashboard.html', context)