Implement file upload in admin interface

81 views
Skip to first unread message

Ben Lau

unread,
Nov 27, 2008, 10:13:46 AM11/27/08
to django...@googlegroups.com
Hi all,

I would like to implement a data upload feature in admin interface
for my application. A form with file upload field will be show for a
data model.
The file should be a XML file which is generated by another program
and contain more than one record of data.

Anybody implemented similar thing before ? Seem that I could
implement it by override ModelAdmin, but it need to modify a lot of
thing.

Thanks.

redbaron

unread,
Nov 28, 2008, 10:08:08 AM11/28/08
to Django users
I try to implement same thing.I need some place where I could upload
file, django should parse it and populate database with new data. To
make it more ease I defined new model BatchUpload with only one field
batch. Now I need to customize upload handler method in admin site.
Could anyone give advice how to do it best way?

Ben Lau

unread,
Nov 28, 2008, 11:53:42 AM11/28/08
to django...@googlegroups.com
Hi redbaron,

My approach is to subclass ModelAdmin to implement a import command .
It should need to override the __call__() and create a import_view()
function to handle the import form. Example:

class XXXAdmin(admin.ModelAdmin):



def __call__(self, request, url):

if url == "import":

return self.import_view(request)

else:

return admin.ModelAdmin.__call__(self,request,url)


However, I am still studying how to make the import_view function by
reading the source of ModelAdmin.add_view(). It use quite a lot of
undocumented functions..

redbaron

unread,
Nov 28, 2008, 1:28:57 PM11/28/08
to Django users

My current solution is.

1. Define new model Batches:

class Batches(models.Model):
batchfile = model.FileField(upload_to="noop")

2. In admin.py define new form with custom validators:

class BatchUploadForm(forms.ModelFormi):
class Meta:
model = Batches

def clean_batchfile(self):
data = self.cleaned_data['batchfile'].read() #here we've got
uploaded file content
ret = your_processing_routine(data) #if file is wrong
processing returns error message
if ret:
raise forms.ValidationError(ret)


3. Register customized ModelAdmin for Batches:

class BatchesAdmin(admin.ModelAdmin):
form = BatchUploadForm #here we've replaced default form to our
one

def save_model(self, request, obj, form, change):
pass #nothing save to base actually

Ben Lau

unread,
Nov 30, 2008, 4:36:23 PM11/30/08
to django...@googlegroups.com
hi,

It is mush easier then my approach. Thanks a lot!
Reply all
Reply to author
Forward
0 new messages