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)
Related
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.
I am trying to create a blog and to display image for each post. i am trying to display user-uploaded images on a webpage. When I upload the image files using the Django admin interface (I made a model for Post images with an ImageField), the image is stored in /media/images correctly. But I can't display the image on my webpage. However, when I inspect my template with GoogleChrome, the path of my files are ok but there is a 500 error (about-us-2.jpg:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error).
Media Settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'core/static'),
)
Project urls.py:
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin' , admin.site.urls),
path("", include("authentication.urls")),
path("", include("app.urls")),
]+ static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
App urls.py:
rom django.urls import path, re_path
from django.conf.urls import include, url
from app import views
from . import views
urlpatterns = [
path('', views.index, name='home'),
url(r'^blog$', views.blog_view, name ='blog'),
url(r'^blog/(?P<id>[0-9]+)$', views.post_view, name ='blog_post'),
re_path(r'^.*\.*', views.pages, name='pages'),
]
Views.py
def blog_view(request):
query = Post.objects.all().order_by('-date')
context = {'post_list' : query}
return render(request, 'blog/blog.html', context)
template : Blog.html
{% for post in post_list %}
<img src="{{ post.image.url }}" class="card-img-top rounded-top">
{% endfor %}
models.py
class Post(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, blank=True)
image = models.ImageField(blank=True, upload_to="images/")
Try this approach:
MEDIA_ROOT = os.path.join(BASE_DIR, "APPName", "media")
MEDIA_URL = "/media/"
You can then find images under:
<img src="media/test.png">
The folder "media" is in the main dir of the Project (not the app!):
Project
media
static
APP
templates
views.py
locally its working fine there is no error
when i deploy django on cpanel(shared hosting) all things are working fine
but when i submit the form without image it submitted successfully.
if i choose an image and submit the form. will get page not found (404) error
i tried to disable imageField from models.py and from every place where it has used. then i checked its working fine with imageField its not working
i have changed the media_root and media_url with static_root and url. but still its not working.
models.py
from django.db import models
from django.urls import reverse_lazy
# Create your models here.
class Eventz(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='events')
class Meta:
ordering = ['-id']
db_table = 'eventz'
def get_absolute_url(self):
return reverse_lazy('eventz')
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from django.views.generic import CreateView, UpdateView, DeleteView, ListView, TemplateView, RedirectView
from .models import Eventz
class EventzCreate(CreateView):
model = Eventz
fields = ['name', 'image']
template_name = 'events.html'
def get_context_data(self, **kwargs):
context = super(EventzCreate, self).get_context_data(**kwargs)
context['events'] = Eventz.objects.all()
return context
urls.py
from django.contrib import admin
from django.urls import path, include
from . import settings
from django.contrib.staticfiles.urls import static
from upload import views
from dashboard1.views import EventzCreate
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.UploadCreate.as_view(), name="upload" ),
path('eventz/', EventzCreate.as_view(), name='eventz'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = '/home/intelexcel/public_html/static'
MEDIA_URL = '/media/'
MEDIA_ROOT = '/home/intelexcel/public_html/media'
# LOGOUT_REDIRECT_URL = 'login'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
events.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.image}}
<input type="submit" value="Save">
</form>
The name you gave to your url page for event is eventz, but in your url bar there is pattern event.
In your urls.py you should have something like:
path('event', views.event, name="eventz"),
change it to:
path('event', views.event, name="event"),
and it should work.
update your urls list with media url path something like this :-
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
update your setting.py like this
MEDIA_ROOT = '/home/dan/mysite/media/'
MEDIA_URL = '/media/'
try to execute.
python manage.py collectstatic
there was an error with path.
i have changed the action url of my form
if the form will be submit on
sec.intelexcel.com/event
i changed the action when form is submitted
sec.intelexcel.com/eventz/eventz/
it works for me
<form action="/eventz/eventz/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form.name}}
{{form.image}}
<input type="submit" value="Save">
</form>
urls.py
from django.contrib import admin
from django.urls import path, include
from . import settings
from django.contrib.staticfiles.urls import static
from upload import views
from dashboard1.views import EventzCreate
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.UploadCreate.as_view(), name="upload" ),
path('eventz/', EventzCreate.as_view(), name='eventz'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I am beginner so please bear silly questions
if i remove highlighted lines 1,2,3(+ static line) my localhost it shows normal django homepage but after adding these highlighted lines, it shows error
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/
Using the URLconf defined in portfolio.urls, Django tried these URL patterns, in this order:
admin/
^media/(?P<path>.*)$
The empty path didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
but admin page loads with no problem
#urls.py file
from django.contrib import admin
from django.urls import path
from django.conf import settings **<----- 1**
from django.conf.urls.static import static **<----- 2**
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ** <--- 3**
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
You are trying to access root page of your app.
Your main urls.py, should look like this
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/', admins.site.urls),
path('', include("exampleapp.urls"),
]
Create another app, which will handle your root page using python manage.py startapp exampleapp
in exampleapp/urls.py
from django.urls import path
from . import views
app_name = "exampleapp"
urlpatterns = [
path('', views.index, name="index)
]
In exampleapp/views.py
from django.shortcuts import render
def index(request):
return render(request, "index.html", {})
Basically, in your app's root urls.py, you have not specifified the '/' route of your app or what you can call is the index of the app. You need to do that and the above is an example of it.
In your settings.py, add this, if you haven't:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
https://docs.djangoproject.com/en/2.2/howto/static-files/
I am trying to view my uploaded image through web-browser/DRF-browsable API. So I added MEDIA_URL and MEDIA_ROOT to my setting.py file. When I trying to run the code , it showing TypeError: static() got an unexpected keyword argument 'document_root' . Here is my relevant portions of code,
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR,'Images')
MEDIA_URL = '/Images/'
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.templatetags.static import static
urlpatterns = [
# Examples:
# url(r'^$', 'project.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', index),
url(r'^health$', health),
url(r'^admin/', include(admin.site.urls)),
url(r'^sample/',sampelview),
url(r'myapp/',include(myRouter.urls)),
url(r'^test/$', testRequest),
]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
This error is due to you are imported wrong References of static.Try to use from django.conf.urls.static import static instead of from django.templatetags.static import static