我正在尝试构建一个django应用程序,它可以让我访问一些包含student(elev)对象的组。我不能让 Elev 对象显示,等等。
Elevi urls.py
from django.conf.urls import url
from . import views
app_name = 'elevi'
urlpatterns = [
#/
url(r'^$', views.index, name = 'index'),
#/Grupe/id
url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect"),
#/Grupe/id/elevi_id
url(r'^grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$', views.elev_individual, name="elev_individual")
]
Elevi views.py
from django.shortcuts import render,get_object_or_404
from .models import Grupa,Elev
def index(request):
toate_grupele = Grupa.objects.all()
context = {"toate_grupele" : toate_grupele}
return render(request,'Elevi/test.html',context)
def connect(request,grupa_id):
grupa = get_object_or_404(Grupa, pk = grupa_id)
return render(request,'Elevi/connect.html',{'grupa':grupa})
def elev_individual(request,elev_id):
elev = get_object_or_404(Elev, pk = elev_id)
return render(request,'Elevi/elev_individual.html',{'elev':elev})
的test.html
{% if toate_grupele %}
<ul>
{% for grupa in toate_grupele %}
<li><a href ="{% url 'elevi:connect' grupa.id %}">{{ grupa.nume_grupa }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>Nu sunt grupe salvate</p>
{% endif %}
connect.html
<h1>{{ grupa.nume_grupa }}</h1>
<h3>Lista Elevi:</h3>
<ul>
{% for elev in grupa.elev_set.all %}
<li><a href="{% url 'elevi:elev_individual' elev.id %}">{{ elev.nume_elev }} {{ elev.prenume_elev }}</a></li>
{% endfor %}
</ul>
elev_individual.html
<p>{{ elev.nume_elev }} {{ elev.prenume_elev }}</p>
答案 0 :(得分:0)
url模式与视图参数
不匹配查看
def index(request): #url pattern don't need any argument
def connect(request,grupa_id): #url pattern needs one argument
def elev_individual(request,elev_id): #requires one argument
URL
url(r'^$', views.index, name = 'index'), # good
url(r'^grupe/(?P<grupa_id>[0-9]+)/$', views.connect, name="connect") #good
如果查看错误消息,elev_individual
在def elev_individual(request,elev_id):
视图方法中需要两个参数。要解决此问题,请删除第二个参数以便
['grupe/(?P<grupa_id>[0-9]+)/(?P<elev_id>[0-9]+)/$']
成为
['grupe/(?P<elev_id>[0-9]+)/$']
或添加另一个参数elev_id
作为视图的第二个参数,使其变为
def elev_individual(request,grupa_id, elev_id):
并根据需要进行过滤