gpt4 book ai didi

python - Django 1.11 不包含 urls.py

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:50 25 4
gpt4 key购买 nike

您好,我正在使用我的第一个 Django 应用程序,但遇到了下一个问题:

The included URLconf 'eventus.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

.
├── eventus
│   ├── eventus
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── db.sqlite3
│   │   ├── settings
│   │   │   ├── __init__.py
│   │   │   ├── __pycache__
│   │   │   │   ├── __init__.cpython-36.pyc
│   │   │   │   ├── base.cpython-36.pyc
│   │   │   │   └── local.cpython-36.pyc
│   │   │   ├── base.py
│   │   │   ├── local.py
│   │   │   ├── prod.py
│   │   │   └── staging.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   ├── manage.py
│   └── myapps
│   ├── __init__.py
│   ├── __pycache__
│   │   └── __init__.cpython-36.pyc
│   ├── events
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── admin.cpython-36.pyc
│   │   │   ├── forms.cpython-36.pyc
│   │   │   ├── models.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── views.cpython-36.pyc
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── forms.py
│   │   ├── media
│   │   │   └── events
│   │   │   ├── evento.png
│   │   │   ├── evento2.png
│   │   │   ├── evento2_a0yEovu.png
│   │   │   ├── evento3.png
│   │   │   ├── evento3_IufcnS5.png
│   │   │   └── evento_HFKQ1lo.png
│   │   ├── migrations
│   │   │   ├── 0001_initial.py
│   │   │   ├── 0002_auto_20170924_2140.py
│   │   │   ├── __init__.py
│   │   │   └── __pycache__
│   │   │   ├── 0001_initial.cpython-36.pyc
│   │   │   ├── 0002_auto_20170924_2115.cpython-36.pyc
│   │   │   ├── 0002_auto_20170924_2140.cpython-36.pyc
│   │   │   └── __init__.cpython-36.pyc
│   │   ├── models.py
│   │   ├── static
│   │   │   ├── css
│   │   │   │   ├── bootstrap-theme.css
│   │   │   │   ├── bootstrap-theme.css.map
│   │   │   │   ├── bootstrap-theme.min.css
│   │   │   │   ├── bootstrap-theme.min.css.map
│   │   │   │   ├── bootstrap.css
│   │   │   │   ├── bootstrap.css.map
│   │   │   │   ├── bootstrap.min.css
│   │   │   │   ├── bootstrap.min.css.map
│   │   │   │   └── estilos.css
│   │   │   ├── fonts
│   │   │   │   ├── glyphicons-halflings-regular.eot
│   │   │   │   ├── glyphicons-halflings-regular.svg
│   │   │   │   ├── glyphicons-halflings-regular.ttf
│   │   │   │   ├── glyphicons-halflings-regular.woff
│   │   │   │   └── glyphicons-halflings-regular.woff2
│   │   │   └── js
│   │   │   ├── bootstrap.js
│   │   │   ├── bootstrap.min.js
│   │   │   └── npm.js
│   │   ├── templates
│   │   │   ├── base.html
│   │   │   └── events
│   │   │   ├── base_events.html
│   │   │   ├── index.html
│   │   │   └── panel
│   │   │   ├── crear_evento.html
│   │   │   ├── detalle_evento.html
│   │   │   ├── editar_evento.html
│   │   │   ├── eliminar_evento.html
│   │   │   ├── navbar.html
│   │   │   └── panel.html
│   │   ├── tests.py
│   │   ├── urls.py
│   │   └── views.py
│   └── users
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── actions.cpython-36.pyc
│   │   ├── admin.cpython-36.pyc
│   │   └── models.cpython-36.pyc
│   ├── actions.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │   ├── 0001_initial.cpython-36.pyc
│   │   └── __init__.cpython-36.pyc
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── requirements
├── base.txt
├── local.txt
├── prod.txt
└── staging.txt

我的文件 events/urls.py 是:

from django.conf.urls import url, include
from .views import IndexView, MainPanelView, CreateEvent, EventDetail, EventEdit, EventDelete


