Created
March 29, 2020 22:12
-
-
Save ankit11421/a15d79a18a0b8a7f67fece0a758cf638 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Paste this at the bottom of settings.py file | |
STATIC_URL = '/static/' | |
STATICFILES_DIRS = [ | |
os.path.join(BASE_DIR, "static_my_proj"), | |
] | |
STATIC_ROOT = os.path.join(os.path.dirname( | |
BASE_DIR), "static_cdn", "static_root") | |
MEDIA_URL = '/media/' | |
MEDIA_ROOT = os.path.join(os.path.dirname( | |
BASE_DIR), "static_cdn", "media_root") | |
STEP 2: Paste this in Main urls.py file of the project at the bottom | |
from django.conf import settings | |
from django.conf.urls.static import static | |
if settings.DEBUG: | |
urlpatterns = urlpatterns + \ | |
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) | |
urlpatterns = urlpatterns + \ | |
static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | |
Step 3: | |
In model add a image field like this | |
image = models.ImageField( | |
upload_to=upload_image_path_posts, null=True, blank=True) | |
At the top of models.py just after imports add this | |
import os | |
import random | |
def upload_image_path_posts(instance, filename): | |
new_filename = random.randint(1, 9910209312) | |
name, ext = get_filename_ext(filename) | |
final_filename = '{new_filename}{ext}'.format( | |
new_filename=new_filename, ext=ext) | |
return "posts/{new_filename}/{final_filename}".format( | |
new_filename=new_filename, | |
final_filename=final_filename | |
) | |
def get_filename_ext(filepath): | |
base_name = os.path.basename(filepath) | |
name, ext = os.path.splitext(base_name) | |
return name, ext | |
STEP 4: Now make the migrations and migrate them | |
STEP 5: You can access the image from your model in your HTML file like this: | |
<img src="{{post.image.url}}" alt="" width="40%" height='30%'> | |
Set height and width as per your need!! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment