Simple App From Scratch and Upload File with Django Framework

  1. Python Version ≥ 3.6
  2. Django Framework
  3. Python venv library
> python -m venv venv
For Mac OS X
> source venv/bin/activate
For Windows
> venv\Scripts\activate
# requirement.txt 
# Django Latest version
Django==3.2.4
> pip install -r requirement.txt
> django-admin startproject django_file_upload_example
For Windows $ python manage.py startapp productMac OS X$./manage.py startapp product
from django.db import modelsclass FileUpload(models.Model):
title = models.CharField(max_length=100)
doc_file = models.FileField(upload_to="documents/")
image_file = models.ImageField(upload_to="images/")
from django import forms
from django.forms import fields
from .models import FileUpload
class UploadForm(forms.ModelForm):
title = forms.CharField(max_length=100)
doc_file = forms.FileField()
image_file = forms.ImageField()

class Meta:
model = FileUpload
fields = ['title', 'doc_file', 'image_file']
  • {{ form.as_table }} will render them as table cells wrapped in <tr> tags
  • {{ form.as_p }} will render them wrapped in <p> tags
  • {{ form.as_ul }} will render them wrapped in <li> tags
<p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>

Configure the Product app to “django_file_upload_example” main project.

Database Migration

In Mac OS X
> ./manage.py makemigrations
In windows > python manage.py makemigrations
1. First argument contains any “url or path or pattern” in string,2. Second argument used for declare the view and view function,3. Third one contains name name of the “route”,given name is the navigation of  specific route.
For windows in virutal environment> python manage.py migrateFor Mac OS x virtual environment> ./manage.py migrate
For Windows in virtual environment$ python manage.py runserver 0.0.0.0:8080For Mac OS x in virtual environment$ ./manage.py runserver 0.0.0.0:8080
{% for <Object> in <List> %} # start the loop
....statement....
{% empty %} # check the list is empty or list length is 0 and enter into this block
.... empty statement ....
{% endfor %} # end for loop
<img height="100px"
width="100px"
src="{{product.doc_file.url}}" />
# {{ }} are is called as template expression, you can declare the python variable inside the expression, i use to show the product image url by following "product.doct_file.url" python variable in it

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store