【问题标题】:Python Django Error during template rendering模板渲染期间的 Python Django 错误
【发布时间】:2021-11-24 07:54:31
【问题描述】:

让我快速解释一下我要做什么。

所以我正在制作一个基于 Django 的小型会议管理,其中可以有多个会议,一个会议可以有多个演讲,每个演讲会有一定数量的演讲者和参与者。

我可以列出会议并提供删除和编辑会议的选项。

问题:

我想要一个选项,我点击一个会议,它会显示该会议的会谈列表。 但是当我点击会议时它显示以下错误。

NoReverseMatch at /Big Data/talks/
Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$']
Request Method: GET
Request URL:    http://127.0.0.1:8000/Big%20Data/talks/
Django Version: 3.2.4
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'conferenceedit' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<id>[^/]+)/edit$']
Exception Location: E:\python\PYTHON and GIT\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix
Python Executable:  E:\python\PYTHON and GIT\python.exe
Python Version: 3.9.1
Python Path:    
['D:\\DjangoConferenceManagementSystem\\mysite',
 'E:\\python\\PYTHON and GIT\\python39.zip',
 'E:\\python\\PYTHON and GIT\\DLLs',
 'E:\\python\\PYTHON and GIT\\lib',
 'E:\\python\\PYTHON and GIT',
 'C:\\Users\\AKS\\AppData\\Roaming\\Python\\Python39\\site-packages',
 'E:\\python\\PYTHON and GIT\\lib\\site-packages',
 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\pip-21.0.1-py3.9.egg',
 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32',
 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\win32\\lib',
 'E:\\python\\PYTHON and GIT\\lib\\site-packages\\Pythonwin']
Server time:    Sun, 03 Oct 2021 15:47:10 +0000

我已包含以下代码来支持该论点。

模型.PY

from django.db import models
from django.db.models.fields import CharField
from django.utils import timezone
# Create your models here.

class ConferenceModel(models.Model):
    conference_title = models.TextField(null=False,primary_key=True)
    conference_description = models.CharField(max_length=1000,null=False)
    conference_start_date = models.DateField(null=False)
    conference_end_date = models.DateField(null=False)

class TalkModel(models.Model):
    talk_conference_title  = models.ForeignKey(ConferenceModel,on_delete=models.CASCADE)
    talk_title = models.TextField(null=False,primary_key=True)
    talk_description =  models.CharField(max_length=100,null=False)
    talk_duration = models.DecimalField(max_digits=2,decimal_places=1)
    talk_time = models.DateTimeField(null=False)

class SpeakerModal(models.Model):
    speaker_talk_title = models.ForeignKey(TalkModel,on_delete=models.CASCADE)
    speaker_username = models.CharField(max_length=25,null=False)
    speaker_email = models.EmailField(max_length=100,primary_key=True,null=False)

class ParticipantModel(models.Model):
    participant_talk_title = models.ForeignKey(TalkModel,on_delete=models.CASCADE)
    participant_username = models.CharField(max_length=25,null=False)
    participant_email = models.EmailField(max_length=100,primary_key=True,null=False) 

URLS.PY

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('',views.conferenceView,name='conference'),
    path('delete/<str:id>',views.conferencedelete,name='conferencedelete'),
    path('<str:id>/edit',views.conferenceedit,name='conferenceedit'),
    path('<str:id>/talks/',views.talkView,name='talks'),
    path('admin/', admin.site.urls),
]
 

VIEWS.PY

from django.shortcuts import render
from django import forms
from django.shortcuts import render,HttpResponsePermanentRedirect,HttpResponse
from myapp.forms import ConferenceForm,TalkForm,SpeakerForm,ParticipantForm
from myapp.models import ConferenceModel,TalkModel,SpeakerModal,ParticipantModel
# Create your views here.

