Django React Image wont display - django

So I recently was trying to deploy my website and I was able to get everything working. However, the images are broken for some reason. I can actually add images to the database fine (easily able to add and change the image itself). However, when I click on the link I go nowhere instead of seeing the image and just see the part of my site that pops up whenever the URL entered isn't part of the API (no error, instead nothing basically shows up). The strange part is that the uploaded images actually get added to my images folder in my project but it seems like Django can't find them afterwards (you can see the image is in the database in my images folder). Here is how my project is laid out and: Here is some of my code:
SETTINGS.PY
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'build/static'),
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
REST_FRAMEWORK = {
'DEFAULT_AUTHETICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication'
]
}
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR),'EZtrade')
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'build')],
'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',
],
},
},
]
URLS.PY
urlpatterns = [
path('api-auth/', include('rest_framework.urls')),
path('admin/', admin.site.urls),
path('api/', include('articles.api.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
re_path('.*',TemplateView.as_view(template_name='index.html')),
url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT,})
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
API URLS
router = DefaultRouter()
router.register(r'articles', ArticleViewSet, basename='articles')
router.register(r'trade', TradeViewSet, basename='trade')
router.register(r'users', UserDataViewSet, basename='users')
urlpatterns = router.urls + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MODEL
class Article(models.Model):
title = models.CharField(max_length=120)
content = models.TextField()
image = models.ImageField(upload_to = 'images', blank=True)
createdBy = models.CharField(max_length=120)
traded = models.BooleanField(default=False)
city = models.CharField(max_length=120)
def __str__(self):
return self.title
VIEWS.PY
class ArticleViewSet(viewsets.ModelViewSet):
serializer_class = ArticleSerializer
queryset = Article.objects.all()
filter_backends = [DjangoFilterBackend,filters.SearchFilter]
filterset_fields = ['createdBy','traded']
search_fields = ['title']
authentication_classes = (TokenAuthentication,) # Add this line
permission_classes = (IsAuthenticated,)
def get_permissions(self):
if self.action == 'list' or self.action == 'retrieve':
return [AllowAny(), ]
return super(ArticleViewSet, self).get_permissions()
def patch(self, request, pk):
testmodel_object = self.get_object(pk)
serializer = TestModelSerializer(testmodel_object, data=request.data, partial=True)
if serializer.is_valid():
serializer.save()
return JsonResponse(code=201, data=serializer.data)
return JsonResponse(code=400, data="wrong parameters")
SERIALIZERS.PY
class ArticleSerializer(PatchModelSerializer):
class Meta:
model = Article
fields = ('id','title','content','image','createdBy','traded','city')
I have tried many different things and have not been able to find anything else like this on the internet since I dont even get an error when trying to access the image. Im pretty stuck with this so if anyone could help that would be awsome!

you have to make an another serializer using method and pass image url on that like this
class ArticleSerializer(PatchModelSerializer):
image_url = serializers.SerializerMethodField('get_image_url')
class Meta:
model = Article
fields = ('id','title','content','image','image_url','createdBy','traded','city')
def get_image_url(self, obj):
return obj.image.url

I figured out that I had to put the re_path at the end since it was overriding my image url.

i just figured out that the problem is in the urls.py file
it's missing some code
here is mine before
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls'))
]
and here is after i saw this article
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/', include('api.urls'))
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

Related

CKEditor in production not showing in admin panel

