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 ?
Related
This is the url i am trying:
http://localhost:8000/blog/categoria/1/
The foreign key is categoria_id that comes from relationship many to many of Post and Categoria.
I am using Sqlite3.
This file is the models.py
from django.db import models
from django.contrib.auth.models import User
class Categoria(models.Model):
nombre=models.CharField(max_length=50)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name='categoria'
verbose_name_plural='categorias'
def __str__(self):
return self.nombre
class Post(models.Model):
titulo=models.CharField(max_length=50)
contenido=models.CharField(max_length=50)
imagen=models.ImageField(upload_to='blog', null=True, blank=True)
autor=models.ForeignKey(User, on_delete=models.CASCADE)
categorias=models.ManyToManyField(Categoria)
created=models.DateTimeField(auto_now_add=True)
updated=models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name='post'
verbose_name_plural='posts'
def __str__(self):
return self.titulo
This file is the views.py:
from django.shortcuts import render
from blog.models import Post, Categoria
def blog(request):
posts=Post.objects.all()
return render(request, "blog/blog.html",{"posts":posts})
def categoria(request, categoria_id):
categoria=Categoria.objects.get(id=categoria_id)
posts=Post.objects.filter(categorias=categoria)
return render(request, "blog/categoria.html",{'categoria': categoria, "posts":posts })
This file is the urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.blog, name='Blog'),
path('categoria/<int:categoria_id>/', views.categoria, name="categoria")
]
I change the database to postgresql and I added a / before categoria in the file urls.py. For now it works. It’s strange, because I’ve made these changes before and it didn't work.
Despite this I would appreciate any suggestion. Thank you.
This file is the urls.py after the change:
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.blog, name='Blog'),
path('/categoria/<int:categoria_id>/', views.categoria, name='categoria'),
]
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.
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/
i am beginner in django and i dont know how to solve this problem
i am getting error on browser as:
Using the URLconf defined in mysite.urls, Django tried these URL
patterns, in this order: ^admin/
The current URL, api/Entry/, didn't
match any of these.
all my files are:
mysite/myapp/models.py:
from tastypie.utils.timezone import now
from django.contrib.auth.models import User
from django.db import models
from django.utils.text import slugify
class Entry(models.Model):
user = models.ForeignKey(User)
pub_date = models.DateTimeField(default=now)
title = models.CharField(max_length=200)
slug = models.SlugField()
body = models.TextField()
def __unicode__(self):
return self.title
def save(self, *args, **kwargs):
# For automatic slug generation.
if not self.slug:
self.slug = slugify(self.title)[:50]
return super(Entry, self).save(*args, **kwargs)
mysite/myapp/api.py:
from tastypie.resources import ModelResource
from myapp.models import Entry
class EntryResource(ModelResource):
class Meta:
queryset = Entry.objects.all()
resource_name = 'Entry'
mysite/myapp/urls.py:
from django.conf.urls.defaults import *
from myapp.api import EntryResource
entry_resource = EntryResource()
urlpatterns = patterns('',
# The normal jazz here...
(r'^blog/', include('myapp.urls')),
(r'^api/', include(entry_resource.urls)),
mysite/mysite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls))
)
where my 'mysite' is my project name and 'myapp' is my app
please help me out
Thanks
Your project-level urls.py doesn't include your application-level urls.py. Change mysite/mysite/urls.py to this:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('myapp.urls')),
url(r'^admin/', include(admin.site.urls))
)
Also, get rid of (r'^blog/', include('myapp.urls')), in mysite/myapp/urls.py.
Hope that helps.
I use django rest framework and have this error:
base_name argument not specified, and could not automatically determine the name from the viewset, as it does not have a .model or .queryset attribute.
This is my code
urls.py
from django.conf.urls import patterns, include, url
from rest_framework import viewsets, routers
import views
router = routers.SimpleRouter()
router.register(r'book', views.BookViewSet.as_view())
views.py
from django.shortcuts import render_to_response
from mobileapp.models import Book
from rest_framework import generics
from mobileapp.serializers import BookSerializer
class BookViewSet(generics.ListAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
serializers.py
from mobileapp.models import Book
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'url', 'date', 'comment')
Have you google'd error statement?
https://github.com/tomchristie/django-rest-framework/issues/933
http://django-rest-framework.org/api-guide/routers.html#usage
I'v solved my problem. There is code.
urls.py
from django.conf.urls import patterns, include, url
from views import BookList, BookDetail
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^book/$', BookList.as_view(), name='book-list'),
url(r'^book/(?P<pk>\d+)/$', BookDetail.as_view(), name='book-detail'),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
)
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'api'])
views.py
class BookList(generics.ListCreateAPIView):
serializer_class = BookSerializer
def get_queryset(self):
queryset = Book.objects.filter(user=self.request.user)
return queryset.order_by('-id')
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
model = Book
serializer_class = BookSerializer