Entry(models.Model): firstname = models.CharField(max_length=200) img_url = models.URLField(max_length=200) w_url = models.URLField(max_length=200) api/models.py With Django, we define a class representing the data structure • https://docs.djangoproject.com/en/1.9/ref/models/fields/
path image/png path image/jpg The image path and the mime type are stored in the database POST add/ uploads The image is stored in the upload directory Image
path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads/') tsans/settings.py
models.CharField(max_length=200) webpage = models.URLField(max_length=200) class Image(models.Model): entry = models.ForeignKey(Entry, unique=True) image = models.ImageField(upload_to='WebDirectory') mimeType = models.CharField(max_length=20) WebDirectory/models.py where to store uploaded files use FileField for generic files We need to record the MIME type (see serving uploaded file) entry foreign key
def add(request): e = Entry(name = request.POST['name'],\ webpage = request.POST['website']) e.save() i = Image(entry = e,\ image = request.FILES['file'],\ mimeType=request.FILES['file'].content_type) i.save() return HttpResponseRedirect(reverse('index')) WebDirectory/views.py get the file from the HTTP request Not secure but we will talk about security later get the MIME type
to control (controller) the file - getImage Reference the image using an identifier • automatically generated hash code • or database entry id (primary key in the database)
uploads Retrieve the image from the upload directory (this is done automatically by Django) Database img mime path image/png path image/jpg Get the image path and mime type from the database based on its id Return a HTTP response of the corresponding mime type Image
return HttpResponse(i.image.read(), content_type=i.mimeType) WebDirectory/views.py get the file from the database return an HTTP response of the corresponding MIME type