Why should I only allow image upload during DEBUG mode? - python

I want to add a field for users to edit their profile pictures and checked out a few tutorials. However, every tutorial I've found included some form of this in urls.py:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
Why can't I do this with deployment and if it has to be like this? Is there any way for me to allow users to upload and modify their profile pictures?
Any help would be appreciated. Thanks.

This is because in production mode django stop serving static files.
Thus static url will result in a page not found.

Related

Django URL and Template with inbuilt authentication

I am a Django Beginner, I started by reading WS Vincent..The book created a customUser model in a separate App name USERS. Also, AUTH_USER_MODEL = 'users.CustomUser' has been set up. I have below question related to URLS and Templates . Any help will be appreciated
I have been reading that the Default Django login path will go to /accounts/login. However , when I used {% url login %} in template base.html it routed to users/login. That would be coz fo Auth_user_model, but I want to be sure how the above tag would fit in below URL's because there is still no accounts/login URL. If it is getting that from auth.urls package then it only has everything starting with /accounts not /user. I did a packet capture thinking it might be translating to account/login but destination was still users/login. .I hope I was able to explain my query. Please help.
urlpatterns = [
path('admin/', admin.site.urls),
path('users/', include('users.urls')), # new
path('users/', include('django.contrib.auth.urls')),# new
path('', TemplateView.as_view(template_name='home.html'),name='home'), # new
]
(if i understand your question correctly) there is a default value in settings.py which you have to override
https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-LOGIN_URL

Django how urls.py how to add url / problem in adding url

i created my first app in Django. and when i am running it in my chrome browser using the url
http://127.0.0.1:8000/hello
It didn't open but when i used the url:-
http://127.0.0.1:8000/
It worked, don't know why. I added the url in urls.py file. like this.
path('hello', views.hello_world_view, name='hello')
suggest me where i am going wrong.
Thanks
URL patterns require a trailing slash in order to work
path('hello/', views.hello_world_view, name='hello')
Write like this
path('hello/', views.hello_world_view, name='hello')
read this djangoproject for URLs dispatcher it will help you how to configure URL into Django

Login page doesn't show in django all-auth

I am having a problem with django allauth login page. I was able to complete the tutorial django all-auth, however I encountered a problem with the login page when I tried http://localhost/accounts/login/ nothing is showing but only a blank page.
And the tutorial does not show how to create the login page, so I guess that is the last step I should be working on.
What I did until now is this,
settings.py
INSTALLED_APPS = (
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
)
SOCIALACCOUNT_PROVIDERS = {'google': {'SCOPE': ['email'],
'AUTH_PARAMS': {'access_type': 'online'}
}
}
# Django all auth settings
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
urls.py
url(r'^accounts/', include('allauth.urls')),
Also I already added a social application in the Django admin and it's required fields.
Thank you soo much, your help is much appreciated.
Piggybacking off of #bharat's post and for others stumbling across this post trying to figure out why nothing is being displayed...
django-allauth comes with templates that have all of the content that you already need and even a few templates that you may have not added yourself. But, as comes with the templates, comes the project-owners project structure.
If you want all of your django-allauth pages to use the content that it comes with, you will need to copy and paste the templates into your template folder and then update them to work with your project structure...
So, you will need to do to the typical installation process and then add all of the templates as well. I just can't find this documented anywhere. You can see all of the templates here.
EDIT: If you look closely at the top of the templates page it says 'Overridable templates' which clearly answers the issue that I had for hours. But, if you missed that as I did. There's your issue.
If you're not planning on using the django-allauth views though, you don't have to. You can totally implement social-authentication without using all of the views. So, it's up to you... But, once you implement them you will realize that it does save you an incredible amount of time in setting your future projects up. It's just a matter of getting it working the first time.
There are likely a couple of things you will have to change in the templates for everything to work.
Update the <title> block that is {% block head_title %}.
Update the {% block content %} to whatever you call your body block.
Import django-crispy-forms with {% load crispy_forms_tags %}.
Make all of your forms crispy.
If you're using all of the django-allauth views. Chances are you want an account view so you will need to create that as well because that does not come in the views.
But, you can totally just use the same pattern that django-allauth does and create something like accounts/<username>/
Having a look at this GitHub Repo would help you to create a login page:
https://github.com/pennersr/django-allauth/blob/master/allauth/templates/account/login.html.
You should also ensure that the login page has appropriate url-mappings on urls.py file.
Hope, that helps.

