Unable to save fileattachment into Django Model FileField - python

I am currently integrating exchange server email to my application. I am able to retrieve attachments from my emails using exchangelib. I am trying to save the attachments into my Django model filefield. However, it is not working with different errors based on different solutions I tried. Any help is appreciated. Thank you. Below are some of my code:
models.py
class Attachments(models.Model):
name = models.CharField(max_length=255)
attachment = models.FileField(upload_to="attachments/")
views.py
for attachment in item.attachments:
if isinstance(attachment, FileAttachment):
attachmentlist.append(attachment.name)
saveattachments = Attachments(
name=attachment.name,
attachment=(attachment.content)
)
saveattachments.save()

Please look an following snippet and try to do same in you code
from django.core.files.base import ContentFile
...
saveattachments = Attachments(name=attachment.name)
saveattachments.attachment.save(attachment.name, ContentFile(attachment.content))
saveattachments.save()

Related

automate file upload in django

I want to monitor a folder (which receives new csv file weekly)and add that file to my django model . The purpose simply is to automize upload procedure. Even if there is a way with selenium to upload each new file (whenever arrived in the folder) that would be fine too my upload page is the default django admin page , any help would be appreciated
from django.db import models
class FilesAdmin(models.Model):
adminupload=models.FileField(upload_to='media')
title=models.CharField(max_length=50)
def __str__(self):
return self.title

How to serialize multiple files in Django

I am trying to serialize multiple files, send the files using 'Postman' and have tried several ways to save several files at once.
This is the model:
class PrtFiles(models.Model):
file_name = models.FileField(null=True, blank=True)
And I getting this request in my view in Django:
<MultiValueDict: {'file_name[0]': [<InMemoryUploadedFile: Inventario Personal_Users [SHORT].xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>], 'file_name[1]': [<InMemoryUploadedFile: Planilla_de_Usuarios_MEL [NEW][SHORT].xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]}>
Whit this Request in Postman:
enter image description here
Any method that to do that?
P.S. I'm beginner with Django, thanks beforehand.
Iterate over the files where you can see the request.
def save_to_model(files):
for f in files:
m = PrtFiles()
m.file_name = f
m.save()
This is the idea what you can do it. I hope you'll implement a better way.

Error when using django-admin-multiupload and django-imagekit together