def conferenceView(request):
    if request.method == 'POST':
        conferenceform = ConferenceForm(request.POST)
        if conferenceform.is_valid():
            conferenceform.save()
            conferenceform = ConferenceForm()  
    else:
        conferenceform = ConferenceForm()
    conference = ConferenceModel.objects.all()
    return render(request,'myapp/conference.html',{'conference':conference,'conferenceform':conferenceform})

def conferenceedit(request,id):
    if request.method == 'POST':
        uniqueconferencetitle = ConferenceModel.objects.get(pk=id)
        requestconferencedetails = ConferenceForm(request.POST,instance=uniqueconferencetitle)
        if requestconferencedetails.is_valid():
            requestconferencedetails.save()
            return HttpResponsePermanentRedirect('/')
    else:
        uniqueconferencetitle = ConferenceModel.objects.get(pk=id)
        requestconferencedetails = ConferenceForm(instance=uniqueconferencetitle)
    return render(request,'myapp/conferenceedit.html',{'requestconferencedetails':requestconferencedetails})
    

def conferencedelete(request,id):
    if request.method == 'POST':
        conferencedelete = ConferenceModel.objects.get(pk=id)
        conferencedelete.delete()
        return HttpResponsePermanentRedirect('/')

def talkView(request,id):
    talk = ConferenceModel.objects.get(pk=id)
    conferencetalks = talk.talkmodel_set.all()
    return render(request,'myapp/talks.html',{'conferencetalks':conferencetalks})

FORMS.PY

from django import forms
from django.db import models
from django.db.models import fields
from django.forms import widgets
from myapp.models import ConferenceModel,TalkModel,SpeakerModal,ParticipantModel

class ConferenceForm(forms.ModelForm):
    class Meta:
        model = ConferenceModel
        fields = ['conference_title','conference_description','conference_start_date','conference_end_date']
        widgets = {
            'conference_title' : forms.TextInput(attrs={'class':'form-control '}),
            'conference_description' : forms.TextInput(attrs={'class':'form-control'}),
            'conference_start_date' : forms.TextInput(attrs={'class':'form-control','placeholder':'YYYY-MM-DD'}),
            'conference_end_date' : forms.TextInput(attrs={'class':'form-control','placeholder':'YYYY-MM-DD'})
        }

class TalkForm(forms.ModelForm):
    class Meta:
        model = TalkModel
        fields = ['talk_conference_title','talk_title','talk_description','talk_duration','talk_time']
        widgets = {
            'talk_conference_title' : forms.HiddenInput,
            'talk_title' : forms.TextInput(attrs={'class':'form-control '}),
            'talk_description' : forms.TextInput(attrs={'class':'form-control '}),
            'talk_duration' : forms.TextInput(attrs={'class':'form-control '}),
            'talk_time' : forms.TextInput(attrs={'class':'form-control '}),
        }

class SpeakerForm(forms.ModelForm):
    class Meta:
        model = SpeakerModal
        fields = ['speaker_talk_title','speaker_username','speaker_email']
        widgets = {
            'speaker_talk_title' : forms.HiddenInput, 
            'speaker_username' : forms.TextInput(attrs={'class':'form-control '}),
            'speaker_email' : forms.TextInput(attrs={'class':'form-control '})
        }

class ParticipantForm(forms.ModelForm):
    class Meta:
        model = ParticipantModel
        fields = ['participant_talk_title' , 'participant_username' , 'participant_email']
        widgets = {
            'participant_talk_title' : forms.HiddenInput,
            'participant_username' : forms.TextInput(attrs={'class':'form-control '}),
            'participant_email' : forms.TextInput(attrs={'class':'form-control '})
        }

会议.HTML

{% extends 'myapp/base.html' %}

{% block content %}
<div class="col-sm-5 container">
    <h4 class="alert alert-info">Add a new conference</h4>
    <form class="form-control" method="POST">
    {% csrf_token %}
    {{ conferenceform }}
    <p></p>
    <input type="submit" class="btn btn-success " value="ADD" id="add">
