创建Django模型对象时如何解决“ django.urls.exceptions.NoReverseMatch”错误?

时间:2019-03-06 17:38:18

标签: python-3.x twitter-bootstrap-3 django-2.1

我正在尝试创建一个其代码文件在下面的应用程序会议。 当我单击conference_list.html文件中的创建会议按钮时,从附件中可以看到我遇到了一个错误。

控制台中显示错误:

enter image description here

我已在base.html中包含静态文件,并在所有其他app_name_base.html文件中进行了扩展。


chrome浏览器指出的

Culprit线位于会议应用程序的文件views.py中,

返回render(request,'conferences / conference_create.html')

请帮助。文件如下所示:

会议模型。py

from django.db import models
from django.utils.text import slugify
from django.urls import reverse

import misaka

from datetime import date
import datetime
from django.contrib.auth import get_user_model
User = get_user_model()
from django import template
register = template.Library()

class Conference(models.Model):
    name = models.CharField(max_length=255,unique=True)
    poster = models.ImageField(upload_to='images/%Y/%m/%d',blank=True)
    venue = models.CharField(max_length=255,editable=True,default='Online')
    created_at = models.DateTimeField(auto_now_add=True,blank=False)
    conference_on = models.DateTimeField(auto_now_add=True,blank=False)
    registration_till = models.DateField(auto_now_add=False, blank=True)
    audience = models.TextField(blank=True,default='Add your audience type here i.e. "Below 25","Entrepreneurs","Music"')
    description = models.TextField(blank=True,default='Add your event description here i.e. "Coding Event for python developers"')
    slug = models.SlugField(allow_unicode=True, unique=True)
    audience_html = models.TextField(editable=False,default='',blank=True)
    conference_user = models.ForeignKey(User, related_name='User', null=True,on_delete=models.CASCADE)
    members = models.ManyToManyField(User,through="ConferenceMember")
    # Add a company user here


    def __str__(self):
        return self.name

    def save(self,*args,**kwargs):
        self.slug = slugify(self.name)
        self.audience_html = misaka.html(self.audience)
        super().save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('conferences:single',kwargs={"slug": self.slug})

    class Meta:
        ordering = ['name']
    def daysleft(self):
        if datetime.date.today() > self.conference_on.date():
            return False
        else:
            return self.conference_on.date() - datetime.date.today()
    def registration(self):
        if datetime.date.today()  > self.registration_till:
            return False
        else:
            return self.registration_till - datetime.date.today()

    def summary(self):
        return self.description[:100]
    def reg_date_pretty(self):
        return self.registration_till.strftime('%b %e %Y')
    def conf_date_pretty(self):
        return self.conference_on.strftime('%b %e %Y')






