Django "TemplateView" and "/media/" url conflict - python

I am writing an SPA with Django 1.11 (switching to 2.0 is no an option), as backend, getting all the data from Django Rest Framework API and I route my app via React routing.
Here is my my main urls.py :
urlpatterns = [
url(r'^api/', include('text_cms.urls')),
url(r'^api/', include('photos_admin.urls')),
url(r'^admin/', admin.site.urls),
url('', TemplateView.as_view(template_name='index.html'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And here is my settings.py file:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
MEDIA_URL = '/media-files/'
The issue is, that the particular url setting
url('', TemplateView.as_view(template_name='index.html'),
is messing up media url, and files uploaded by user cannot be reached by url link, even though they are saved to folder, I just get a 404 error. When I comment my "Template as view" url, delete it or just give it another address, like url('main/') - everything works fine again.
I've tried to serve the template from the other app and registering it in the main urls.py file, but it did not work too
urlpatterns = [
url(r'^', views.IndexView),
]
views.py
def IndexView(request):
return render(request, 'main/index.html', {})

url('', TemplateView.as_view(template_name='index.html'),
You are missing a closing ). It also appears that you url pattern is incorrect as well. Should be
url(r'^$' , TemplateView.as_view(template_name='index.html')),

Related

django The current path,didn't match any of these

i want to try another apps in django but i got problem when access another apps.
Page not found
tree:
main:
search:
index.html
scrape.html
preprocessing:
index.html
the scenario like this. from scrape.html i want to access index.html in preprocessing but got an error path not found. I've done to add apps in settings.py
main url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('search.urls')),
path('preprocessing/', include('preprocessing.urls')),
]
search url.py
urlpatterns = [
path('', views.index,),
path('scrape/',views.scrape,),
]
slice of scrape.html:
Preprocessing
preprocessing url.py
path('', views.index),
let me know where did I go wrong, thx for your help
Your anchor tag is written as:
<a href = "/preprocessing" ...>
The problem here is that your url pattern is like 'preprocessing/', notice that it ends in a trailing slash while your anchors url doesn't. Furthermore in your settings you set APPEND_SLASH = False.
Normally when Django finds a url not ending in a trailing slash it appends a slash to it and redirects the user to this new url. But you have stopped this behaviour by setting APPEND_SLASH = False. As the first step I would advice you to change this back to APPEND_SLASH = True.
Next you should always name your urls and use those names to refer to the urls. So your urlpatterns should be:
main url.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('search.urls')),
path('preprocessing/', include('preprocessing.urls')),
]
search url.py
urlpatterns = [
path('', views.index, name='index'),
path('scrape/',views.scrape, name='scrape'),
]
preprocessing url.py
path('', views.index, name='preprocessing'),
Now in your templates you would simply use the url template tag:
Preprocessing

Django login required middleware not working

