我正在尝试使用url标记在include html模板中呈现链接。 我之前已经这样做了,通常它有效,但出于某种原因,这次我无法做到。
我收到NoReverseMatch错误并怀疑它,因为Django首先尝试加载url标记,但我的对象还没有准备好,所以pk为空。我相信,因为动态数据加载需要一些时间,而静态已加载。
如果我将pk设置为固定数字,则网址有效,但我希望动态更改。
错误:
Reverse for 'transaction' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['en/budget/account\\/(?P<pk>[0-9]+)\\/$']
相关网址:
from django.urls import path
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
app_name='budgetapp'
urlpatterns = [
path('', views.index, name='index'),
path('account/<int:pk>/', views.transaction, name='transaction'),
path('account/', views.account, name='account'),
]
相关观点:
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.models import Group
from django.contrib.auth.decorators import login_required, user_passes_test
from .models import *
from .forms import *
def index(request):
context = {}
context['accounts'] = Account.objects.filter(author=request.user)
return render(request, 'budgetapp/index.html', context)
def account(request):
context = {}
context['account'] = get_object_or_404(Account, pk = request.POST['accountPk'])
return render(request, 'budgetapp/account.html', context)
def transaction(request, pk):
context = {}
context['account'] = get_object_or_404(Account, pk = pk)
return render(request, 'budgetapp/addTransaction.html', context)
的index.html:
{% csrf_token %}
<h1>Personal Budget</h1>
<br />
<p>
<label for="accountSelector">Account:</label>
<select required = "" id="accountSelector">
{% for account in accounts %}
<option value="{{account.pk}}">{{account}}</option>
{% endfor %}
</select>
</p>
<hr />
{% include 'budgetapp/account.html' %}
<script>
$(document).ready(function () {
reload();
});
$("#accountSelector").change(function () {
reload();
});
function reload() {
var dictionary = {}
dictionary['csrfmiddlewaretoken'] = $('input[name="csrfmiddlewaretoken"]').val();
dictionary['accountPk'] = $('#accountSelector').val();
$('#accountDiv').load("account/", dictionary);
console.log('Changed account');
}
</script>
account.html:
<div id="accountDiv">
<p>
Name: {{account.name}} Account balance: {{account.balance}} <a href="{% url 'budgetapp:transaction' pk=account.pk %}">Add a transaction</a>
</p>
</div>
如果我将{% url 'budgetapp:transaction' pk=account.pk %}
更改为/budget/account/{{account.pk}}
则可行,但这感觉不对。
我试图提供所有必要的代码,但请告诉我是否有很多或缺少某些东西。
答案 0 :(得分:1)
如果您要使用{% url 'budgetapp:transaction' pk=account.pk %}
,那么account
必须位于模板上下文中。这与您的浏览器动态加载数据无关。在将响应发送到浏览器之前,服务器将呈现整个模板。
使用/budget/account/{{account.pk}}
不会出错,但是如果您查看呈现的HTML,您会看到/budget/account/
,因为{{ account.pk }}
将评估为''
。