I'm making simple blog website in Django and I got this error: invalid literal for int() with base 10: 'media'. It's happnes when I added FileField to models.py in my blog application. Here is some code:
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
Here is part of 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")
And 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)
Thanks a lot for help !
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'),
]
These pattern are consuming all requests to media files.
url(r'^', include('blog.urls')) # in main urls.py
url(r'(?P<pk>[^/]+)', PostDetail.as_view(), name='post') # in blogs/urls.py
When you go to http://127.0.0.1:8000/media/media_cdn/e1980c9642c03529db70a9c6060f247f.jpg, the url router tries to use that for a blog entry, which causes this error.
You should rewrite your url patterns so that this doesn't happen. If your blogs urls only consume numeric urls ( for example http://127.0.0.1:8000/1/), you can create a pattern for this.
url(r'^(?P<pk>\d+)/$', PostDetail.as_view(), name='post'),
url(r'^(?P<pk>\d+)/(?P<slug>[-\w]+)/$', PostDetail.as_view(), name='post_detail'),
Remember to use ^ and $ in your url patterns.
See the official documentation for more examples and explanation of how url patterns and dispatching works.
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Related
I`m writing a site on Django and I faced a problem. I have a cv field in the database, in which users can store their resume, I did everything as stated in the documentation. Namely:
Create FileField model in models.py
class JobseekerProfileInfo(models.Model):
jobseeker = models.OneToOneField(JobseekerRegisterInfo, on_delete=models.CASCADE)
photo = models.ImageField(upload_to='avatars/%Y/%m/%d',
default='static/personal_profile/images/default_avatar.png')
expected_job = models.CharField(max_length=400, blank=True)
telegram = models.CharField(max_length=150, blank=True)
linkedin = models.URLField(blank=True)
git_hub = models.URLField(blank=True)
cv = models.FileField(upload_to='cvs/%Y/%m/%d')
active_search = models.BooleanField(default=True)
def __str__(self):
return self.expected_job
Notice the FileField, I specified the upload_to argument
Created a MEDIA_ROOT and MEDIA_URL variables in settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Added static() to urlpatterns list in urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
import debug_toolbar
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main_page.urls')),
path('jobseeker', include('jobseeker.urls')),
path('profile', include('personal_profile.urls')),
path('__debug__/', include('debug_toolbar.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += [
path('captcha/', include('captcha.urls'))
]
But when I added file to db, media root doesn`t create
Help me please
Problem - When trying to fetch an image leads to 404 error
URL Declarations -
from django.urls import include, path
from rest_framework import routers
from django.conf.urls.static import static
from django.conf import settings
from my_awesome_api.views import PersonViewSet, SpeciesViewSet
router = routers.DefaultRouter()
router.register(r'people', PersonViewSet)
router.register(r'species', SpeciesViewSet)
urlpatterns = [
path('', include(router.urls)),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
print('avail url patterns')
print(urlpatterns)
VIEW DECLARATION -
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework import permissions
from my_awesome_api.serializers import PersonSerializer, SpeciesSerializer
from my_awesome_api.models import Person, Species
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
parser_classes = (MultiPartParser, FormParser)
#permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save()
class SpeciesViewSet(viewsets.ModelViewSet):
queryset = Species.objects.all()
serializer_class = SpeciesSerializer
parser_classes = (MultiPartParser, FormParser)
#permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save()
MODEL DECLARATION -
from django.db import models
# Create your models here.
class Species(models.Model):
name = models.CharField(max_length=100)
classification = models.CharField(max_length=100)
language = models.CharField(max_length=100)
image_url = models.ImageField(blank=True, null=True)
class Person(models.Model):
name = models.CharField(max_length=100)
birth_year = models.CharField(max_length=10)
eye_color = models.CharField(max_length=10)
species = models.ForeignKey(Species, on_delete=models.DO_NOTHING)
image_url = models.ImageField(blank=True, null=True)
SETTING DECLARATION
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'media')
print(MEDIA_ROOT)
print('value of media root')
# URL used to access the media
MEDIA_URL = 'media/'
In an effort to troubleshoot the problem, I printed out the media root path and it is correct
/Users/ss1/Desktop/drf/media
value of media root
Printing out the URLs give the output -
[<URLResolver (None:None) ''>, <URLPattern '^media/(?P.*)$'>]
Here is the URL from PROJECT
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path('star-wars/', include('my_awesome_api.urls')),
]
HERE IS THE URL FROM APP
from django.urls import include, path
from rest_framework import routers
from django.conf.urls.static import static
from django.conf import settings
from my_awesome_api.views import PersonViewSet, SpeciesViewSet
router = routers.DefaultRouter()
router.register(r'people', PersonViewSet)
router.register(r'species', SpeciesViewSet)
urlpatterns = [
path('', include(router.urls)),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
print('avail url patterns')
print(urlpatterns)
Here is the screenshot confirming successful image uploads --
What did I miss here ?
I am trying to add a document file from the admin panel Django but I am getting 404 not found URL errors.
admin file
from django.contrib import admin
from .models import Category, Document
# Register your models here.
admin.site.register(Category)
admin.site.register(Document)
from django.db import models
class Document(models.Model):
doc_name = models.CharField(max_length=100)
doc_slug = models.CharField(max_length=100)
doc_file = models.FileField(upload_to='docs')
doc_price = models.IntegerField()
doc_cat = models.CharField(max_length=100)
doc_desc = models.TextField()
doc_var = models.TextField()
Main URLs
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', include('UserAccount.urls')),
path('dashboard/', include('Dashboard.urls')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
What could possibly be the error?
404 error means that path to the admin panel doesn't declarated.
Check main urls.py file. There should be this import statement: from django.contrib import admin and path('admin/', admin.site.urls) line in urlpatterns var.
have problems.
1)In production Django tries to access photos at http://"ip_address"/images/"image".jpg URL however images must be in http://"ip_address"/media/images/"image".jpg
2)I have added two more fields (alt and text) to existing model. Migrations work and show that the fields are added but i can not see them in the admin panel ( I have added them to the list_display) and i can not access them in my templates.
settings for media
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = 'http://"ip_address"/media/'
urls
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
url(r'^$','main.views.mainpage'),
)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
models
from django.db import models
class Slider(models.Model):
image = models.ImageField(upload_to = 'images/')
caption = models.TextField()
alt = models.CharField(max_length = 20, default = "an image")
text = models.CharField(max_length = 5, null=True)
admin
from django.contrib import admin
from main.models import Slider
class SliderAdmin(admin.ModelAdmin):
list_display = ('image','alt','caption','text')
admin.site.register(Slider,SliderAdmin)
See https://docs.djangoproject.com/en/1.8/howto/static-files/
Add a STATIC_URL to your settings.py
Using python 2.7, django 1.4.1, filebrowser 3.5.0, grappelli 2.4.2, win7 x64
So heres my problem:
Im creating a object, and trying to attach an image to it:
Clicking on search:
Navigating through folders to get to my file, and picking it:
After i pick it, this is the path it returns:
Attaching model itself:
class EntryManager(models.Manager):
def active(self):
return super(EntryManager, self).get_query_set().filter(is_active=True)
class Services(models.Model):
name = models.CharField(max_length = 20, help_text = 'Nazwa oferowanej usługi', verbose_name='Usługa')
slug = models.SlugField(max_length=255, help_text = 'Odnośnik, generowany automatycznie na podstawie nazwy', unique=True,verbose_name='Odnośnik')
icon = FileBrowseField(verbose_name='Ikona', max_length=255, directory="images/", extensions=[".jpg",'.png','.gif'], blank=True, null=True,help_text = '.jpg, .png, .gif')
is_active = models.BooleanField(help_text='Zaznacz aby obiekt był widoczny dla użytkowników', default=False)
objects = EntryManager()
class Meta:
ordering = ['name']
verbose_name = "Usługę"
verbose_name_plural = "Usługi"
def __str__(self):
return self.name
def __unicode__(self):
return self.name
def get_absolute_url(self):
return '/uslugi/%s/' % self.slug
I have no idea where to search for a problem at the moment, could any1 help?
edit:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from filebrowser.sites import site
#when on dev, serve media files
from django.conf import settings
urlpatterns = patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^uslugi/?$', 'services.views.services'),
)
#when on dev, serve media files
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
and part of settings.py
import os
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__) + "../../")
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'site_media/media')
STATIC_ROOT = os.path.join(PROJECT_DIR, 'site_media/static')
ADMIN_MEDIA_PREFIX = os.path.join(PROJECT_DIR, 'site_media/admin_media')
INSTALLED_APPS = (
'grappelli',
'filebrowser',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'services'
)
After reading yours urls.py I need to show You Documentation:
In your url.py import the default FileBrowser site:
from filebrowser.sites import site
and add the following URL-patterns (before any admin-urls):
urlpatterns = patterns('',
url(r'^admin/filebrowser/', include(site.urls)),
)
So only differences between You and my new project are:
I'm using Linux Ubuntu x86 on VirtualBox undex Windows 7
I have /admin/file-browser BEFORE any admin-urls:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from filebrowser.sites import site
from django.conf.urls.static import static
from django.conf import settings
admin.autodiscover()
urlpatterns = static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + patterns('',
url(r'^grappelli/', include('grappelli.urls')),
url(r'^admin/filebrowser/', include(site.urls)),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^', include('django.contrib.flatpages.urls')),
)