</form>
</div>
<div class="container mt-3">
    <h4 class="alert alert-info text-center">
        Here is the list of confrences
    </h4>
    <table class="table table-hover">
        <th class="thead-dark">
            <tr>
                <th scope="col">Title</th>
                <th scope="col">Description</th>
                <th scope="col">Start Date</th>
                <th scope="col">End Date</th>
                <th scope="col">Options</th>
            </tr>
        </th>
            {% for conferences in conference %}
            <tr>
                <th scope="col"><a href="{% url 'talks' conferences.conference_title %}">{{conferences.conference_title}}</a></th>
                <th scope="col">{{conferences.conference_description}}</th>
                <th scope="col">{{conferences.conference_start_date}}</th>
                <th scope="col">{{conferences.conference_end_date}}</th>
                <td>
                    <a href="{% url 'conferenceedit' conferences.conference_title %}" class="btn btn-danger btn-sm">Edit</a>
                    <form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
                        {% csrf_token %}
                        <input type="submit" value="Delete" class="btn btn-danger btn-sm">
                    </form>
                </td>
            </tr>
            {% endfor %}
    </table>
</div>
{% endblock content %}

TALKS.HTML

{% extends 'myapp/base.html' %}

{% block content %}
<div class="container mt-3">
    <h4 class="alert alert-info text-center">
        Here is the list of Talks under this conference 
    </h4>
    <table class="table table-hover">
        <th class="thead-dark">
            <tr>
                <th scope="col">Talk Title</th>
                <th scope="col">Talk Description</th>
                <th scope="col">Talk Duration </th>
                <th scope="col">Talk Time</th>
                <th scope="col">Options</th>
            </tr>
        </th>
            {% for talkss in conferencetalks %}
            <tr>
                <th scope="col">{{talkss.talk_title}}</th>
                <th scope="col">{{talkss.talk_description}}</th>
                <th scope="col">{{talkss.talk_duration}}</th>
                <th scope="col">{{talkss.talk_time}}</th>
                <!-- <td>
                    <a href="{% url 'conferenceedit' conferences.conference_title %}" class="btn btn-danger btn-sm">Edit</a>
                    <form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
                        {% csrf_token %}
                        <input type="submit" value="Delete" class="btn btn-danger btn-sm">
                    </form>
                </td> -->
            </tr>
            {% endfor %}
    </table>
</div>
{% endblock content %}

【问题讨论】:

  • 错字:在talks.html 中你写{% url 'conferenceedit' conferences.conference_title %} 但循环变量是talkss... 即它应该是{% url 'conferenceedit' talkss.conference_title %}(注意:请一致且更好地命名事物,不要反转单数和复数,可以防止此类错误)

标签: python django django-models django-forms django-templates


【解决方案1】:

您通过将项目命名为 conferences 来循环访问您的 queryset

所以要访问 Id,因为 URL 需要一个 id。看看这个path('&lt;str:id&gt;/edit',views.conferenceedit,name='conferenceedit'),

你需要这样做:

{% url 'conferenceedit' conferences.id %}

或者

{% url 'conferenceedit' conferences.pk %}

附言。通过将 '&lt;str:id&gt; 更新为 '&lt;int:id&gt; 来改进您的路径,因为您的模型是整数。

【讨论】:

  • 问题似乎出在talks.html上,conferenceedit工作正常,我可以编辑当前的会议,但是当我点击一个会议以检查该会议下的谈话时,就会出现这个错误出现。
【解决方案2】:

urls.py

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
    path('',views.conferenceView,name='conference'),
    path('delete/<int:id>',views.conferencedelete,name='conferencedelete'),
    path('<int:id>/edit',views.conferenceedit,name='conferenceedit'),
    path('<int:id>/talks/',views.talkView,name='talks'),
    path('admin/', admin.site.urls),
]

talks.html

{% extends 'myapp/base.html' %}

{% block content %}
<div class="container mt-3">
    <h4 class="alert alert-info text-center">
        Here is the list of Talks under this conference 
    </h4>
    <table class="table table-hover">
        <th class="thead-dark">
            <tr>
                <th scope="col">Talk Title</th>
                <th scope="col">Talk Description</th>
                <th scope="col">Talk Duration </th>
                <th scope="col">Talk Time</th>
                <th scope="col">Options</th>
            </tr>
        </th>
            {% for talkss in conferencetalks %}
            <tr>
                <th scope="col">{{talkss.talk_title}}</th>
                <th scope="col">{{talkss.talk_description}}</th>
                <th scope="col">{{talkss.talk_duration}}</th>
                <th scope="col">{{talkss.talk_time}}</th>
                <!-- <td>
                    <a href="{% url 'conferenceedit' talkss.talk_conference_title_id %}" class="btn btn-danger btn-sm">Edit</a>
                    <form action="{% url 'conferencedelete' talkss.talk_conference_title_id %}" method="POST" class="d-inline">
                        {% csrf_token %}
                        <input type="submit" value="Delete" class="btn btn-danger btn-sm">
                    </form>
                </td> -->
            </tr>
            {% endfor %}
    </table>
</div>
{% endblock content %}

conference.html

{% extends 'myapp/base.html' %}

{% block content %}
<div class="col-sm-5 container">
    <h4 class="alert alert-info">Add a new conference</h4>
    <form class="form-control" method="POST">
    {% csrf_token %}
    {{ conferenceform }}
    <p></p>
    <input type="submit" class="btn btn-success " value="ADD" id="add">
</form>
</div>
<div class="container mt-3">
    <h4 class="alert alert-info text-center">
        Here is the list of confrences
    </h4>
    <table class="table table-hover">
        <th class="thead-dark">
            <tr>
                <th scope="col">Title</th>
                <th scope="col">Description</th>
                <th scope="col">Start Date</th>
                <th scope="col">End Date</th>
                <th scope="col">Options</th>
            </tr>
        </th>
            {% for conferences in conference %}
            <tr>
                <th scope="col"><a href="{% url 'talks' conferences.pk %}">{{conferences.conference_title}}</a></th>
                <th scope="col">{{conferences.conference_description}}</th>
                <th scope="col">{{conferences.conference_start_date}}</th>
                <th scope="col">{{conferences.conference_end_date}}</th>
                <td>
                    <a href="{% url 'conferenceedit' conferences.pk %}" class="btn btn-danger btn-sm">Edit</a>
                    <form action="{% url 'conferencedelete' conferences.pk %}" method="POST" class="d-inline">
                        {% csrf_token %}
                        <input type="submit" value="Delete" class="btn btn-danger btn-sm">
                    </form>
                </td>
            </tr>
            {% endfor %}
    </table>
</div>
{% endblock content %}

【讨论】:

  • 将 int 工作,因为我的模型中的主键是字符串类型?
  • @AkshatSharma 在 Django 中最好使用 (int) 作为主键而不是字符串。这是最好的方法。这段代码是否解决了您的问题?
  • 是的,我明白了,我可能需要更改我的模型。
【解决方案3】:

我发现问题出在我的 TALKS.HTML 上,我从 CONFERENCE.HTML 中复制了这个 HTML,但错过了删除以下代码。

<!-- <td>
                    <a href="{% url 'conferenceedit' conferences.conference_title %}" class="btn btn-danger btn-sm">Edit</a>
                    <form action="{% url 'conferencedelete' conferences.conference_title %}" method="POST" class="d-inline">
                        {% csrf_token %}
                        <input type="submit" value="Delete" class="btn btn-danger btn-sm">
                    </form>
                </td> -->

虽然我评论了它,但似乎没有评论,我删除了它,现在它可以工作了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 2017-01-31
    • 2017-05-21
    相关资源
    最近更新 更多