Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Today I opened my Django project and tried running the command "Python manage.py runserver" it showed import error: couldn't import Django
On my Django project today, I tried running the command "Python manage.py runserver" it showed ImportError: couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? So I had to install Django all over again. How do I stop this from happening everytime? I saw a post about adding C:\Python27\Scripts to user variables in the environment variable but didn't quite get the site-packages part. -
Headers content included in file uploaded in django rest framework
I'm having an issue in my django api file upload. When I upload file using FileUploadParser everything goes well but the file upload contains the header of the request stuff like Content-Disposition when i try to open the uploaded file it is broken. I searched for a while for some solution but no chance. Decided to use MultiPartparser but this way nothing is included in the request.data dict. How can I go around this ? Can somebody show me a code or a way to successfully upload file or image to my api without having them broken ? Thanks for any hint. -
How to handle file after saving and using pandas and saving that file in django?
I want to user to upload file, and then I want to save that file (that part is working), then I want to calculate data in this document and export it in results.html. Problem is this, I already used return function for user to download document (with done calculations). How to additionally save edited file, and forward to user to download and to see data? This is how i tried def my_view(request): print(f"Great! You're using Python 3.6+. If you fail here, use the right version.") message = 'Upload as many files as you want!' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.save() #This part is doing calculations for uploaded file dfs = pd.read_excel(newdoc, sheet_name=None) with pd.ExcelWriter('output_' + newdoc + 'xlsx') as writer: for name, df in dfs.items(): print(name) data = df.eval('d = column1 / column2') output = data.eval('e = column1 / d') output.to_excel(writer, sheet_name=name) return redirect('results') else: message = 'The form is not valid. Fix the following error:' else: form = DocumentForm() documents = Document.objects.all() context = {'documents': documents, 'form': form, 'message': message} return render(request, 'list.html', context) def results(request): documents = Document.objects.all() context = {'documents': documents} return render(request, 'results.html', context) -
how to customize form using django-bootstrap-v5
hello thank you for your visiting I'm a new learner of Django I would like to know how to format the form i try this and does not work i have this this is form.py pathesForm = inlineformset_factory( Book, VoyagePlace, fields=('name','time',), can_delete=False,extra=4,max_num=4, widgets={'name': forms.TextInput(attrs={ 'placeholder': 'name of book', }) } ) i use django-bootstrap-v5 and in file html this form is not working with me <form role="form" class="form-horizontal" method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row"> <div class="col-md-6"> {% bootstrap_field form.name %} </div> <div class="col-md-6"> {% bootstrap_field form.time %} </div> </div> {% if form.maybemissing %} {% bootstrap_field form.maybemissing %} {% endif %} {% endfor %} <button type="submit">Save</button> </form> but this is working with me (i can save the form) {% bootstrap_formset_errors formset %} <form role="form" class="form-horizontal" method="post"> {% csrf_token %} {% bootstrap_formset formset %} <button type="submit">Save</button> </form> this is my view.py def hello(request,id): book=Book.objects.get(id=id) if request.method == 'POST': form= pathesForm(request.POST,request.FILES,instance=book) if form.is_valid(): form.save() form = pathesForm(instance=book ) return render(request,'hello/pathesForm.html',{'formset':form}) i use print('hello) to try know where is the problem and the result seems like the form is not valid how i can to customize the style of my form like the first one -
Using telethon with a django application
I want to watch updates on telegram messages in an django application and interact with django orm. I found telethon library, it works with user api which is what I want. Below code simply works on its own. from telethon import TelegramClient from telethon import events api_id = 231232131 api_hash = '32131232312312312edwq' client = TelegramClient('anon', api_id, api_hash) @client.on(events.NewMessage) async def my_event_handler(event): if 'hello' in event.raw_text: await event.reply('hi!') client.start() But telethon requires phone message verification and it needs to work in a seperate thread. I couldn't find a way to put this code in a django application. And when django starts, I dont know how to bypass phone verification. It should always work in an seperate loop and interact with django orm. Which is very confusing for me. -
I I install pipenv environment with "pip3 install pipenv" command and ı did but ı can't find bin folder in my .vitualenvs folder
I I install pipenv environment with "pip3 install pipenv" command and ı did but ı can't find bin folder in my .vitualenvs folder.I can't run "python manage.py runserver" command is giving an ImportError "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?"What should ı do? -
Block django allauth default singup/login url
I am rendering my django-allauth singin/singup form through custom urls. from allauth.account.views import LoginView, SignupView urlpatterns = [ ... url(r'^customurl/login/', LoginView.as_view(), name="custom_login" ), url(r'^customurl/signup/', SignupView.as_view(), name="custom_singup" ), ... ] These are working fine. Problem is django-allauth default singin/singup urls working also. How can i block default singin/singup urls? -
Hi i have question about can we use request-html library on flask or Django and How
Hi i have question about can we use request-html library on flask or Django and How Hi i have question about can we use request-html library on flask or Django and How -
after add postgresql database get programming error in django
I'm creating a blog app with django and also it works fine with django default database called dbsqllite so. I decided to add postgresql database for my blog application after adding postgresql database it gives me a error like this django.db.utils.ProgrammingError: relation "blog_category" does not exist LINE 1: ...log_category"."name", "blog_category"."name" FROM "blog_cate.. by the way I have already tired so many things like python manage.py makemigrations python manage.py migrate python manage.py migrate --run-syncdb python manage.py migrate --fake python manage.py migrate {app name} zero none of them work for me.So if you any suggestion please let me know. here is my views.py of category view def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats.replace('-', ' ')) return render(request, 'categories.html', {'cats':cats.replace('-', ' ').title(), 'category_posts':category_posts}) models.py STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = SummernoteTextField(blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) image = models.ImageField(upload_to='images',null=True, blank=True) category = models.CharField(max_length=50, default='uncatagories') class Meta: ordering = ['-created_on'] # this is used to order blog posts using time def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('home') class Comment(models.Model): post = … -
How to make visits count seperate for each item
Hello I am making django app, i would like to add visit counter feature but seperate for each item. I think it would be a nice feature. def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comments'] = Comment.objects.filter(item=self.object) context['form'] = CommentCreationForm() num_visits = self.request.session.get('num_visits', 0) self.request.session['num_visits'] = num_visits + 1 context['visits'] = num_visits return context -
DRF + Serializer to return custom data from multiple models
Related to this question I am trying to return data from multiple models in one query by DRF. class Artist(models.Model): artist_name = models.CharField(max_length=100) class Genre(models.Model): genre_name = models.CharField(max_length=100) class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.ForeignKey(Artist, on_delete=models.CASCADE) genre = models.ForeignKey(Genre, on_delete=nodels.CASCADE) I want to return a JSON list of all options for albums and genres for all artists. Something like: { "genres": ["techno", "rap", "rock", ...], "albums": ["nevermind", "collection", "fragile", ...] } I created a custom serializer: class InfoSerializer(serializers.Serializer): albums = serializers.CharField() genres = serializers.CharField() class Meta: fields = ["albums", "genres"] and a Viewset: class ShelfStationOptionsViewSet(ViewSet): serializer_class = InfoSerializer def list(self, request): options = [{"albums": Album.objects.all()}, {"genres": Genre.objects.all()}] results = InfoSerializer(options, many = True) results.is_valid() return Response(results.data) Error message I keep getting: KeyError when attempting to get value for field albums on serializer InfoSerializer ... -
Celery cannot read value from env file after being run by supervisor
I am facing the issue, where If I run celery worker locally with celery -A project worker -l info. Celery tasks can access variables from .env file (I am using django-environ for reading .env file). But, in production server it's causing issues after being ran by supervisor. If a key doesn't exist in .env file it throws an error as it should be inside tasks. But, when I am properly setting all the variables it reads them without an error, but reads them as empty strings. I am also using firebase_admin for notifications. The same issue happens for it as well. import firebase_admin firebase_admin.initialize_app() This is how I am setting the default app in settings.py and the fcm service account file is also in my project directory. Locally, the notification task sends the notification properly. But, after being ran by supervisor, it throws File Not Found error. This is quite confusing for me. Below is my celery.conf file: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') # Using a string here means the worker doesn't have to serialize # the configuration … -
How to display a dropdown list in Django form?
I have an issue with the display of a dropdown list, which is a field part of a Django form. Related model field is defined like this: class Company(models.Model): """ Company informations - Detailed information for display purposes in the application but also used in documents built and sent by the application - Mail information to be able to send emails """ company_name = models.CharField("nom", max_length=200) comp_slug = models.SlugField("slug") rules = [("MAJ", "Majorité"), ("PROP", "Proportionnelle")] # Default management rule rule = models.CharField( "mode de scrutin", max_length=5, choices=rules, default="MAJ" ) The form has no dedicated ruels, evenf if tried to add some (kept as comment in the code below): class CompanyForm(forms.ModelForm): company_name = forms.CharField(label="Société", disabled=True) # rules = [("MAJ", "Majorité"), ("PROP", "Proportionnelle")] # rule = forms.ChoiceField(label="Mode de scrutin", choices=rules) class Meta: model = Company exclude = [] Here is the view: @user_passes_test(lambda u: u.is_superuser or u.usercomp.is_admin) def adm_options(request, comp_slug): ''' Manage Company options ''' company = Company.get_company(comp_slug) comp_form = CompanyForm(request.POST or None, instance=company) if request.method == "POST": if comp_form.is_valid(): comp_form.save() return render(request, "polls/adm_options.html", locals()) And the part of HTML code: <div class="row border mt-4"> <div class="col-sm-12"> <h5>Préférences de l'application</h5> <div class="row"> <div class="col-sm-5 mt-2"> {{comp_form.use_groups}} <label for="{{comp_form.use_groups.label}}">{{comp_form.use_groups.label}} </div> <div class="col-sm-7 mt-2"> … -
I tried to test but there is import test error, so what is the problem?
https://github.com/Angelheartha/tera ↓ i did python manage.pytest polls ↓ (venv) C:\Users\user\PycharmProjects\pythonProject22\mysite\mysite\mysite>python manage.py text polls Unknown command: 'text'. Did you mean test? Type 'manage.py help' for usage. (venv) C:\Users\user\PycharmProjects\pythonProject22\mysite\mysite\mysite>python manage.py test polls System check identified no issues (0 silenced). E ERROR: mysite.mysite.mysite.polls (unittest.loader._FailedTest) ImportError: Failed to import test module: mysite.mysite.mysite.polls Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name import(name) ModuleNotFoundError: No module named 'mysite.mysite' Ran 1 test in 0.001s FAILED (errors=1) (venv) C:\Users\user\PycharmProjects\pythonProject22\mysite\mysite\mysite>cd mysite/mysite but test is imported on polls/text.py so i dont get what is the problem ..... -
webRTC channels not
I am creating a webRTC connection to transmit data between 2 peers. Currently, I am stuck in the stage of getting the channel.readyState to get into "open" state. Can someone help me understand why the ondatachannel() in code block 2 and the onopen in codeblock 1 eventlisteners do not fire? I am using django backend with django channels for sdp exchange. instantiating RTCPeerConnection and sending localdescription to my back end. function hostroom(){ lc = new RTCPeerConnection() dc = lc.createDataChannel("channel") dc.onmessage = e =>("Just got a message " + e.data); dc.onopen = e => console.log("Connection opened!") lc.onicecandidate = function(e){ console.log("icecandidate created"); } lc.createOffer().then(o => lc.setLocalDescription(o)).then(a => console.log("set successfully!")).then( function (){ var ice = JSON.stringify(lc.localDescription); console.log(ice); var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var p={{p.id}} $.ajax({ type: 'POST', url: '{% url 'createroom' %}', data:{ "ice": ice, "csrfmiddlewaretoken": csrftoken, "p": p, }, success: function (data) { alert(data["response"]) } }); } ) Output on dev tool console: Code on the remote peer's side. Runs on page load and will send the local description via the back end and then via django channels to the host. const rc = new RTCPeerConnection(); rc.onicecandidate = function(e){ console.log("New Ice Candidate reprinting SDP " + JSON.stringify(rc.localDescription)); } rc.ondatachannel = e => { … -
why there is import test errors? if i already imported on polls/text.py?
para efibutov https://github.com/Angelheartha/tera ↓ i did python manage.pyy text polls ↓ (venv) C:\Users\user\PycharmProjects\pythonProject22\mysite\mysite\mysite>python manage.py text polls Unknown command: 'text'. Did you mean test? Type 'manage.py help' for usage. (venv) C:\Users\user\PycharmProjects\pythonProject22\mysite\mysite\mysite>python manage.py test polls System check identified no issues (0 silenced). E ERROR: mysite.mysite.mysite.polls (unittest.loader._FailedTest) ImportError: Failed to import test module: mysite.mysite.mysite.polls Traceback (most recent call last): File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "C:\Users\user\AppData\Local\Programs\Python\Python39\lib\unittest\loader.py", line 377, in _get_module_from_name import(name) ModuleNotFoundError: No module named 'mysite.mysite' Ran 1 test in 0.001s FAILED (errors=1) (venv) C:\Users\user\PycharmProjects\pythonProject22\mysite\mysite\mysite>cd mysite/mysite but test is imported on polls/text.py so i dont get what is the problem ..... -
How make Django save an image to static folther
I have a view that receives an image than it saves this image in a temp folther. After that I make some processing in the image and save it in other folther. But i can´t use it because it is not in the static folther of the app it is considered not secure and give an error message. img = request.FILES["image"] img_extension = os.path.splitext(img.name)[1] # This will generate random folder for saving your image using UUID save_path = 'D:/Photo/GFPGAN/inputs/whole_imgs' if not os.path.exists(save_path): # This will ensure that the path is created properly and will raise exception if the directory already exists os.makedirs(os.path.dirname(save_path), exist_ok=True) # Create image save path with title uui = str(uuid.uuid4()) img_save_path = "%s/%s%s%s" % (save_path, "image", uui, img_extension) with open(img_save_path, "wb+") as f: for chunk in img.chunks(): f.write(chunk) subprocess.call('python D:/Photo/GFPGAN/inference_gfpgan.py --upscale 2 --test_path D:/Photo/GFPGAN/inputs/whole_imgs --save_root D:/Photo/GFPGAN/results', shell=True) shutil.move('D:/Photo/GFPGAN/results/restored_imgs/image'+uui+'.jpg', 'C:/Users/rapha/OneDrive/Área de Trabalho/Harvard/CSW/commerceTest/cs50-commerceM/auctions/static/auctions/images/images'+uui+'.jpg') listing = form.save(commit=False) print(img_save_path) listing.restoredimage = 'C:/Users/rapha/OneDrive/Área de Trabalho/Harvard/CSW/commerceTest/cs50-commerceM/auctions/static/auctions/images/images'+uui+'.jpg' #listing.restoredimage = cv2.imread("D:/Photo/GFPGAN/results/restored_imgs/image.jpg") listing.restoredimage = 'C:/Users/rapha/OneDrive/Área de Trabalho/Harvard/CSW/commerceTest/cs50-commerceM/auctions/static/auctions/images/images'+uui+'.jpg' listing.owner = user listing.save() return HttpResponseRedirect(reverse("index")) How can I save the processed image in the correct path. The erro is : Exception Type: SuspiciousFileOperation -
why isn't the Django dev server reloading?
I've used django dev servers for years. I start them with python manage.py runserver and when I change any of the python code, they restart nicely. Now I've inherited someone else's project for maintenance, and for whatever reason, I change the Python code and the server does not restart. I can't seem to find any kind of configuration option that would cause this. I don't have the --noreload flag set, here's my proof: $ ps -ef | grep runserver chris 290898 250765 1 11:55 pts/6 00:00:00 python manage.py runserver chris 290914 290898 5 11:55 pts/6 00:00:01 /home/chris/.virtualenvs/my-webapp-4cLYw-9X/bin/python manage.py runserver Has anyone run into this before? Python 3.9.5 Django 3.2.6 using pipenv to manage my virtual environment -
How do I properly save a file from chromedriver in a docker container with django?
I'm doing Django + Chrome standalone selenium, I can't configure the download folder correctly. I've been trying to do it for half a day, I've never been able to solve the problem like that. Tell me how to do it right? I need chrome to save files to a folder from the django project, namely in app/media/uploads I tried to do this: chrome: image: selenium/standalone-chrome:latest container_name: Chrome-selenium ports: - "4444:4444" volumes: - ./app:/app - media:/app/media privileged: true shm_size: 2g restart: always And at the very start with the command: options = webdriver.ChromeOptions() options.headless = True # User Agent options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84') # Disable driver mode options.add_argument('--disable-blink-features=AutomationControlled') # Download settings download_dir = os.path.join(settings.MEDIA_ROOT, 'uploads') ?? options.add_experimental_option('prefs', { 'download.default_directory': download_dir, 'download.prompt_for_download': False, 'download.directory_upgrade': True, 'safebrowsing_for_trusted_sources_enabled': False, 'safebrowsing.enabled': False }) driver = webdriver.Remote("http://chrome:4444/wd/hub", options=options) But after launching from django, no file is saved, more precisely, I do not know where it is saved, but definitely not where I indicated -
Nuxt Auth token request cancelled because of XHR
Created a new nuxt project and installed/configured nuxt-auth plugin. For some reason the POST request to the server - which should fetch the token - does always be cancelled on the client side because of XHR. Already tested with Postman and nicks-cors-test ( https://github.com/njgibbon/nicks-cors-test ) in order to check if it's a misconfiguration on the server side but everything works just fine, it seems to be an issue with nuxt-auth. -
Override query on Django DateField to change date searched for
I have a model in Django that represents a week. I'd like to have someone enter any date and have the model automatically save the start of the week. That's easy, just override save. class Week(models.Model): start_date = models.DateField() def save(self): self.start_date = self.start_date - datetime.timedelta(days=date.weekday()) But I'd also like someone to be able to query any day and get the week. So for example, I'd want someone to do this: this_week = Week.objects.filter(start_date=date.today()) where today is a Wednesday, and get the week object where the date is set for the start of the week. It needs to work for any date, not just today. I know we can override get_queryset in a manager, but is there a way to edit what was actually searched for? Every manager example I can find just changed the queryset in a static way. Or would my best bet be trying to subclass the DateField? (Note code above is typed in, simplified, and may contain mistakes, but it works in my actual code) -
Django offline Document language
I‘ve downloaded Django document "html" version of zh-hans, the file name is django-docs-3.2-zh-hans, but when I search word like "model", it turns out to be english, not Chinese. and I found that a lot of html file is english context, but when I go to online website, I could see it had been translated properly, So how to solve it? -
Using Inline in ModelForm in Django Admin
I would like to validate a Many-to-many field in Django admin by overriding the clean method. This thread gives a way to do that by creating a ModelForm and then doing the clean there. However, my problem is the many-to-many field is an inline i.e. instead of the widget where you have to select multiple elements, I have a tabular inline. I would like to find out if anyone knows how to add the inlines in the ModelForm so that I can do the clean and validation. I've seen people talk about inlineformset_factory but it's always been as it relates to views.py and not the admin (and I can't figure out how I'd even go about overriding the clean method of that). I've added some of my code below: class ProductVariantForm(ModelForm): class Meta: model = ProductVariant fields = [ 'name', 'price', ] # I then want to be able to add something like # inlines = [OptionValueInline,] # for the inline many-to-many field. def clean(self): # Check if list of option_values is ok. class ProductVariantAdmin(admin.ModelAdmin): form = ProductVariantForm -
the ajax code didn't work on a django app
I am working on a machine learning app with Django and I have to pass the data that I wont to use in the model to a views function using ajax and Jquery but the function didn't get called at all so whenever I submit the form is show nothing I've try many solution but didn't work ps: I am still a beginner in JS here is the views function: def Iris_classify(request): print('called1') if request.POST.get('action') =='post': print('caled2') sepal_length = float(request.POST.get('sepal_lenght')) sepal_width = float(request.POST.get('sepal_width')) petal_length = float(request.POST.get('petal_lenght')) petal_width = float(request.POST.get('petal_width')) model = pd.read_pickle(r"C:\Users\zakaria\Django\DataProject\Data_science\machinlearning\classifier_model.pickl") prediction_features=[sepal_length,sepal_width,petal_length,petal_width] result = model.predict([prediction_features]) classification = result[0] print(classification) return JsonResponse({'result': classification, 'sepal_length': sepal_length, 'sepal_width': sepal_width, 'petal_length': petal_length, 'petal_width': petal_width}, safe=False) and here is the template: {%extends 'machinlearning/base.html'%} {%block title%}Iris classification{%endblock %} {%block content %} <div class='container pt-5'> <form action ="" method="POST"id ="input_form"> {% csrf_token %} <div class="form-group" > <label for="sepal_length" style="color:white">Sepal Length</label> <input type="number" step="0.1" class="form-control" id="sepal_length" placeholder="Sepal Length"> </div> <div class="form-group" > <label for="sepal_width">Sepal Width</label> <input type="number" step="0.1" class="form-control" id="sepal_width" placeholder="sepal width"> </div> <div class="form-group" > <label for="petal_length">Petal Length</label> <input type="number" step="0.1" class="form-control" id="petal_length" placeholder="petal_length"> </div> <div class="form-group" > <label for="petal_width">Petal Width</label> <input type="number" step="0.1" class="form-control" id="petal_width" placeholder="petal width"> </div> <button type="submit" value = "Submit" class="btn btn-primary" … -
Django-ckeditor image resize or image max-width
I added ckeditor for my django project but there is a problem. Ckeditor image uploading is working but when I add an image that is too width, the image overlowing of the container. I'm adding a picture to give you an idea: I tried add sample code to ckeditor_uploader > views.py > ImageUploadView(): class ImageUploadView(generic.View): http_method_names = ['post'] def post(self, request, **kwargs): """ Uploads a file and send back its URL to CKEditor. """ uploaded_file = request.FILES['upload'] backend = registry.get_backend() ck_func_num = request.GET.get('CKEditorFuncNum') if ck_func_num: ck_func_num = escape(ck_func_num) filewrapper = backend(storage, uploaded_file) allow_nonimages = getattr(settings, 'CKEDITOR_ALLOW_NONIMAGE_FILES', True) # Throws an error when an non-image file are uploaded. if not filewrapper.is_image and not allow_nonimages: return HttpResponse(""" <script type='text/javascript'> window.parent.CKEDITOR.tools.callFunction({0}, '', 'Invalid file type.'); </script>""".format(ck_func_num)) filepath = get_upload_filename(uploaded_file.name, request) print(filepath, "filepath") print(uploaded_file,"path") ## IT'S MY SAMPLE CODE image = Image.open(filewrapper.file_object) if image.width > 800: factor = 800/image.width new_width = int(image.width*factor) new_height = int(image.height*factor) width = new_width height = new_height # output_size = (300,300) # image.thumbnail(output_size) # image.save(filepath.path) print(width) print(height) else: width = image.width height = image.height saved_path = filewrapper.save_as(filepath) print(saved_path, "saved_path") url = utils.get_media_url(saved_path) print(url, "url") if ck_func_num: # Respond with Javascript sending ckeditor upload url. return HttpResponse(""" <script type='text/javascript'> window.parent.CKEDITOR.tools.callFunction({0}, '{1}'); …