Получение представления на основе pk с помощью шаблона url
Привет. У меня небольшая проблема с получением URL с переданным аргументом (pk). Я получаю ошибку, в которой я получаю post_edit, что связано с другим приложением сайта, поэтому в качестве шаблона он пытался использовать:
NoReverseMatch at /questions/question/5/ Reverse for 'post_edit' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['blog/post/(?P[0-9]+)/edit/$']
Почему он не передает pk в questions_list.html в цикле for?
urls.py
from django.urls import path
from django.conf.urls import url
from . import views
urlpatterns = [
path('', views.questionMain_view, name='questionMain_view'),
path('postQ/', views.postQ_view, name='postQ_view'),
path('all/', views.displayQ_view, name='displayQ_view'),
path('question/<int:pk>/', views.question_detail_view, name='question_detail_view'),
]
questions_list.html
{% extends 'questions_page/base_questions.html' %} {% load i18n %} {% block title %} {% translate 'Questions Main' %} {% endblock %} {% block content %} <h1>{% translate 'Questions display' %}</h1> <br> {% for question in questions %} <div> <div class="date"> {{ question. published_date }} </div> <h1><a href="{% url 'question_detail_view' question.pk %}">{{ question.title }}</a></h1> <p>{{ question.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %}
questions_detail.html
{% extends 'questions_page/base_questions.html' %} {% load i18n %} {% block title %} {% translate 'Questions detail' %} {% endblock %} {% block content %} <h1>{% translate 'Questions detail' %}</h1> <br> <div> {% if question.published_date %} <div class="date"> {{ question.published_date }} </div> {% endif %} {% if user.is_authenticated %} <!-- <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> --> {% endif %} <h1>{{ question. title }}</h1> <p>{{ question.text|linebreaksbr }}</p> </div> {% endblock %}
viws.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required, user_passes_test
from django.utils import timezone
from .forms import ImageForm, QuestionForm
from .models import Image, Question
# Create your views here.
@user_passes_test(lambda u: u.groups.filter(name='Premium').count() > 0)
@login_required
def questionMain_view(request):
return render(request, 'questions_page/questions_main.html')
@user_passes_test(lambda u: u.groups.filter(name='Premium').count() > 0)
@login_required
def postQ_view(request):
if request.method == 'POST':
questionForm = QuestionForm(request.POST, request.user)
img_form = ImageForm(request.POST, request.FILES)
if questionForm.is_valid() and img_form.is_valid():
question_obj = questionForm.save(commit=False)
question_obj.user = request.user
question_obj.save()
for img in request.FILES.getlist('images'):
Image.objects.create(image=img, question=question_obj)
return redirect('postQ_view')
questionForm = QuestionForm()
img_form = ImageForm(request.POST, request.FILES)
return render(request, 'questions_page/postQ.html', {"questionForm":questionForm, "img_form": img_form})
def displayQ_view(request):
questions = Question.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'questions_page/questions_list.html', {'questions' : questions})
def question_detail_view(request, pk):
question = get_object_or_404(Question, pk=pk)
return render(request, 'questions_page/question_detail.html', {'question': question})
вот причина ошибки
в вашем шаблоне questions_detail.html
у вас есть такой код
{% if user.is_authenticated %}
<!-- <a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> -->
% endif %}
измените его на
{% if user.is_authenticated %}
{% comment %}<a class="btn btn-default" href="{% url 'post_edit' pk=post.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> {% endcomment %}
{% endif %}
Теги <!---->
не комментируют код django, а комментируют только html
но мы используем {% comment %} {% endcomment %}
, чтобы закомментировать код django в html-шаблоне
для получения дополнительной информации о том, как комментировать в django framework, посетите официальную документацию django