Django - 以 10 为底的 int() 的 FileField 无效文字:'media'

Django - FileField invalid literal for int() with base 10: 'media'

我正在用 Django 制作简单的博客网站,但遇到了这个错误:invalid literal for int() with base 10: 'media'。当我在我的博客应用程序中将 FileField 添加到 models.py 时很高兴。这是一些代码:

models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone


class Post(models.Model):

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('publish', 'Public')
    )

    author = models.ForeignKey(User)
    title = models.CharField(max_length=140)
    slug = models.SlugField(max_length=140)
    image = models.FileField(blank=False, null=False, upload_to='media_cdn')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')

    class Meta:
        ordering = ['-publish']

    def __str__(self):
        return self.title

这是settings.py的一部分:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn")

和urls.py

from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('blog.urls'))
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL,
                          document_root=settings.STATIC_ROOT)

非常感谢您的帮助!

blog/urls.py

from django.contrib.auth.urls import url
from .views import PostList, PostDetail

urlpatterns = [
    url(r'^$', PostList.as_view(), name='blog'),
    url(r'(?P<pk>[^/]+)', PostDetail.as_view(), name='post'),
    url(r'(?P<pk>[^/]+)/(?P<slug>[-\w]+)$',
        PostDetail.as_view(), name='post_detail'),
]

这些模式正在消耗对媒体文件的所有请求。

url(r'^', include('blog.urls'))  # in main urls.py

url(r'(?P<pk>[^/]+)', PostDetail.as_view(), name='post')  # in blogs/urls.py

当您转到 http://127.0.0.1:8000/media/media_cdn/e1980c9642c03529db70a9c6060f247f.jpg 时,url 路由器会尝试将其用于博客条目,这会导致此错误。

你应该重写你的 url 模式,这样就不会发生这种情况。如果您的博客 url 仅使用数字 url(例如 http://127.0.0.1:8000/1/),您可以为此创建一个模式。

url(r'^(?P<pk>\d+)/$', PostDetail.as_view(), name='post'),
url(r'^(?P<pk>\d+)/(?P<slug>[-\w]+)/$', PostDetail.as_view(), name='post_detail'),

记得在 url 模式中使用 ^$。 有关 url 模式和调度工作原理的更多示例和说明,请参阅官方文档。 https://docs.djangoproject.com/en/1.11/topics/http/urls/