I'm trying to upload a file (any file) to my rest framework.
At the current time, I'm able to upload the file but unable to click on the generated link for some reason.
This is my settings.py:
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_DIRS = [os.path.join(BASE_DIR, "site_static")]
STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
This is my model.py:
...
class FileUpload(models.Model):
created = models.DateTimeField(auto_now_add=True)
user_profile = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
datafile = models.FileField(blank=False, null=False)
This is my views.py:
...
class FileUploadViewSet(viewsets.ModelViewSet):
"""Handles uploading a file"""
authentication_classes = (TokenAuthentication,)
serializer_class = (serializers.FileUploadSerializer)
queryset = models.FileUpload.objects.all()
parser_classes = (MultiPartParser, FormParser,)
permission_classes = (
permissions.UpdateOwnStatus,
IsAuthenticated
)
def perform_create(self, serializer):
"""Sets the user profile"""
serializer.save(user_profile=self.request.user,
datafile=self.request.data.get('datafile'))
This is my serializer.py:
...
class FileUploadSerializer(serializers.HyperlinkedModelSerializer):
user_profile = serializers.SlugRelatedField(
read_only=True,
slug_field='id'
)
class Meta:
model = models.FileUpload
fields = ('id', 'user_profile', 'created', 'datafile')
extra_kwargs = {'user_profile': {'read_only': True},
'created': {'read_only': True}}
This is my complete urls.py:
router = DefaultRouter()
router.register('hello-viewset', views.HelloViewSet, basename='hello-viewset')
router.register('profile', views.UserProfileViewSet)
router.register('feed', views.UserProfileFeedViewSet)
router.register('upload', views.FileUploadViewSet)
urlpatterns = [
path('hello-view/', views.HelloApiView.as_view()),
path('login/', views.UserLoginApiView.as_view()),
path('', include(router.urls)),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
When I upload a file, the datafile field becomes populated with the file location, such as:
{
"id": 2,
"user_profile": 4,
"created": "2020-04-27T21:08:16.269058Z",
"datafile": "http://127.0.0.1:8000/media/test.png"
},
I look at the project files and I can find the file at /media/, however, the link does not work.
How can I make the link work.
quoted from the docs here
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My problem, as it turns out, is that I was editing the wrong urls.py.
Both the api folder and the project folder has urls.py.
When adding that urlpattern to the correct project urls.py, it works fine!
Related
Today I tried to have images in my project and the idea is simple - create news with an image, title, and description.
I wonder why when I set up my media files
So I make my news in this view:
class NewsCreate(views.CreateView):
template_name = 'web/create_news.html'
model = News
fields = ('title', 'image', 'description')
success_url = reverse_lazy('home')
Here is the model:
class News(models.Model):
TITLE_MAX_LENGTH = 30
title = models.CharField(
max_length=TITLE_MAX_LENGTH
)
image = models.ImageField(
upload_to='news/',
blank=True
)
description = models.TextField()
Here is the set-up in settings.py:
MEDIA_ROOT = BASE_DIR / 'mediafiles'
MEDIA_URL = '/media/'
Here is the urls.py file:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('University_Faculty.web.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one
This is the result in my media folder after 10+ POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder
You need to correct
MEDIA_ROOT = BASE_DIR / 'media'
Hope this will work for you.
add this to settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
I've tried many ways but nothing works.
I can't find a solution to this issue.
My frontend is React and My backend is Django.
On browser only show the URL path link of the image instead of an image.
I've tried to add this code to another template and It was working but this one does not work.
browser display
My settings.py file:
INSTALLED_APPS = ['django.contrib.staticfiles',]
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
My urls.py file:
from django.views.generic import TemplateView
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
if not settings.DEBUG:
urlpatterns += [re_path(r'^.*',
TemplateView.as_view(template_name='index.html'))]
My Model looks like this
class Product(models.Model):
name = models.CharField(max_length=200)
image = models.ImageField(blank=True)
description = models.TextField()
price = models.DecimalField(max_digits=9, decimal_places=2)
createdAt = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f" '{self.name}' "
this is my configuration, in my project React within Django, hope that could help
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / 'static',
BASE_DIR / 'frontend/build/static' //this is from react, frontend is the React project's name
]
MEDIA_ROOT = BASE_DIR / 'static/media'
STATIC_ROOT = BASE_DIR / 'staticfiles
dont forget to add/install corsheader(add it in INSTALLED_APPS also),and whitenoise
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
...]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
CORS_ALLOW_ALL_ORIGINS = True
urls.py
urlpatterns = [
path('', TemplateView.as_view(template_name='index.html')),
.....
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
When I am using re_path('.*',index,name='index') unable to route to my media locations and instead of re_path when i am using path('/',index,name='index') then my react app routing is not working.
so what should i do ?
from django.contrib import admin
from django.urls import path , include,re_path
from .views import index
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/bookdetails/', include('backend.api.urls', 'api')),
re_path('.*', index , name='index')
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
setting.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "/static")
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "frontend/build/static")
]
MEDIA_URL = '/images/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'images')
The data form api is
{
"user": "exist",
"password": "valid",
"userdetails": {
"user_name": "laxman1006",
"full_name": "ajay nagpal",
"user_email": "Laxman#9451",
"college_name": "iitd",
"city": "luckonow",
"country": "india",
"profile_img": "/images/profile_image/laxman1006/laxman1006.jpg"
}
}
This is my serializer
class UserdetailsSerializer(serializers.ModelSerializer):
'''user details seriailizer '''
class Meta:
model = Userinfo
fields = ['user_name','full_name','user_email','college_name','city','country','profile_img']
Change it on your settings.py file and urls.py file as like below :
settings.py :
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static')
STATICFILES_DIR = os.path.join(BASE_DIR, '/static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py :
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('admin/', admin.site.urls),
path('api/bookdetails/', include('backend.api.urls', 'api')),
]
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Edited:
Add this inside your model UserInfo :
models.py :
def get_image_url(self):
img = self.profile_img
if img:
return img.image.url
else:
return None
serializers.py :
class UserdetailsSerializer(serializers.ModelSerializer):
'''user details seriailizer '''
profile_img = seriailizer.SerializerMethodField()
class Meta:
model = Userinfo
fields = ['user_name','full_name','user_email','college_name','city','country','profile_img']
def get_profile_img(self, obj):
request = self.context.get('request')
profile_img = obj.get_image_url()
return request.build_absolute_uri(profile_img)
I changed to this and now it is working
As that line was handling all of my url requests and my media files url was also handled by that so i just changed the sequence and now its working
from django.contrib import admin
from django.urls import path,include,re_path
from .views import index
from django.conf.urls.static import static
from django.conf.urls import url
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/bookdetails/', include('backend.api.urls', 'api')),
]
# urlpatterns += static(settings.MEDIA_URL,document_root= settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL , document_root=settings.STATIC_ROOT)
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns+= [re_path('.*', index , name='index')]
I followed the qblog tutorial, using python 2.7.10 and django 1.9.5.
When i enter the admin's blog interface, and clicked add blog entry, then it shown me below:
TemplateDoesNotExist at /admin/blog/entry/add/
django_markdown/editor_init.html
but i have installed django-markdown already. I would like to show the code below:
models.py:
class Entry(models.Model):
title = models.CharField(max_length=200)
body = MarkdownField()
slug = models.SlugField(max_length=200, unique=True)
publish = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)
objects = EntryQuerySet.as_manager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("entry_detail", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Blog Entry"
verbose_name_plural = "Blog Entries"
ordering = ["-created"]
admin.py:
from django.contrib import admin
from . import models
from django_markdown.admin import MarkdownModelAdmin
from django_markdown.widgets import AdminMarkdownWidget
from django.db.models import TextField
class EntryAdmin(MarkdownModelAdmin):
list_display = ("title", "created")
prepopulated_fields = {"slug": ("title",)}
# Next line is a workaround for Python 2.x
formfield_overrides = {TextField: {'widget': AdminMarkdownWidget}}
admin.site.register(models.Entry, EntryAdmin)
admin.site.register(models.Tag)
qblog/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
import settings
urlpatterns = patterns(
'',
url(r'^admin/', include(admin.site.urls)),
url(r'^markdown/', include("django_markdown.urls")),
url(r'^', include('blog.urls')),
)
if settings.DEBUG:
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
You need to add the editor_init.html file in your project.
If your project root is project/ there should be a directory called templates in there. If that directory does not exist, create it (so the path would be project/templates).
Place the editor_init.html file in this directory and everything should work.
You can find more information about setting up templates here and in the django docs.
I am facing problem in returned image url, which is not proper.
My return image url is "http://127.0.0.1:8000/showimage/6/E%3A/workspace/tutorial_2/media/Capture1.PNG"
But i need
"http://127.0.0.1:8000/media/Capture1.PNG"
When i click on image_url then image open in new browser tab
But currently its shown error:
view.py
from showimage.models import ShowImage
from showimage.serializers import ShowImageSerializer
from rest_framework import generics
# Create your views here.
class ShowImageList(generics.ListCreateAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
class ShowImageDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = ShowImage.objects.all()
serializer_class = ShowImageSerializer
model.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to=settings.MEDIA)
serializer.py
from rest_framework import serializers
from showimage.models import ShowImage
class ShowImageSerializer (serializers.ModelSerializer):
class Meta:
model = ShowImage
fields = ('id', 'image_name', 'image_url')
settings.py
MEDIA=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
I am new in python and also in django-rest-framework.
Please also tell me how we extend models or serialize class
You might want to try this in your settings:
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in your models:
class ShowImage(models.Model):
image_name = models.CharField(max_length=255)
image_url = models.ImageField(upload_to="") # or upload_to="images", which would result in your images being at "http://127.0.0.1:8000/media/images/Capture1.PNG"
Finally, i solve this road block with the help of
#Remi
Thanks #Remi
But some other change i do so that i elaborate solution and fix this issue.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, "media")
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^showimage/', include('showimage.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your code seems correct except one thing you have passed settings.MEDIA in uploads image. you don't need to pass settings.MEDIA in uploads.
try this
image_url = models.ImageField(upload_to='Dir_name')
Dir_name will create when you'll run script.