我的目标是创建超链接,该超链接将把一个关键字扔进一个views函数中,然后将查询从我的数据库拉到页面上。
目标:按超链接,这将向我查询特定专业。
我试图使用转换器, 所以目标是,1是第一步,3是最后一步。 这可能吗?
1) Click the hyperlink -> Major = Accounting
2)URL.py
path(<str:Accounting/, views.Major, name=Major)
3)Views.py
def Major(request, Accounting):
major_choice = professor.objects.filter(Major = Accounting)
return render(request, 'locate/major.html', {'major_choice': major_choice})
注意:我将变量替换为希望包含“ Accounting”的变量,您会在底部views.py内部注意到它称为“ Major”。
Index.html
<a href="{% url 'locate:Major' 'Accounting' %}">Accounting</a>
major.html
<ul>
{% for major in major_choice %}
<li>{{major.ProfessorName}}</li>
{%endfor%}
</ul>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('<str:Major/', views.Major, name='Major')
]
models.py
from django.db import models
class professor(models.Model):
ProfessorIDS = models.IntegerField()
ProfessorName = models.CharField(max_length=100)
ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
NumberofRatings = models.CharField(max_length=50)
Major = models.CharField(max_length=50)
def __str__(self):
return self.ProfessorName
views.py
from django.http import HttpResponse
from django.shortcuts import render
from .models import professor
def index(request):
professors = professor.objects.all()
return render(request, 'locate/index.html', {'professors': professors})
def Major(request, major):
major_choice = professor.objects.filter(Major = major)
return render(request, 'locate/major.html', {'major_choice': major_choice})
答案 0 :(得分:1)
请将您的网址路径更新为此:
path('<str:Major>/', views.Major, name='Major')
在您的html中:
<a href="{% url 'Major' 'Accounting' %}">Accounting</a>
观看次数:
def Major(request, Major):
....