urlpatterns = [
#url(r'^$',views.index, name="index"),
url(r'^$',IndexView.as_view(), name="index"),


url(r'^panel/$', MainPanelView.as_view(), name="panel"),
url(r'^panel/evento/nuevo/$',CreateEvent.as_view(), name="nuevo"),
url(r'^panel/evento/(?P<pk>\d+)/$',EventDetail.as_view(), name="detalle"),
url(r'^panel/evento/editar/(?P<pk>\d+)/$',EventEdit.as_view(), name="editar"),
url(r'^panel/evento/eliminar/(?P<pk>\d+)/$',EventDelete.as_view(), name="eliminar"),
]

我的文件是 events/views.py 是:

from django.shortcuts import render, redirect, get_object_or_404
from .models import Event, Category
from django.views.generic import TemplateView, CreateView, DetailView, UpdateView, DeleteView
from myapps.users.models import User
from .forms import EventoForm
from django.core.urlresolvers import reverse, reverse_lazy
# Create your views here.

def login(request):
return render(request, "login.html", {})

#def index(request):
# events = Event.objects.all().order_by('-created')[:6]
# categories = Category.objects.all()
# return render(request, 'events/index.html', {'events': events, 'categories': categories})

class IndexView(TemplateView):
template_name = 'events/index.html'

def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['events'] = Event.objects.all().order_by('-created')[:6]
context['categories'] = Category.objects.all()
return context


#def main_panel(request):
# #organizer = request.user.username
# events = Event.objects.filter(organizer__username='').order_by('is_free', '-created')
# cantidad_eventos = events.count()
# return render(request, 'events/panel/panel.html', {'events': events, 'cantidad': cantidad_eventos})


class MainPanelView(TemplateView):

template_name = 'events/panel/panel.html'

def get_context_data(self, **kwargs):
context = super(MainPanelView, self).get_context_data(**kwargs)
context['events'] = Event.objects.filter(organizer__username='').order_by('is_free', '-created')
context['cantidad'] = context['events'].count()
return context


#def crear_evento(request):
# if request.method == 'POST':
# modelform = EventoForm(request.POST, request.FILES)
# if modelform.is_valid():
# organizador = User.objects.get(pk=3)
# nuevo_evento = modelform.save()
# nuevo_evento.organizer = organizador
# nuevo_evento.save()
# return redirect ('events_app:panel')
# else:
# modelform = EventoForm
#
# return render(request, "events/panel/crear_evento.html", {'form': modelform})


class CreateEvent(CreateView):

form_class = EventoForm
template_name = 'events/panel/crear_evento.html'
success_url = reverse_lazy('events_app:panel')

def form_valid(self, form):
form.instance.organizer = User.objects.get(pk=3)
return super(CreateEvent, self).form_valid(form)


#def detalle_evento(request, evento_id):
# event = get_object_or_404(Event, pk=evento_id)
# return render(requestr, 'events/panel/detalle_evento.html', {'event': event})

class EventDetail(DetailView):

template_name = 'event/panel/detalle_evento.html'
model = Event


#def editar_evento(request, evento_id):
# event = get_object_or_404(Event, pk=evento_id)
#
# if request.method == 'POST':
# modelform = EventoForm(request.POST, request.FILES, instance=event)
# if modelform.is_valid():
# modelform.save()
# return redirect(reverse('events_app:panel'))
# else:
# modelform = EventoForm(instance=event)
#
# return render(request, 'events/panel/editar_evento.html', {'form': modelform, 'event': event})

class EventEdit(UpdateView):

template_name = 'events/panel/editar_evento.html'
success_url = reverse_lazy(reverse('events_app:panel'))
model = Event
form_class = EventoForm

def form_valid(self, form):
form.instance.organizer = User.objects.get(pk=3)
return super(EventEdit, self).form_vaslid(form)



#def eliminar_evento(request, evento_id):
# event = get_object_or_404(Event, pk=evento_id)
#
# if request.method == 'POST':
# event.delete()
# return redirect(reverse('events_app:panel'))
#
# return render(request, 'events/panel.eliminar_evento.html')


class EventDelete(DeleteView):

template_name = 'events/panel.eliminar_evento.html'
model = Event
success_url = Ureverse_lazy('events_app:panel')
context_object_name = 'event'

我的 urls.py 是:

from django.conf.urls import  url, include
from django.contrib import admin
from django.conf import settings
urlpatterns = [
url(r'^', include('myapps.events.urls', namespace="events_app")),
url(r'^admin/', admin.site.urls),
]

if settings.DEBUG:
urlpatterns = [
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}
),
]#

我的 events/models.py 是:

from django.db import models
from django.template.defaultfilters import slugify
from django.conf import settings
# Create your models here.

class TimeStampModel(models.Model):
created = models.DateTimeField(auto_now_add=True)
modified = models.DateField(auto_now=True)

class Meta:
abstract = True

class Category(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(editable=False)

def save(self, *args, **kwargs):
if not self.id:
self.slug =slugify(self.name)
super(Category, self).save (*args,**kwargs)

def __unicode__(self):
return self.name

class Event(TimeStampModel):
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(editable=False)
summary = models.TextField(max_length=255)
content = models.TextField()
category = models.ForeignKey(Category)
place = models.CharField(max_length=50)
start = models.DateTimeField()
finish = models.ImageField(upload_to= 'events')
is_free = models.BooleanField(default=True)
amout = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)
views = models.PositiveIntegerField(default=0)
organizer = models.ForeignKey(settings.AUTH_USER_MODEL)

def save(self, *args, **kwargs):
if not self.id:
self.slug =slugify(self.name)
super(Event, self).save (*args,**kwargs)


def __unicode__(self):
return self.name

class Assistant (TimeStampModel):
Assistant = models.ForeignKey(settings.AUTH_USER_MODEL)
event = models.ManyToManyField(Event)
attended = models.BooleanField(default=False)
has_paid = models.BooleanField(default=False)

def __unicode__(self):
return "%s %s" % (self.assistant.username , self.event.name)


class Comments(TimeStampModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
event = models.ForeignKey(Event)
content = models.TextField()

def __unicode__(self):
return "%s %s" % (self.user.username, self.event.name)

错误是下一个:

Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 327, in execute
self.check()
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "/Users/dmuino/.virtualenvs/Pruebas/CursoProDjango/eventus/eventus/urls.py", line 27, in <module>
{'document_root': settings.MEDIA_ROOT}
File "/Users/dmuino/.virtualenvs/Pruebas/lib/python3.6/site-packages/django/conf/urls/__init__.py", line 85, in url
raise TypeError('view must be a callable or a list/tuple in the case of include().')
TypeError: view must be a callable or a list/tuple in the case of include().

我的base.py是下一个:

"""
Django settings for eventus project.

Generated by 'django-admin startproject' using Django 1.11.5.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os
from unipath import Path

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = Path(__file__).ancestor(3)


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '70r=ho4co205hed75q!)am+dnqi=lj(98$lnadxmgf2n(s&_qi'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition
DJANGO_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

LOCAL_APPS = [
'myapps.events',
'myapps.users',
]

THIRD_PARTY_APPS = [
]

INSTALLED_APPS = DJANGO_APPS + LOCAL_APPS + THIRD_PARTY_APPS

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'eventus.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'eventus.wsgi.application'

# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


AUTH_USER_MODEL = 'users.User'

我不知道问题是什么,因为在它工作正常之前,但现在我不知道问题是什么,我只将基于函数的 View 更改为基于 View 的 events/urls.py类,但在文件中,在文件中的新 View 之前注释旧 View 。

最佳答案

回溯显示 events/views.py 第 97 行发生错误:

success_url = reverse_lazy(reverse('events_app:panel'))

为 View 设置 success_url 时,无法调用 reverse。它会导致 Django 在加载 url 配置之前尝试反转 url,从而导致“似乎没有任何模式”错误消息。

解决方案是使用reverse_lazy。你有 reverse_lazy(reverse(...)) 这是没有意义的。将其更改为仅使用 reverse_lazy:

success_url = reverse_lazy('events_app:panel')

您的第二个错误“ View 必须是可调用的”是因为您提供媒体文件的代码使用字符串'django.views.static.serve'。这已经过时了,并且不适用于 Django 1.10+。更新为match the docs :

from django.conf.urls.static import static

urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

关于python - Django 1.11 不包含 urls.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46553802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com