Using Django: How to serve a file for download?

Let me start by saying I have spent a lot of energy on this and any input is very valuable to me at this point. Now, onto my question:
What I have working: My website provides a simple interface for users to upload a file in which they will be given a key. The file is saved to the server and the key is generated using a modern, secure encryption algorithm. These details are not important to the question at hand.
What I want to implement: On a download page, the user can enter the key and the file will be downloaded to their computer. Want I want to know is how to provide a user with this ability to download an uploaded file. To put it simply, I just want to allow users to download a file in the MEDIA_ROOT folder.
I am using class-based views, so my urls are:
urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.conf import settings
from fileupload.views import FileDownloadView, GetFileView
urlpatterns = patterns('',
url(r'^key/?$', FileDownloadView.as_view(), name='getkey'),
url(r'^download/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}, GetFileView.as_view()),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Please provide me with the basic idea on what functions I should use in my views to actually download the file. I am still in development so I want to take advantage of Django's ability to serve files, not Apache's. I will consider other options if I go into production. Whatever code I need to post, I can post.
Thank you!
If the key grants them access to the file, why not have the key be the file name? That is, when the file is uploaded, create a long key (say 64 characters long) and rename the file to the key name. Then simply serve up that file using the static.serve method when it is requested.
The benefits of this approach are: 1) You don't need to map the key to the file in the database, and 2) you don't need to validate the key when retrieving the file. If the file name is found, the key is valid.
Basically I told you, Django should not serve files in production.
After is it possible yes:
You can serve a file tree with django.conf.urls.static.static(), as a view in your urls.py. Example:
urlpatterns = patterns('',
...
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...
)
Or use whitenoise, a package for server static file with Python web apps. It is very simple to use, only change your wsgi.py file like this:
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
And use 'whitenoise.django.GzipManifestStaticFilesStorage' as STATICFILES_STORAGE.
Along with the url file I have shown in the original question, all I needed to do from here was to provide an HttpResponseRedirect('/path/of/my/media/file')
Very simple!

Serving static files from root of Django development server

My goal is to have an Angular project being served from the root of my development server. The files will be completely static as far as Django is concerned, no Django template processing is needed. The angular project will then make resource calls to a Django project located at /api/ on the same development server, which will then return json results generated from a view for the Angular project to process.
I assumed it would be as easy as adding the following to my urls.py file.
url(r'^/', 'django.views.static.serve', {
'document_root':'/Users/kyle/Development/project/site/app',
}),
Or
+ static("^/$", document_root="/Users/kyle/Development/project/site/app")
To the end of the urlpatterns.
With /project/site/app being the directory with the Angularjs files.
However, both of these leave me with 404 errors.
I'm open to changing the structure of the project if a more obvious solution exists.
You need to serve both index.html and your static files on / which is done like this in Django 1.10:
from django.contrib.staticfiles.views import serve
from django.views.generic import RedirectView
urlpatterns = [
# / routes to index.html
url(r'^$', serve,
kwargs={'path': 'index.html'}),
# static files (*.css, *.js, *.jpg etc.) served on /
url(r'^(?!/static/.*)(?P<path>.*\..*)$',
RedirectView.as_view(url='/static/%(path)s')),
]
See this answer where I wrote a more complete explanation of such a configuration – especially if you want to use it for production.
It turned out that it was a combination of 2 things, as shavenwarthog said, it shouldn't have the slash. Also, it needed a regular expression to direct it to the file. The final line ended up being:
url(r'^(?P<path>.*)$', 'django.views.static.serve', {
'document_root':'/Users/kyle/Development/project/site/app',
}),
I can then access files like
http://localhost/beer.jpg
note that by default Django won't serve a directory listing. Do you still get a 404 if file /Users/kyle/Development/project/site/app/beer.jpg doesn't appear as http://localhost/beer.jpg ?
in urls.py URLs don't start with a slash; compare url(r'beer') with url(r'^/beer')
I suggest just going for the standard STATIC support. It's awkward, but lets you serve file simply during development, and switch to a 3rd party server (ie Nginx) for production:
https://docs.djangoproject.com/en/dev/howto/static-files/

Categories

Resources