class ConferenceMember(models.Model):
    conference = models.ForeignKey(Conference,related_name="memberships",on_delete=models.CASCADE)
    user = models.ForeignKey(User,related_name="user_groups",on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username
    class Meta:
        unique_together = ('conference','user')



    pass

views.py中的会议应用程序“创建”功能

@login_required(login_url = "accounts/signup")
def create(request):
    if request.method == 'POST':
        if request.POST['name'] and request.POST['venue'] and request.POST['registration_till'] and request.FILES['poster']  and request.POST['audience']:
            project = Conference()
            project.name = request.POST['name']
            project.venue = request.POST['venue']
            project.registration_till = request.POST['registration_till']
            project.poster = request.cleaned_data['poster']

            project.audience = request.POST['audience']
            project.created_at = timezone.datetime.now()
            project.conference_user = request.user
            project.save()
            return redirect('conferences/event/in/' + str(project.slug))
        else:
            return render(request , 'conferences/conference_create.html',{'error':'All fields are required.'})
    else:
        return render(request , 'conferences/conference_create.html')

会议urls.py

from django.urls import path
from . import views
app_name="conferences"
urlpatterns=[
    path('',views.ListConferences.as_view(),name='all'),
    # path('event/in/<int:conference_id>',views.SingleConference,name='single'),
    path('event/in/<slug:slug>',views.SingleConference.as_view(),name='single'),
    path('create', views.create , name = 'create'),
    path('join/<slug:slug>',views.JoinConference.as_view(),name="join"),
    path('leave/<slug:slug>',views.LeaveConference.as_view(),name="leave"),
]

会议conference_list.html

{% extends "conferences/conference_base.html" %}
{% block pregroup %}

<div class="row">
  <div class="col-md-4">
    <div class="content profile">
      {% if user.is_authenticated %}

        <h2>Welcome Back
          <a href="{% url 'posts:for_user' username=user.username %}">@{{user.username}}</a>
        </h2>

      {% endif %}

    </div>

  </div>
</div>
{% endblock %}

{% block group_content %}
<a href="{% url 'conferences:create' %}" class="nav-item nav-link btn btn-info btn-lg plus">
  Create Conference
</a>
{% for conference in object_list %}
<div class="row">
  <div class="col-md-2">
    <img src="{{conference.poster.url}}" alt="Image" width=200 height=150>
  </div>
  <div class="col-md-10">
    <div class="list-group">



      <a href="{% url 'conferences:single' slug=conference.slug %}" class="list-group-item">
        <h3 class="title list-group-item-heading">{{conference.name}}</h3>
        <div class="list-group-item-text container-fluid">
          {{conference.audience_html|safe}}
          <div class="row">
            <div class="col-md-4">
              <span class="badge">{{ conference.members.count }}</span> attendy{{ conference.members.count|pluralize }}
              <span class="badge">
                {% if conference.registration %}
                    Hurray conference is in {{conference.daysleft}} days. Registration closes in {{conference.registration}}
                {% else %}
                    Conference was on {{conference.conference_on}}. Visit Post Section on {{conference.name}} Page.
                {% endif %}
              </span>

            </div>
          </div>
        </div>
      </a>
      <br>



    </div>

  </div>

</div>

{% endfor %}
{% endblock %}

conference_create.html

{% extends 'base.html' %}
{% block content %}
{% if error %}
<p class="alert alert-primary" role="alert">{{error}}</p>
<br>
<br>
{% endif %}
<h1>Create your hosted Conference</h1>
<form action="{% url 'conferences:create' %}" method = "POST" enctype = "multipart/form-data">

    {% csrf_token %}
    Name:<br/>
    <input style="background-color:white;
              border: solid 1px #6E6E6E;
              height: 30px;
              font-size:18px;
              vertical-align:9px;color:#bbb" type="text" name = "name" />
    <br/>
    Venue:<br/>
    <input style="background-color:white;
              border: solid 1px #6E6E6E;
              height: 30px;
              font-size:18px;
              vertical-align:9px;color:#bbb" type="textbox" name = "venue" />
    <br/>
    Audience:<br/>
    <input style="background-color:white;
              border: solid 1px #6E6E6E;
              height: 30px;
              font-size:18px;
              vertical-align:9px;color:#bbb" type="textbox" name = "audience" />
    <br/>

    <!-- Registration open till:<br/>
    <input type="date" name = "reg_date" />
    <br/>
    Conference on Date:<br/>
    <input type="date" name = "conf_date" />
    <br/> -->
    Poster:<br/>
    <input type="file" name = "poster" />
    <br/>
    <input type="submit" value = "Create Conference" class = "btn btn-primary"/>
</form>


{%endblock%}

项目urls.py

from django.conf.urls.static import static
from django.contrib import admin
from django.conf import settings
from django.urls import path, include
from . import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.HomePage.as_view(),name = "home"),
    path('accounts/',include('accounts.urls',namespace="accounts")),
    path('accounts/', include("django.contrib.auth.urls")),
    path('thanks/',views.ThanksPage.as_view(),name="thanks"),
    path('conferences/',include('conferences.urls',namespace="conferences")),
    path('companies/',include('companies.urls',namespace="companies")),
    path('posts/',include('posts.urls',namespace="posts")),
    path('profiles/',include('profiles.urls',namespace="profile")),

]
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

编辑和解决方案: 我还添加了经过修改的Conference_create.html文件[Culprit行是第9行,因为我需要以html格式添加action="{% url 'conferences:create' %}"

0 个答案:

没有答案