At the moment I'm on my way using the django-imagekit to show thumbnails in an image-heavy view of a gallery app. For this purpose I'm using the 'model-method', means I'm creating the thumbnails within the model.
Now with the comfort of the admin in mind (upload multiple picture at once) I also want to implement a multi-upload form in the admin-view. To ease things a little bit I tried to use an app I found on GitHub, django-admin-multiupload (I'm not able to link to it because of my low reputations but that's the exact name for it on GitHub).
When I only use django-imagekit, everything works fine and I get nice thumbnails, just like expected. When I only use django-admin-multiupload, everything works fine and I'm able to upload multiple images just like expected.
The problem starts when I'm using both apps at the same time. The multiupload works still fine but when I'm opening the view, and actually implementing the thumbnail (only using both and not implementing the thumbnail works fine), where the thumbnails should be shown I will get the following error:
OSError at /gallery/ - decoder jpeg not available
You can see the full error here: http://pastebin.com/gtVYEeG7
My confusion starts when starting only the single app and it works. So as far as my knowledge goes, all PIL issues could not be present.
To provide some more information: I'm using a virtualENV with the following list of packages:
pip
django
PIL
pilkit
django-imagekit
django-amdin-multiupload
To also provide some of my implementet code, here it is:
File: models.py
class Image(models.Model):
"""the model for the images"""
# the foreign key from the event
event = models.ForeignKey('Event', related_name='images',
blank=True, null=True)
# the image itself
# file = models.FileField('File', upload_to='gallery/images/')
file = models.ImageField('File', upload_to='gallery/images/')
image_thumbnail = ImageSpecField(source='file',
processors=[
ResizeToFill(300, 250)
],
format='JPEG',
options={'quality': 40})
# image title to represent it in the admin interface
image_name = models.CharField(max_length=35, default='img')
# publication date of the image
pub_date = models.DateTimeField('date published',
auto_now_add=True)
# for a better representation of the image
def __str__(self):
return self.image_name
File: admin.py
(this one is mostly as suggested in the example from the django-admin-multiupload repo, can be viewed here: https://github.com/gkuhn1/django-admin-multiupload/blob/master/example/gallery/admin.py)
from django.contrib import admin
from django.shortcuts import get_object_or_404
from gallery.models import Event, Image
from multiupload.admin import MultiUploadAdmin
# Register your models here.
# allows inline add of single images
class ImageInlineAdmin(admin.TabularInline):
model = Image
# used to define the process_uploaded_file function
# so it will not be duplicated in the Admin-Classes
class GalleryMultiuploadMixing(object):
def process_uploaded_file(self, uploaded, event, request):
image = event.images.create(file=uploaded)
return {
'url': image.file.url,
'thumbnail': image.file.url,
'id': image.id,
'name': image.image_name
}
# admin class for event model
class EventAdmin(GalleryMultiuploadMixing, MultiUploadAdmin):
inlines = [ImageInlineAdmin,]
multiupload_form = True
multiupload_list = False
def delete_file(self, pk, request):
obj = get_object_or_404(Image, pk=pk)
return obj.delete()
admin.site.register(Event, EventAdmin)
# admin class for image model
class ImageAdmin(GalleryMultiuploadMixing, MultiUploadAdmin):
multiupload_form = False
multiupload_list = True
admin.site.register(Image, ImageAdmin)
File: index.html
<td><img class="img-responsive" src="{{ image.image_thumbnail.url }}" /></td>
If there is any need for additional information please don't hesitate to ask.
Thank you in advance and I appreciate any help.
Edit: Today I tried another way and recognized that the error is only appearing to images that were uploaded with the django-admin-multiupload and not if only images are shown that were uploaded with the normal method. Maybe this could help to find a solution.
This error was mainly caused by a broken database that could be fixed by going back to an older version and reimplementing the new code. So there is no problem in django-admin-multiupload or django-imagekit.

Uploading files in django admin, download through public site

I am running a Django website and I want to be able to upload a file through my admin panel and then have visitors to the main site be able to download it. I am running my site using Django-nonrel, Django FileTransfers and Google App Engine. I believe the upload functionality is working correctly as I am able to see the file in my App Engine Blob Storage. What I can't seem to figure out is how to present a download link to the specified file on the public website. I have pasted the relevant classes below:
I have an app called Calendar, that has the following model:
class CalendarEvent (models.Model):
start = models.DateTimeField(auto_now=False, auto_now_add=False)
end = models.DateTimeField(auto_now=False, auto_now_add=False)
title = models.CharField(max_length=500)
description = models.TextField()
file = models.FileField(upload_to='uploads/%Y/%m/%d/%H/%M/%S/')
Here is the view:
def calendar(request):
events = CalendarEvent.objects.exclude(start__lt=datetime.datetime.now()).order_by('start')
return render_to_response('home/calendar.html',{'events': events},context_instance=RequestContext(request))
def download_handler(request, pk):
upload = get_object_or_404(CalendarEvent, pk=pk)
return serve_file(request, upload.file, save_as=True)
Here is my admin:
class calendarAdmin(admin.ModelAdmin):
list_display = ('title','start','end')
admin.site.register(CalendarEvent, calendarAdmin)
Finally, here is the relevant part of my template:
{% for e in events %}
{% url Calendar.views.download_handler pk=e.pk as fallback_url %}
Download
{% endfor %}
{% firstof e.file|public_download_url fallback_url %} is just returning blank, i'm not sure where I am going wrong.
The GAE blob store does not support public download according to the documentation here, so if you use the default backend for public download urls, it returns None. So my guess is that e.file|public_download_url always return None. You could verify that.
Then I think your template is wrong. You're trying to access e.views.download_handler where it should be Calendar.views.download_handler if your app is named Calendar.
I think the sample on the django-filetransfers page is error prone because the variable used in the template loop has the same name as the sample app: "upload".
If this doesn't fix it, could you post your urls.py from Calendar app. It could be that the template's url method is not able to resolve the url for Calendar.views.download_handler if there is no mapping in urlpatterns.
You should have something like
urlpatterns = patterns('Calendar.views',
...
(r'^download/(?P<pk>.+)$', 'download_handler'),
...
)
in this file.
I don't see anything special, eg
Download File
should work, or just use e.file.url directly?
I haven't deployed on Google App Engine myself, but this appears to be what django-filetransfers was designed for:
http://www.allbuttonspressed.com/projects/django-filetransfers#handling-downloads
edit: I believe I've answered this in the other question you posted, then: Trouble downlaoding file using Django FileTransfers
I think easiest way is to write a view since this file blob cannot be retrieved directly to write a function which is such:
def file_transfer(req, calendar_event_id):
try:
ce = CalendarEvent.objects.get(calendar_event_id)
except CalendarEvent.DoesNotExist:
raise Http404()
file = ce.file (Write Google appengine specfic routine to pull file)
return HttpResponse(file, media_type='file content type')
Hook it up on urls.py

Django comment email notification

I'm trying to setup notifications on the django comments framework. I've gone through the documentation here -
https://docs.djangoproject.com/en/dev/ref/contrib/comments/moderation/#django.contrib.comments.moderation.CommentModerator
I've added all of the code into my noticeboard app which is where the comments are currently being posted. When posting a comment to the site it works fine. However when i click the 'enable comments' field which is meant to allow the notifications, i'm not receiving any emails.
**UPDATE:
Just to add the site has a built in mailer so it records all emails being sent out from the website and it's not picked up any of the comments. If i also untick the 'enable comments' box I get an error message like so - comment_will_be_posted receiver 'pre_save_moderation' killed the comment
So i know the functionality is working ok.
Here is the code I've got so far:
//SNIPPET OF MODELS
from django.contrib.comments.moderation import CommentModerator, moderator
class Notice(models.Model):
class Meta:
ordering = ['-date']
content_type = 'noticeboard'
title = models.CharField(max_length=255)
sector = models.ForeignKey(BusinessSector, verbose_name="Sector", related_name='notices')
date = models.DateTimeField(auto_now_add=True, verbose_name="Date posted")
copy = models.TextField()
owner = models.ForeignKey('auth.User', related_name='notices')
owner_company = models.ForeignKey('directory.Company', verbose_name='Company')
enable_comment = models.BooleanField()
class EntryModerator(CommentModerator):
email_notification = True
enable_field = 'enable_comment'
moderator.register(Notice, EntryModerator)
I've also uploaded the file 'comment_notification_email.txt' into templates/contact.
The above code has been included into an exisiting app called noticeboard as this is where the comments are being posted.
Feel free to ask any questions if you think something would be of use to you.
Am I missed anything!?
Thanks!
I had to add an If statement in the code to say if mailer was being used then send the email. Otherwise it wouldn't send the email.
if "mailer" in settings.INSTALLED_APPS:
from mailer import send_mail
else:
from django.core.mail import send_mail

Categories