Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to check duplicate names in djnago
This is the model I want fetch such records who's first_name and last_name will be same class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) I tried this check only first_name or last_name are same but i have to check both first_name and last_name are same. this checks if last names are the same. duplicates = Customer.objects.values('last_name') .annotate(name_count=Count('last_name')) .filter(name_count__gt=1) queryset = Customer.objects.filter(last_name__in=[item['last_name'] for item in duplicates]) .values() this checks if first_names are the same. duplicates = Customer.objects.values('first_name') .annotate(name_count=Count('first_name')) .filter(name_count__gt=1) queryset = Customer.objects.filter(first_name__in=[item['first_name'] for item in duplicates]) .values() Any Help Will Be Appreciated! Thanks! -
How to implement Audit Trail in django
I'm looking for ideas on how to implement audit trails in Django for payment Gateway Integration.Please help me. -
Django: Getting "Page not found" Error While Using Slug in URL
I am a beginner learning Django through a building an app, called PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models and their reviews. Right now, I am facing an error just after I have added codes to use slug in the URLs. When I go to http://127.0.0.1:8000/index, I see this page: When I click on "Samsung," I get this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index/samsung/ Raised by: PhoneReview.views.ModelView No phone model found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I have successfully performed migration. But still, I am facing the issue. Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True, max_length=150) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform … -
Creating an union-like related models
I have a Django app with a model called OS (as in "Operating System"). The model has some usual fields, like name or version. Those fields are common to all operating systems. I also have two other (related) models, called Linux and Windows. Those have some OS-specific fields (Linux has a desktop_environment, as in "KDE" or "Gnome", apps_manager, as in "apt", pacman", etc...; Windows has a built_in_antivirus field, etc...). This means that those two models have completely different fields, that make sense only for specific operating systems. The OS model has a OneToOne relation with both the Linux and the Windows models, but only one of those 2 actually exists (an OS can't be Linux and Windows at the same time). How can I create some sort of "relation", "attribute", "manager" or XYZ property so I can access the fields of Linux and Windows from an instance of an OS model? Example: a = OS.objects.get(pk=3) # This is a Windows instance a.<magic>.built_in_antivirus True b = OS.objects.get(pk=14) # This is a Linux instance b.<magic>.desktop_environment Please note that I don't want to move all fields to the same model. -
Error: <text> attribute x: Expected length, "NaN"
I am getting an error Error: <text> attribute x: Expected length, "NaN" I'm using chart.js and google timeline for representation purpose. But actually I am selecting some data between a date range start_date and end_date then it's passing to the function. but there it's showing the error. function addMarker(markerDate, container, dateRangeStart, dateRangeEnd, options, formatDate) { var baseline; var baselineBounds; var chartElements; var markerLabel; var markerLine; var markerSpan; var svg; var timeline; var timelineUnit; var timelineWidth; var timespan; baseline = null; timeline = null; svg = null; markerLabel = null; chartElements = container.getElementsByTagName('svg'); if (chartElements.length > 0) { svg = chartElements[0]; } chartElements = container.getElementsByTagName('rect'); if (chartElements.length > 0) { timeline = chartElements[0]; } chartElements = container.getElementsByTagName('path'); if (chartElements.length > 0) { baseline = chartElements[0]; } chartElements = container.getElementsByTagName('text'); if (chartElements.length > 0) { markerLabel = chartElements[0].cloneNode(true); } if ((svg === null) || (timeline === null) || (baseline === null) || (markerLabel === null) || (markerDate.getTime() < dateRangeStart.min.getTime()) || (markerDate.getTime() > dateRangeEnd.max.getTime())) { return; } in console, it shows the error is in this part. if (chartElements.length > 0) { markerLabel = chartElements[0].cloneNode(true); } -
How to specify date field format while creating django objects
I have a model Team class Team(models.Model): team = models.IntegerField(primary_key=True) name = models.CharField(max_length=170) code = models.CharField(max_length=20) logo = models.URLField(null=True) country_id = models.ForeignKey('Country',null=True, on_delete=models.SET_NULL) founded = models.DateField(null=True) venue_name = models.CharField(max_length=170) venue_surface = models.CharField(max_length=170) venue_address = models.CharField(max_length=200) venue_city = models.CharField(max_length=150) venue_capacity = models.IntegerField(null=True) lastModified = models.DateTimeField(auto_now=True) I want to create object from this model where input data for founded field is only year data for example 1970 How i can do it. Thanks in advance -
i need to modify rowCallback jquery
Working on django. Need to modify rowCallback jquery. Page is loading with multipleSelect dataTable and have server based pagination. Now i want to change the color of one column on the base of data. And I couldn't understand what is happening inside this rowCallback function as the documentation is not helping for me. $('#example').dataTable( { "rowCallback": function( row, data ) { if ( data.grade == "A" ) { $('td:eq(4)', row).html( '<b>A</b>' ); } } } ); Can anyone explains last 2 lines, I am kind of new to this. -
How to get row wise sum of all previous value in column using django queryset
I want to get the row wise sum of all previous value in column amount. models.py class PaymentRecord(models.Model): invoice_no = models.ForeignKey(Invoice, unique=False, related_name='paymentrecord', on_delete=models.CASCADE) amount = models.CharField(max_length=10) paid_into = models.CharField(max_length=40, choices=PAID) payment_date = models.DateField(auto_now=False, auto_now_add=False) cheque_date = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) cheque_no = models.CharField(max_length=20, null=True, blank=True) notes = models.CharField(max_length=100, null=True, blank=True) I tried the queryset pay_receipt = PaymentRecord.objects.filter(Q(payment_date__range=[startdate, enddate]),Q(paid_into='ONLINE') | Q(paid_into='CHEQUE')).annotate(totals=Sum('amount')).order_by('payment_date') I want the result like this Id paid_into payment_date amount SumAmount --------------------------------------------------------- 1 Bank 12-09-2019 40.00 40.00 2 Cash 12-09-2019 40.00 80.00 3 Bank 12-09-2019 45.00 125.00 4 Bank 12-09-2019 50.00 175.00 -
Date pipe shows correct Date but wrong time in Linux
I am using date pipe date:'short'.For storing the time ,I am using timezone.now().For displaying the time to the user in the UI,I am using like <span>{{dat.last_heard_time|date:'short'}}</span> in the template file. I am using two OS in the same machine.I am doing all this things that is storing in DB,template file everything in Windows. The windows machine shows the correct time but while running the same page in Linux's mozilla/chrome,it result wrong time but shows correct date. DB( in windows):2019-11-14 16:56:06.503 Windows's Chrome:11/14/19, 5:00 PM(shows the time in Window system i.e 5 PM)(CORRECT) Linux's Chrome:11/14/19, 6:30 AM(Actual time in Linux system 17.00)(WRONGLY DISPLAY) Help me with this. Thanks in advance :) -
ERROR OCI runtime create failed: starting container process caused "exec: \"-\": executable file not found in $PATH" when i write docker-compose up
I have dockerfile and docker-compose .When i write docker-compose up it gives me error .my app dir is /www/django-folder/crinfo/. FROM ubuntu:18.04 RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python-dev default-libmysqlclient-dev RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip COPY . /var/www/api/ WORKDIR /var/www/api/ RUN pip install -r requirements.txt RUN pip install ptvsd ADD ./site-conf.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 3500 CMD ["apache2ctl","-D","FOREGROUND"] and my docker-compose is version: "2" services: django-apache2: build: . container_name: django-apache2 ports: - "8005:80" - "3500:3500" - "8006:81" volumes: - $PWD/www:/var/www/html command: > - /bin/sh/ -c "python ./www/django-folder/crinfo/manage.py makemigrations && ./www/django-folder/crinfo/manage.py migrate " I want when i write docker compose up , it migrate and makemigrations -
Dynamically set filterset_class in Django ListView
I have a ListView where I would like to set a different filterset for each user: if the user is in group admin it would have a specific Filterset; if it is a standard user another Filterset will be applied. How can I do this? In the documentation they say that I can override the method get_filterset_class() when I am using DjangoRestFramework but I am not using it. class StandardFilterset(FilterSet): field_1 = django_filters.ModelChoiceFilter(queryset=Model.objects.all()) def __init__(self, *args, **kwargs): super(StandardFilterset, self).__init__(*args, **kwargs) self.filters['field_1'].extra.update({ 'widget': forms.Select(attrs={'class': 'form-control', 'type': 'text'}) }) class Meta: model = Model fields = { 'field_1': ['exact'], } class AdminFilterSet(FilterSet): field_1 = django_filters.ModelChoiceFilter(queryset=Model.objects.all()) active = django_filters.BooleanFilter(label='Is active', field_name='active') def __init__(self, *args, **kwargs): super(AdminFilterSet, self).__init__(*args, **kwargs) self.filters['field_1'].extra.update({ 'widget': forms.Select(attrs={'class': 'form-control', 'type': 'text'}) }) self.filters['active'].extra.update({ 'widget': django_filters.widgets.BooleanWidget(attrs={'class': 'form-control', 'type': 'text'}) }) class Meta: model = Model fields = { 'field_1': ['exact'], 'active': ['exact'], } class AListView(GroupRequiredMixin, LoginRequiredMixin, ListView): group_required = [ "Standard", "Administrator",] filterset_class = StandardFilterset template_name = 'temp/a_listview.html' context_object_name = 'a' In "AListView" filterset_class is set to StandardFilterset and the other filterset "AdminFilterSet" is different (here it has a field more). How can I change filterset in AListView based on the user stored in the request? There is a method similar … -
Optimise nested manager
I was wondering how I can optimize the python code below? If you are curious, the code is for a custom permissions class in DRF/Django. The permissions check is there to see if the currently logged in user is the manager of user who created the object, or managers manager and so on. class IsManager(permissions.BasePermission): """ """ def has_object_permission(self, request, view, obj): user = request.user if hasattr(user, 'manager'): if user == obj.user.manager: has_permission = True else: has_permission = False elif hasattr(user.manager, 'manager'): if user == obj.user.manager.manager: has_permission = True else: has_permission = False elif hasattr(user.manager.manager, 'manager'): if user == obj.user.manager.manager.manager: has_permission = True else: has_permission = False elif hasattr(user.manager.manager.manager, 'manager'): if user == obj.user.manager.manager.manager.manager: has_permission = True else: has_permission = False elif hasattr(user.manager.manager.manager.manager, 'manager'): if user == obj.user.manager.manager.manager.manager.manager: has_permission = True else: has_permission = False elif hasattr(user.manager.manager.manager.manager.manager, 'manager'): if user == obj.user.manager.manager.manager.manager.manager.manager: has_permission = True else: has_permission = False else: has_permission = False return has_permission cheers James -
How can i display detailed data from many to many field instead of objects in django rest API , currently im getting only objects of it
I'm new to Django,i tryed to list all invoices from my model Invoices and im getting items as only its object, to make the code efficient i need to get the whole data of items in a single query how can i get the details of items along with the data instead of item objects Here is what i have tryed models.py class ItemsInvoice(models.Model): invoiceId = models.CharField(max_length=20) product_Id = models.CharField(max_length=20) item_price = models.CharField(max_length=20) class Invoices(models.Model): customer = models.CharField(max_length=10,null=True) total_amount = models.CharField(max_length=12,null=True) items = models.ManyToManyField(ItemsInvoice,related_name="item_invoice") views.py class InvoiceView(ListAPIView): serializer_class = InvoiceSerializers def get_queryset(self): # queryset = Invoices.objects.prefetch_related('items').all().order_by('-id') queryset = Invoices.objects.all().order_by('-id') return queryset serializers.py class InvoiceSerializers(serializers.ModelSerializer): class Meta: model = Invoices fields = '__all__' if i run it on my postman, its response will be like this API response what i have [ { "id": 69, "customer": "4", "total_amount": "25000", "items": [ 66, 67, 68 ] } ] but actually i want my output like this , ie the item field should list all data inside in it API response what i want [ { "id": 69, "customer": "4", "total_amount": "25000", "items": [ { "id": 66, "invoiceId": "69", "product_Id": "3", "item_price": "300", }, { "id": 67, "invoiceId": "69", "product_Id": "4", "item_price": "200", … -
Django login authentication with credentials from custome table(mysql) not working
I am trying to login with credentials which is in my mysql database , but its not working.it works fine for admin credentials. views.py def logauth(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate( username=username, password=password) if user is not None: messages.error(request, 'if part : user is not None') login(request, user) messages.error(request, '111') return redirect('emp') else: messages.error(request, 'else part : user is None') return redirect('login_url') else: messages.error(request, 'Please provide valid credentials') return render(request, 'registration/login.html') models.py class RegAuth(AbstractBaseUser): username = models.CharField(max_length=255) email = models.EmailField(unique="TRUE") password = models.CharField(max_length=255) mobile = models.CharField(max_length=12) registrationDate = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) objects = UserManager() is_anonymous = "FALSE" is_authenticated = "TRUE" is_active = False is_superuser = True USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "mobile"] class Meta: db_table = "bloggerauth" def __str__(self): return self.email setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'jayesh', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } AUTHENTICATION_BACKENDS = ('polls.backends.MyBackEnd', 'django.contrib.auth.backends.ModelBackend', ) -
Error during WebSocket handshake: Unexpected response code: 404 in django chat application
<script> var roomName = {{ room_name_json }}; console.log(window.location.host) var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/'); chatSocket.onopen = function(e) { alert("[open] Connection established"); alert("Sending to server"); }; chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; document.querySelector('#chat-log').value += (message + '\n'); }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; chatSocket.send(JSON.stringify({ 'message': message })); messageInputDom.value = ''; }; chatSocket.onerror = function(error) { alert(`[error] ${error.message}`); }; </script> I want to make a chat app so I am making use of Django channels and Redis server. Error I got with it is given below (index):134 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/s/' failed: Error during WebSocket handshake: Unexpected response code: 404 (index):150 Chat socket closed unexpectedly (index):167 WebSocket is already in CLOSING or CLOSED state. Can anyone help me?? -
How to delete post and delete tag which will be unused on Django2.2 using django-taggit
I'm making a blogapp which uses django and django-taggit. I made a deleteview using django.views.generic.edit.DeleteView . But when I saw the admin page, post was deleted but tag was not deleted. How can I delete post and delete tag which will be unused at the same time? This is the code that I tried. If you remove the "delete" function , it will only delete the post. views.py class DeleteView(LoginRequiredMixin, generic.edit.DeleteView): model = Post success_url = reverse_lazy('portal:index') def delete(self, request, *args, **kwargs): deltag = self.object.tags.clear() result = super().delete(request, *args, **kwargs) return deltag,result -
Add plugins (power paste) in TinyMce django
Hi I am trying to add paste plugin in TinyMce in my django app. Here is the setting.py configuration. TINYMCE_DEFAULT_CONFIG = { "toolbar": 'mobileequationeditor', 'height': 360, 'width': 1120, 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'selector': 'textarea', 'theme': 'modern', 'plugins':"powerpaste", 'toolbar1': ''' fullscreen preview bold italic underline | fontselect, fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | MathJax | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, 'statusbar': True, } When I open the model in admin there is an error saying Failed to load plugin: powerpaste from url https://website.com/static/tinymce/js/tinymce/plugins/powerpaste/plugin.min.js I have tried collectstatic but no new static was collected. Where can I get plugin.min.js and where should I put it. My static file configuration in setting.py is STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' I am running these in production. What's the solution? The thing is I want to copy images from word file directly into the RichTextField. -
Django: Getting OperationalError While Using Slug in URL
I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models, views and the template files. Now, I am facing a problem. While attempting to use slug in URL, I am facing OperationalError. While I run the server, the PyCharm terminal says the following: OperationalError at /index no such table: PhoneReview_brand" Here are my codes of models.py located inside PhoneReview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Brand(models.Model): brand_name = models.CharField(max_length=100) origin = models.CharField(max_length=100) manufacturing_since = models.CharField(max_length=100, null=True, blank=True) slug = models.SlugField(unique=True, max_length=150) def __str__(self): return self.brand_name def save(self, *args, **kwargs): self.slug = slugify(self.brand_name) super().save(*args, **kwargs) class PhoneModel(models.Model): brand = models.ForeignKey(Brand, on_delete=models.CASCADE) model_name = models.CharField(max_length=100) launch_date = models.CharField(max_length=100) platform = models.CharField(max_length=100) slug = models.SlugField(unique=True, max_length=150) def __str__(self): return self.model_name def save(self, *args, **kwargs): self.slug = slugify(self.model_name) super().save(*args, **kwargs) class Review(models.Model): phone_model = models.ManyToManyField(PhoneModel, related_name='reviews') review_article = models.TextField() date_published = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, null=True, blank=True) link = models.TextField(max_length=150, null=True, blank=True) def __str__(self): return self.review_article Here are my codes of urls.py located inside … -
implementing login for custom user model in django-rest-framework
i have implemented a custom user model to register a new user and trying to make the login funtionality through obtain_auth_token functionality in Django via DRF but it is showing me response as { "non_field_errors": [ "Unable to log in with provided credentials." ] } pls guide -
How to save the parse json array values to the database in django python rest api,by using models.py , serializers.py and views.py
I want save the category and their subcategories to the database and here each category have a multiple subcategories.Could you please help me to save the user,category and multiple subcategories corresponding to category.Models.py , Serializers.py, Views.py and incomming request is attached. Models.py class SavingCategoryandPreferences(models.Model): user = models.ForeignKey(User, related_name='user') news_category = models.ForeignKey(NewsCategory) subcategories= models.ForeignKey(NewsSubCategory, related_name='sub') sort_order = models.IntegerField(default=0) slug = AutoSlugField(populate_from='subcategories_id', separator='', editable=True) created_time = models.DateTimeField("Created Date", auto_now_add=True) Serializers.py class MobilecatsubSerializer(serializers.ModelSerializer): class Meta: model = SavingCategoryandPreferences fields = ('id', 'user', 'subcategories', 'news_category',) Views.py class MobileCatsubViewswt(viewsets.ModelViewSet): serializer_class = serializers.MobilecatsubSerializer queryset = SavingCategoryandPreferences.objects.all() Incomming Request { "user":"39", "news_category":"22", "subcategories": [ {"sub_id":"1"}, {"sub_id":"2"} ] } -
calculated property in Django model with QuerySet
I am working on a frontend that consumes a Django backend. I want to add a new calculated property to one Django model, that contains chart-data for amCharts. After some research i found out, that using @property would be the way to go here. However all the viewsets implemented atm use querysets, which as i found out after some googling ignore calculated properties. Is there a way to keep the queryset and let it use my calculated property? If not: Would manually writing out all the queryset operations solve the problem? Code: # models.py class MyModel: # Normal props @property def calced(self): return somecalc # views.py class MyModelView(ModelViewSet): serializer_class = MyModelSerializer def get_queryset(self): return MyModel.objects.filter(id=self.kwargs['id_pk']) -
Using Ajax to send data to a Django model
I created the following Ajax request to send data to my views.py. Once the request is sent, the view should save thata in my database. The problem with my actual code is that the value that i submit in the form, is not being saved. Here is what i tried: Html/JS <script> $(document).ready(function () { $("#test").submit(function (event) { $.ajax({ type: "POST", url: "/ajtest/", data: { csrfmiddlewaretoken: "{{ csrf_token }}", state:"inactive", data: $('#test').serialize(), }, success: function () { $('#message').html("<h2>Submitted.</h2>") } }); return false; }); }); </script> <form method='post' id='test'> {% csrf_token %} <input type="text"> <input type='submit' value='Test button'/> <div id='message'>Initial text</div> </form> And here is the view: def ajtest(request): if request.method == 'POST': model = MyModel() model.value = request.POST['data'] model.user = request.user model.save() messages.success(request, f"Success!!") else: messages.success(request, f"Error") return HttpResponse('ok') Here, user is being saved. I see a new record appearing in the DB when i hit the Ajax form, the problem is that, in the column value i'm not seeing the data submitted in the form, but instead i'll see either a blank field or, now, the CSRF token of the request. Can someone help me find the problem? I'm sure it is in the Ajax request. -
How to migrate models to a differents installed apps in django
so i need to migrate some data or i can say alter new column to some database table INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] whenever i try to migrate, it will migrate to a new table called polls_modelsname(like in installedapps) thing i want to alter the columns into auth_users tables how can i achieve this? -
What is the django drop down type?
I Want to know: What is the django drop down type? if we add dropdown and add class so should we need to pass this widgets = { 'Currency':forms.TextInput(attrs={'class':'form-control'}) } or something? Because when i pass this my dropdown convert into input i don't need like that i just need to know what is the drop down type for example TextInput or something Any Help Will Be Appreciated! Thanks! -
Resize and Create Thumbnail on Image Upload Django 2 using Pillow
I am trying to resize an image on upload and also create a thumbnail out of the same resized image. I previously was able to resize the image without issues, however, when I tried adding in the thumbnail feature I was unable to get it working. I have looked at all the other related questions and all of them are either outdated or haven't worked in my case. models.py class Project(models.Model): cover_image=models.ImageField(max_length=150, upload_to='project-covers/', default='Default.png', null=True) thumbnail=models.ImageField(max_length=150, upload_to='project-thumbnails/', null=True) def save(self, *args, **kwargs): super(Project, self).save(*args, **kwargs) if self.cover_image: fname = self.title + '_cover.' tname = self.title + '_thumbnail.' self.resizeUploadedImage(fname) self.createThumbnail(tname) # pdb.set_trace() # im = Image.open(self.cover_image) # im_thumb = im.copy() # im.thumbnail(IMAGE_SIZE) # im_thumb.thumbnail(THUMB_SIZE) # sized_io = BytesIO() # thumb_io = BytesIO() # im.save(sized_io, format=im.format) # im_thumb.save(thumb_io, format=im.format) # fname.join(im.format) # tname.join(im.format) # # self.cover_image.delete(save=False) # self.cover_image.save( # fname, # ContentFile(sized_io.getvalue()), # False # ) # self.thumbnail.save( # tname, # ContentFile(thumb_io.getvalue()), # False # ) def resizeUploadedImage(self, fname): '''Resize the image being uploaded.''' try: im = Image.open(self.cover_image) if im.size > IMAGE_SIZE: im_sized = im.resize(IMAGE_SIZE, Image.ANTIALIAS) image_io = BytesIO() im_sized.save(image_io, im.format) # pdb.set_trace() fname = fname + im.format self.cover_image.save(fname, ContentFile(image_io.getvalue(), False)) im.close() except IOError as e: print("Could not resize image for", self.image) …