I've launched my project into production, CKEditior and CKEditor_uploader both worked on my local server but now doesn't show on my production admin panel. Any ideas why it may not be showing would be greatly appreciated. Or any alternative ways to implement richtext and image uploading to blog posts in django admin.
*UPDATE
I have some how got the CKEditor back but I cannot get the uploader to work, I have followed all documentation to a tee.
settings.py
STATIC_URL = '/static/'
MEDIA_URL = '/static/images/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static/images/')
STATIC_ROOT = os.path.join(BASE_DIR, '/home/martinhenso/public_html/static')
CKEDITOR_UPLOAD_PATH = "uploads/"
urls
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('martinhensonphotography.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.MEDIA_ROOT)
models
class Topic(models.Model):
title = models.CharField(max_length=100)
content = RichTextUploadingField()
def __str__(self):
return self.title
class BlogPost(models.Model):
blog_title = models.CharField(max_length=255)
blog_article = RichTextField(null=True, blank=True)
blog_image = models.ImageField(null=True, blank=True, upload_to="images", default="default.png")
def __str__(self):
return self.blog_title
admin
from django.contrib import admin
from . models import PostImage, EnterImage, BlogPost, Topic
# Register your models here.
admin.site.register(PostImage)
admin.site.register(BlogPost)
admin.site.register(EnterImage)
admin.site.register(Topic)
Try:
settings.py
STATIC_ROOT = [
os.path.join(BASE_DIR,'static','static_files')
]
python manage.py collectstatic
Location of static files are must be mension in nginx config file
Or
After entering the comment there will be a folder created 'static_files' inside static folder copy all the static files to to main static folder

Django URL not rendering templates

Instead of directing me to the page django is simply returning the following error:
“C:\Users\RodrigoPinto\Desktop\Insider\users\register” does not exist
This is my url;
from django.urls import path
from users import employee_views
from users import views as auth_views
from django.contrib.auth.views import LoginView, LogoutView
app_name = 'users'
urlpatterns = [
path('login/', LoginView.as_view(template_name='users/login.html')),
path('logout/', LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('register/', auth_views.Register.as_view, name='register'),
path('profile/', auth_views.Profile.as_view, name='profile'),
path('listView/', employee_views.AccountsListView.as_view, name='listView'),
path('update/<pk>/', employee_views.AccountsUpdate.as_view, name='updateView'),
path('password_update/<pk>/', employee_views.update_password, name='password_update'),
path('delete/<pk>/', employee_views.AccountsDelete.as_view, name='deleteView'),
]
and on the main app i have this inside the URL;
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import urls as user_urls
app_name = "inside"
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('inside.urls')),
path('users/', include(user_urls)),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I've been over this code for the last two hours and I cant understand what I'm doing wrong. Maybe someone can see something that I'm missing.
Also my template directory in settings is configured like this;
template_dir = [
os.path.join(BASE_DIR, 'users', 'templates'),
os.path.join(BASE_DIR, 'forums', 'templates'),
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': template_dir,
'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',
],
},
},
]
views.py;
from django.urls import reverse_lazy
from .forms import UserCreateForm
from django.views.generic import CreateView, TemplateView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.mixins import LoginRequiredMixin
class Register(SuccessMessageMixin, CreateView):
form_class = UserCreateForm
success_url = reverse_lazy('users:login')
template_name = 'users/register.html'
success_message = 'Your Account has been created!'
class Profile(LoginRequiredMixin, TemplateView):
template_name = 'users/profile.html'
separate file to keep code cleaner employee_views.py;
from django.views.generic import TemplateView, ListView, UpdateView, DeleteView
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages import error, success
from django.shortcuts import redirect, reverse
from django.urls import reverse_lazy
from django.shortcuts import render
from .models import User
#login_required()
def update_password(request, pk):
if request.method == "POST":
form_data = request.POST
if form_data['password1'] == form_data['password2'] and len(form_data['password1']) > 7:
u = User.objects.get(pk=pk)
u.set_password(form_data['password1'])
success(request, "Your Password has been updated!")
u.save()
return redirect(reverse('users:listView'))
else:
error(request, "Please check your passwords!")
return render(request, "users/users/change_password.html", context={'pk': pk})
return render(request, "users/users/change_password.html", context={'pk': pk})
class Profile(LoginRequiredMixin, TemplateView):
template_name = 'users/profile.html'
class AccountsListView(LoginRequiredMixin, ListView):
model = User
paginate_by = 15
template_name = "users/profile.html"
class AccountsUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
model = User
fields = ('username',
'first_name',
'last_name',
'email',
'image',
'is_admin',
'is_supervisor',
)
template_name = 'user_update_form.html'
success_url = reverse_lazy('users:listView')
class AccountsDelete(LoginRequiredMixin, DeleteView):
model = User
success_url = reverse_lazy('users:listView')
template_name = 'users/user_confirm_delete.html'
the problem is 99% sure in this statement:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I guess in your settings.py you have something like
MEDIA_URL = '/users/register/'
MEDIA_ROOT = 'C:/....../register'
You access "127.0.0.1:8000/users/register/ and the static(...) catches the request and produces exactly the error message you get.
That is also the reason why you do not get the usual detailed Django Error trace.
If your using generic class based views you need to have the structure like this
app_name
|
|--templates
|
| -- app_name
|
|--register.html
If the error is occuring the login url, its looking in the specifed template for register.html.

Django - serve() got an unexpected keyword argument 'documuent_root'

