0

The following is my device model:

class Device(models.Model):
    device_type         = models.ForeignKey(DeviceType,to_field='device_type')
    serial_number       = models.CharField(max_length=200,unique=True)
    in_use_by           = models.ForeignKey(User,to_field='username')
    brand               = models.CharField(max_length=200,default="-", null=False)
    model               = models.CharField(max_length=200,default="-", null=False)
    type_number         = models.CharField(max_length=200,blank=True,null=True, default = None)
    mac_address         = models.CharField(max_length=200,blank=True,null=True, default = None)
    invoice             = models.FileField(upload_to='', null=True)

Here, the invoice field is not of use to me in my website but, it is of use to me as a admin. What I am basically trying to do is, if a device request is accepted then, I will upload the invoice of the device into my sqlite db using the admin panel. I am a newbie to Django and hence, require help for this purpose. Also, I will only upload file through django admin. How should I achieve this? What should I write in upload to parameter so that the file is stored in database?

Aishwary Shukla
  • 450
  • 1
  • 7
  • 21

1 Answers1

0

You need to configure your Admin with the required fields you want to edit.

In admin.py:

class DeviceAdmin(admin.ModelAdmin):
    fields = ('device_type', 'invoice', ..)

admin.site.register(Device, DeviceAdmin)

Django Admin field reference

EDIT:

upload_to parameter is the path where you need to store the file. Generally it is the MEDIA_ROOT path as configured in Django settings.

models.FileField(upload_to=settings.MEDIA_ROOT, null=True)

To serve this during development:

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Refer

In the DB, only the URL of the file will be stored.

Pranav Aggarwal
  • 605
  • 4
  • 9
  • But what should be passed in upload_to parameter in FileField so that my file ges stored in sqlite3 db? – Aishwary Shukla Jun 11 '18 at 08:12
  • `upload_to` parameter is for the directory you want to save the file in. And the path should come from settings.py file. When you retrieve this field it will give you URL of the file. – Pranav Aggarwal Jun 11 '18 at 08:18
  • Ok, there must be some way to store files in DB right? – Aishwary Shukla Jun 11 '18 at 08:23
  • Edited the answer for `FileField`. Django's `FileField` only stores link. If you need to store the file in the DB you need to look at storing blob in DB. For which you need to create a Custom Field dependent on your DB. Refer: https://stackoverflow.com/questions/4915397/django-blob-model-field – Pranav Aggarwal Jun 11 '18 at 08:32