I'm new to Django and I'm trying to implement the django-login-required-middleware in my project to be able to direct all the users who are not logged in to the index page with login view.
I Installed the pip install django-login-required-middleware, added login_required in my INSTALLED_APPS settings and added login_required.middleware.LoginRequiredMiddleware in my MIDDLEWARE. Then in my settings I ignore the views that I want to display to users even when They're not logged in.
settings.py
LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [
'index',
'register'
]
However, when I run the server, I get the error
Not Found: /accounts/login/
[22/Jan/2020 12:27:56] "GET /accounts/login/?next=/ HTTP/1.1" 404 4417
and in my browser:
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/login/?next=/
It seems like it automatically directs me to the accounts, even though my app is called movies_app and not accounts. Anyone knows how to fix this? Thank you very much!
urls.py
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from .views import editprofile
from . import views
app_name = 'movies_app'
urlpatterns = [
path('', views.login, name='login'),
path('browse/', views.index, name='index'),
path('register/', views.register, name='register'),
path('movies/', views.allMovies, name='allMovies'),
path('movies/<int:pk>/', views.movie, name='movie'),
path('movies/<int:pk>/rate', views.addRating, name='rate'),
path('my-list/', views.myMovies, name='my-list'),
path('my-list/<int:pk>/delete', views.deleteFavoriteMovie, name='favorite-movie-delete'),
path('profile/', views.profile, name='register'),
path('editprofile/', views.editprofile, name='editprofile'),
path('logout/', views.logout, name='logout'),
path('movie-video', views.movieVideo, name='movie-video')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your middleware is working and redirecting you to the default login page, /accounts/login/.
To customise the default login page, add LOGIN_URL to your settings, e.g.
LOGIN_URL = '/login/'
Finally, you have app_name = 'movies_app', so you should include this when referring to URL patterns from this app. For example, yourLOGIN_REQUIRED_IGNORE_VIEW_NAMES` should be:
LOGIN_REQUIRED_IGNORE_VIEW_NAMES = [
'movies_app:index',
'movies_app:register'
]

Django Rest Docs Show Wrong Urls

I'm using the Django Rest Docs to describe my API built in the Django Rest Framework, but the urls it's displaying are incorrect. Specifically, they prepend /admin/ to everything:
These paths should be /session-auth/, /session/, etc. I don't know why the /admin/ is being preprended. Here's my urls.py file:
# URLs for serving static media and user uploaded media
urlpatterns = patterns('',
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_URL, 'show_indexes': True}),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += patterns('myapp.views',
#Home page
(r'^$', 'home'),
url(r'^docs/', include('rest_framework_docs.urls')),
# Refresh all locations
(r'^admin/refresh-all-locations/$', 'refresh_all_locations'),
# Admin all locations page
(r'^admin/all-locations/$', admin.site.admin_view(all_locations)),
# Admin
(r'^admin/', include(admin.site.urls)),
####API urls####
# Authenticate a user
url(r'^session-auth/$', API.Session.SessionAuth.as_view(), name='authenticate'),
# Update user password or email
url(r'^session/$', API.Session.SessionDetail.as_view()),
# Get the detail on one entity
url(r'^entities/(?P<entity_id>[0-9]+)/$', API.Entity.EntityDetail.as_view()),

Django Admin: Determine correct image upload path

I am new to Django and I am currently having problems in showing uploaded images in Django Admin. I have followed many posted Q and A here in stackoverflow but of those worked in my problem. I hope any active of the coding ninja here could help me with this problem. Here is the detailed view of the problem:
I have defined the MEDIA_ROOT and MEDIA_URL in settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = "/media/"
This is my upload model in models.py:
from django.utils.html import mark_safe
class ImageDetails(models.Model):
image = models.ImageField(null=True)
def image_img(self):
if self.image:
return mark_safe('<img src="%s" height="125px" width="125px"/>' % (self.image.url))
else:
return '(No image found)'
image_img.short_description = 'Thumbnail'
In my Application urls.py:
urlpatterns = [
url(r'^inputImage', views.inputImage, name='inputImage'),
url(r'', views.index),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
In my admin.py:
class ImageDetailsAdmin(admin.ModelAdmin):
fields = ["image"] #for file upload
list_display = ("image_img",)
admin.site.register(ImageDetails, ImageDetailsAdmin)
The image was successfully stored at ProjectDIR/media. The HTML returns the url: http://127.0.0.1:8000/media/imagename.jpg at img tag. But the page fails to load the image (I will be redirected to index page whenever when using the url http://127.0.0.1:8000/media/imagename.jpg). I am using Django version 1.10
As suspected, this problem is about URLs in Django. The problem occurred because I declared the following urlpattern in an app urls.py:
url(r'', views.index, name='index'),
I solved the problem by changing the code to:
url(r'^$', views.index, name='index'),
And adding the following code at the project's main urls.py:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Python Page 404 not found

New to Python, just starting up with a Issue reporting app which involves an API module.
My Urls.py file:
urlpatterns = patterns('',
url(r'^api/', include('api.urls')),
)
My api.urls file
urlpatterns = patterns('api.v1',
# Examples:
# url(r'^$', 'newproject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
# authentication / session managemen
url(r'^auth/profile/me/$', 'account', name='my-account'),
url(r'^auth/profile/$', 'new_account', name='new-account'),
url(r'^auth/session/(?P<key>[a-z0-9]{64})/$', 'session', name='existing-session'),
url(r'^auth/session/$', 'new_session', name='new-session'),
....
My Web Page 404 Error
Using the URLconf defined in newproject.urls, Django tried these URL patterns, in this order:
^api/
The current URL, , didn't match any of these.
I might be overlooking a mistake I made...
Help Please?
Using Django 1.9.7
replace url(r'^api/', include('api.urls')),
with url(r'', include('api.urls')),

Categories