im trying to set up media file path / images for DRF but its not working and i cant figure out why.
i get this error:
serve() got an unexpected keyword argument 'documuent_root'
I am on mac runing django 1.11 DRF w/ python 3.6.
I have moved the settings urls to top level by why way of this link so i am one step closer although i still cant figure out why my links show 404 when i click on them.
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'src')
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
CORS_ORIGIN_WHITELIST = 'localhost:3000', #whitelists the localhost to run
views.py
from accounts.api.permissions import IsOwnerOrReadOnly
from rest_framework import generics, mixins, permissions, viewsets
from books.models import Books
from books.api.serializers import BooksSerializer
class BookViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] # authentication_classes = []
serializer_class = BooksSerializer # necessary
queryset = Books.objects.all()
lookup_field = 'id'
search_fields = ('user__username', 'content', 'user__email')
ordering_fields = ('user__username', 'timestamp')
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from . import views
from django.conf.urls.static import static
from django.conf import settings
from rest_framework import routers
from books.api.views import (
BookViewSet)
router = routers.SimpleRouter()
router.register(r'books', BookViewSet) # --> http://127.0.0.1:8000/api/books/api/books/
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(router.urls)),
] + static(settings.MEDIA_URL, documuent_root=settings.MEDIA_ROOT)
Its a typo actually. You were using documuent_root , but it should be document_root.
So, change to urlpatterns = [
.... other patters,
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Django, React, Redux: Serving up images

I'm using a React/Redux frontend and a Django backend for a little project. I'm not using anything but the standard Django server for development. I'm trying to add an image field to an already existing UserProfile model. Currently I've got everything working except that Django won't properly serve up my images to either to the main React site or the admin site. When I either attempt to navigate to the url in question or use the Python requests library to directly request the media, the response is of type 'text/html'. Currently my model has the following field:
models.py
class UserProfile(models.Model):
...
...
profile_image = models.ImageField(upload_to='path_to_media')
project urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/account/', include('account.urls')),
url(r'^api/post/', include('post.urls')),
url(r'.*', views.root, name='root')
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'nattr'),
)
account urls.py
urlpatterns = (
...,
url(r'^edit_profile/(?P<user_id>[^/]+)/$',
views.edit_profile,
name='edit_profile'),
)
account views.py
def edit_profile(request, user_id):
try:
user = User.objects.get(pk=user_id)
form = UserProfileForm(request.POST, request.FILES, instance=user.profile, user=request.user)
valid = form.is_valid()
if valid:
profile = form.save()
return JsonResponse(profile.to_user())
else:
return JsonResponse({'errors': form.errors}, status=400)
except User.DoesNotExist:
return JsonResponse({'errors': 'cannot find user with that id'}, status=400)
What am I doing wrong? I've assigned my media_url & media_root; I've added the media urls to my urlpatterns. My view and form are pretty standard and I can see that the images are being uploaded to the folder structure
Django URL patterns are processed in order. You have .* before settings.MEDIA_URL so every URL, no matter what, will be caught by it. You should move the static URL above .*.
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/account/', include('account.urls')),
url(r'^api/post/', include('post.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# make sure this is always last
urlpatterns += [url(r'.*', views.root, name='root')]
Add the following in your urlpatterns
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
And also add this to your settings.py
ENV_PATH = os.path.abspath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.join(ENV_PATH, 'media/')
MEDIA_URL = '/media/'

Issue with serving uploaded files from filesystem

I made a project using Django 1.5.4 and have now a problem with serving files being uploaded locally. My urls.py look like this now:
urlpatterns = patterns('',
url(r'^$', views.home),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_ROOT, document_root='')
In models.py there is an ImageField of a class Product:
photo = models.ImageField(upload_to=MEDIA_ROOT)
and a method for displaying it:
def display_photo(self):
return '<img src="%s" />' % (self.photo)
display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True
And, finally, MEDIA_ROOT in settings.py:
MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/uploads/'
Still firebug shows an error:
GET http://127.0.0.1:8000/home/nervosa/DjangoProjects/Sit_test/uploads/cover.jpg 404 (NOT FOUND)
What did i do wrong?
Solved. I just needed to modify urls.py:
urlpatterns = patterns('',
url(r'^$', views.home),
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += patterns('',
url(r'^uploads/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
)
The whole class Product contained by models.py now looks like this:
class Product(models.Model):
title = models.CharField(max_length=50)
height = models.FloatField(max_length=10)
weight = models.FloatField(max_length=10)
color = models.CharField(max_length=7)
photo = models.ImageField(upload_to='products_photo/')
thumbnail = ThumbnailerImageField(default='', upload_to='products_photo_thumbnails')
def __unicode__(self):
return self.title
def display_photo(self):
return '<img src="%s" />' % (self.photo.url)
display_photo.short_description = 'Photo of a product'
display_photo.allow_tags = True
Sorry for not providing my ModelAdmin - here it is:
class ProductAdmin(admin.ModelAdmin):
fieldsets = [
('Title of a product', {'fields':['title']}),
('Parameters of a product', {'fields':['height', 'weight', 'color']}),
('Upload a photo', {'fields':['photo']}),
('Photo', {'fields':['display_photo']}),
]
list_display = ['title', 'height', 'weight', 'color']
readonly_fields = ('display_photo',)
admin.site.register(Product, ProductAdmin)
And finally - MEDIA_ROOT and MEDIA_URL - in my case they should be:
MEDIA_ROOT = '/home/nervosa/DjangoProjects/Sit_test/'
MEDIA_URL = '/uploads/'
Now image is displayed properly after uploading. Thanks for attention and answers.