Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django bulk_create ignoring foreign key integrity errors
I am using django with an sqlite database and I need to load entries from a json file. Since there are a lot of entries (190 mil) I have to use the bulk_create. Unfortunately we have only an incomplete database, so sometimes values should be inserted into a Many To Many relation for which there is no matching foreign key. In this case I get the following error: django.db.utils.IntegrityError: The row in table 'projects_paper_citing_literature' with primary key '1' has an invalid foreign key: projects_paper_citing_literature.to_paper_id contains a value '90241d37be4b06dd9b2f4ee4cf8de9089d7ea9ce' that does not have a corresponding value in projects_paper.paper_id. I found out that some other errors can be solved with ignore_conflicts=True. However, this does not apply to these errors: see my code below. Unfortunately, due to the high number of entries, it is also impossible/way to slow to check with filter() before each insertion if the two entries really exist. My code to read the database in is: def load_citations(paper_json_entries: List[Dict[str, any]]): paper_cites_paper_relationship = Paper.citing_literature.through citations: List[paper_cites_paper_relationship] = [] for paper_json in paper_json_entries: base_paper_id: int = paper_json['id'] for citation_id in paper_json['outCitations']: new_citation: paper_cites_paper_relationship = paper_cites_paper_relationship( from_paper_id=base_paper_id, to_paper_id=citation_id) citations.append(new_citation) paper_cites_paper_relationship.objects.bulk_create(citations, ignore_conflicts=True) -
Do I use the same database for Django-RQ as for my Django-project?
I'm trying to implement django-rq in my Django-project. In my settings.py I need to include some back-end informations (taken from the guide) RQ_QUEUES = { 'default': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, 'PASSWORD': 'some-password', 'DEFAULT_TIMEOUT': 360, }, 'with-sentinel': { 'SENTINELS': [('localhost', 26736), ('localhost', 26737)], 'MASTER_NAME': 'redismaster', 'DB': 0, 'PASSWORD': 'secret', 'SOCKET_TIMEOUT': None, 'CONNECTION_KWARGS': { 'socket_connect_timeout': 0.3 }, }, 'high': { 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku 'DEFAULT_TIMEOUT': 500, }, 'low': { 'HOST': 'localhost', 'PORT': 6379, 'DB': 0, } } I'm completly new to Redis and job-queing, so I wonder, if I just should use the same credentials as for DATABASES i.e using the same database as for my models, or is it best-practice to have a different database for the queing? If that has any impact, my database for Django is a PostgreSQL at Google SQL-server. -
This site can’t be reached - django setup
I'm starting working with django and try to setup new project and after the command "py manage.py runserver" Everything working and I get this address http://127.0.0.1:8000/ and when I try to enter this address I get that message " This site can’t be reached127.0.0.1 refused to connect". What I need to fix ? Thanks -
Which model shall be used by using() in django when there are two models with same name and different apps in the same db?
I have defined a model MyUser in two apps(let's say A and B) in different projects in django with the same DB(CAP_db). The second project uses more than one DB. So, when querying the model MyUser in one of its apps, I am using the statement : ambassador = MyUser.objects.using('CAP_db').get(code=code). By default, Django is creating the two tables a_myuser and b_myuser for the model from the two different apps. Is there any way to direct the query from one particular table( from the different project i.e. a_myuser)? Note: The model doesn't contain any foreign key nor is used as a foreign key in any other model. Also, the views.py for the query doesn't import any models from any app. -
Cannot render the details saved in database to another app in same project
This is my HTML File in where I am trying to render the details of the AffProduct Model which has been saved and created in another app inside the project named: affiliation. I am using from affiliation.models import AffProduct to import the details of the product in which the details have been saved. But the details is not rendering and also showing no error. <!-- Start of Online Shopping Part--> <h1>I-Frame</h1> <iframe height="75%" id="encoder_iframe" src="{% url 'blink_network' %}" width="50%"> </iframe> <div class="a-section a-spacing-none"> <div class="a-row"> {% for rows in resulted %} <div class="a-column a-span12"> <div class="a-section a-spacing-medium"> <a class="a-color-base a-link-normal" href=””></a> <div class="a-row"> <a class="a-color-base a-link-normal" href=""> <div class="a-column a-span4 a-text-center"> <img alt="X" src="{{rows.img1.url}}"> </div> </a> <div class="a-column a-span8 a-span-last"><a class="a-color-base a-link-normal" href=””> <div class="a-section a-spacing-none"> <span class="a-size-base-plus a-color-base a-text-bold" dir="auto">{{rows.product_title}}</span> </div> <div class="a-section a-spacing-none apb-browse-searchresults-mobileproduct-byline"> <span class="a-size-small a-color-secondary a-text-normal" dir="auto">ID: {{rows.uid}}</span> </div> <div class="a-section a-spacing-none a-spacing-top-micro"> <i class="a-icon a-icon-star-small a-star-small-4"></i> <span class="a-size-small a-color-secondary" dir="auto">14,464</span> </div> </a> <div class="a-section a-spacing-none a-spacing-top-micro"> <a class="a-color-base a-link-normal" href=""> <span class="a-price" data-a-color="base" data-a-size="l"><span class="a-offscreen">₹{{rows.sale_price}}</span><span aria-hidden="true"><span class="a-price-symbol">₹</span><span class="a-price-whole">{{rows.sale_price}}<span class="a-price-decimal">.</span></span></span></span> <span class="a-price a-text-price" data-a-color="secondary" data-a-size="b" data-a-strike="true"><span class="a-offscreen">{{ rows.discount }}</span><span aria-hidden="true">{{ rows.discount }}</span></span> <b>FREE Delivery.</b> </a> <a href=" ">Details</a> </div> <div class="a-section a-spacing-none a-spacing-top-micro"> Delivery By: <b>July … -
Django/Postgres integration issues
whenever i try to integrate the postgres database into my django application to deploy on heroku. It continues to display this error despite the correct integration made on the settings.py. how do i fix this? File "/home/tochikaze/Projects/b-aid/env/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type timestamp with time zone to interval LINE 1: ...LUMN "last_login" TYPE interval USING "last_login"::interval -
Django - Giving "a bytes-like object is required, not 'dict'" error while trying to create manual jwt token function
I need to create custom JWT token creator. When I want to test it with dump data it gives this error. All I need is return a json web token. I am new to Django and Python. I partially understand the problem but can't relate. I'm struggling with data types while working on them. I tried to convert token variable into different data type but didn't work. https://dpaste.com/B9K9KWP27 Here is my codes def base64url_decode(input: Union[str, bytes]) -> bytes: if isinstance(input, str): input = input.encode("ascii") rem = len(input) % 4 if rem > 0: input += b"=" * (4 - rem) return base64.urlsafe_b64decode(input) def base64url_encode(input: bytes) -> bytes: return base64.urlsafe_b64encode(input).replace(b"=", b"") def jwt_creator(expiration, userid, userrole): header = { "alg": "HS256", "typ": "JWT" } payload = {'expired': expiration, 'userid': userid, 'userrole': userrole } secret_key = secrets.token_hex(32) userauth =User_Tokensec(iduser_tokensec=userid, key=secret_key, personal_id=Personal.objects.get(id=userid)) userauth.save() total_params = base64url_encode(header) + '.' + base64url_encode(payload) signature = hmac.new(secret_key, total_params, hashlib.sha256).hexdigest() token = total_params + '.' + base64url_encode(signature) context3 = {'jwt': token, 'title': 'jwtt'} return context3 def jwt_decoder(jwt): input = jwt.split(".") payload = base64url_decode(input[1]) secret_key = User_Tokensec(personal_id=payload['userid']) header = { "alg": "HS256", "typ": "JWT" } total_params = base64url_encode(header) + '.' + base64url_encode(payload) signature = hmac.new(secret_key, total_params, hashlib.sha256).hexdigest() token = total_params … -
I have this error in my project, how can i rectify this error? How can i add jinja template extention in my visual studio 2019?
{% extends 'base.html' %} 2 3 {% block content %} 4 5 Hello {{name}}!!!!! 6 7 8 {% csrf-token %} 9 10 Enter 1st number= 11 Enter 2nd number= 12 13 14 15 {% endblock %} -
i want to handle multiple manytomanyField in django but i got different types of error
I want to handle multiple manytomanyField in Django but I got different types of error. I use json response for save the data .but i got different errors like invalid literal for int() with base 10 , and other function savecontract(){ allowance = $('#allowance').val(); var data = new FormData(); data.append("allowance", allowance) var r = false; $.ajax({ type: 'POST', contentType: "application/json; charset=utf-8", contentType: false, processData: false, url: '/Employee/savecontract/', data: data, async: false, success: function (response) { if(response.status == "success"){ $('#cid').val(response.id) r=true; } else{ swal("Error","Something Went Wrong!","error") } }, error: function () { swal("Error","Something Went Wrong!","error") } }); return r; } }); {% for d in allowance %} <input value="{{d.id}}" type="checkbox" class=" " name="{{allowance.enName}}" id="allowance" style=" zoom: 1.5;"> {{d.enName}}<br> {% endfor %} models.py class allowances(models.Model): enName = models.CharField(max_length=200, blank=True, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) class CreateContracts(models.Model): allowance = models.ManyToManyField(allowances) views.py def savecontract(request): uid = request.session["userid"] e = Employees.objects.get(user=uid) allowance = [x.enName for x in allowances.objects.filter(company=e.company)] allowance_id=[] for x in allowance: allowance_id.append(int(request.POST.get(x))) if request.POST.get(x) else print("Error") for x in allowance_id: contract.allowance.add(allowances.objects.get(id=x)) contract.save() res = {"status": "success"} return JsonResponse(res) -
Is it possible to access form inputs which are looped with django?
I have this form to answer a survey a user received in a html file. <form method="POST" action="/answerSurvey"> <ol> {% for q in questions %} <li> <label for="questionBody"><b>{{ q.body }}</b></label> <ul style="list-style: none;"> {% for a in answers %} {% if q.id == a.question_id %} <li><input type="checkbox" name="{{ a.id }}"> {{ a.body }}</li> {% endif %} {% endfor %} </ul> </li> {% endfor %} </ol> <button type="submit">Submit</button> </form> I want to create a function to receive the user input to see which questions got ticked. Something similar to @app.route('/answerSurvey', methods=['GET', 'POST']) @login_required def answerSurvey(): question_answers = request.form['something'] so I can store them in a database table with the associated answer.id. -
ValueError: Unable to configure handler 'file_store'
I tried to setup handler of django logging for display my filtters in a file; This is my handler in settings.py: 'handlers': { 'file_store': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'logs', 'phones.log'), 'formatter': 'verbose' } }, and this one is my logger in settings.py: 'loggers': { 'root': { 'phones': { 'handlers': ['file_store'], 'level': 'INFO', }, } } I interested to display my logger messages in a file in the name phones.log, but after I run ./manage.py runserver command, it shows me this error messeage: ValueError: Unable to configure handler 'file_store' -
Custom Django User with Default values
I am using Django 3.2 with Restframework. I have created a custom user for my project and given default values in Models for some fields. But the default values are not accepted when the POST request is made. Like for example, "date_joined" is left blank, then it has to be today's date, but while making request from postman, its taking it as mandatory field. What am I doing wrong? Models.py class MasterUser(AbstractBaseUser): email = models.EmailField(verbose_name='email address',max_length=255,unique=True,) date_of_birth = models.DateField(default="2020-10-10") is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) firstname = models.CharField(max_length=100,blank=True) lastname = models.CharField(max_length=100,blank=True) is_member = models.BooleanField(default=False) date_joined = models.DateField(default=datetime.now) last_signed_in = models.DateTimeField(default=datetime.now) is_subscription = models.BooleanField(default=True) category = models.CharField(max_length=100, null=True) contact = models.CharField(max_length=100, blank=True, unique=True) membership_id = models.CharField(max_length=100, blank=True) objects = MyUserManager() serializer class RegisterUserSerializer(serializers.ModelSerializer): ... ... def save(self): timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) account = MasterUser( email = self.validated_data['email'], firstname = self.validated_data['firstname'], lastname = self.validated_data['lastname'], is_member = self.validated_data['is_member'], date_joined = self.validated_data['date_joined'], last_signed_in = self.validated_data['last_signed_in'], is_subscription = self.validated_data['is_subscription'], category = self.validated_data['category'], contact = self.validated_data['contact'], membership_id = hashString(str(timestamp)) ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Password doesnt matches'}) account.set_password(password) account.save() return account views.py def registration_view(request): if request.method == "POST": is_member = request.POST.get('is_member') timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) serializer = RegisterUserSerializer(data= request.data) data … -
using email and username for login in django
what do I do to put username and email login together in django? I mean something like: enter your Username/Email I tried this before: log = authenticate(request, username=username or email=email, password=password) but I faced an error is there any suggestion? -
Using a multi-table inheritance model as a through table
I'm trying to use a multi-table inheritance model as a through table, as shown below: class Base(models.Model): ... class Through(Base): ... class RelatedModel(models.Model): ... class Model(models.Model): field = models.ManyToManyField(RelatedModel, through='Base') instance = Model.objects.get(pk=1) related = RelatedModel.objects.get(pk=1) instance.add(related) # ValueError: Can't bulk create a multi-table inherited model However, I keep running into an error when adding a model to the ManyToMany relationship, as to how multi-table inheritance models cannot be bulk created. Is there any way around this? ManyToManyField.add doesn't take a bulk argument so it doesn't seem to be possible to disable bulk creation there. Does anyone know of a workaround for this without getting rid of the inheritance? -
django.db.utils.OperationalError: no such table: themes_theme
Django = 3.2.3 from django.core.exceptions import ValidationError from django.forms import ModelForm from themes.models import Theme class ThemeForm(ModelForm): def clean_archived(self): number_of_active_themes_without_current_instance = len(Theme.objects.filter(archived=False).exclude(id=self.instance.id)) number_of_active_themes_with_current_instance = number_of_active_themes_without_current_instance + int( self.instance.archived) if number_of_active_themes_with_current_instance > 1: raise ValidationError("Only one active theme is possible.") return self.cleaned_data['archived'] class Meta: model = Theme exclude = [] ########################################################################### from django.core.exceptions import ValidationError from django.forms import ModelForm from themes.models import Theme class ThemeForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.active_other_themes = Theme.objects.filter(archived=False).exclude(id=self.instance.id) def clean_archived(self): number_of_active_themes_without_current_instance = len(self.active_other_themes) number_of_active_themes_with_current_instance = number_of_active_themes_without_current_instance + int( self.instance.archived) if number_of_active_themes_with_current_instance > 1: raise ValidationError("Only one active theme is possible.") return self.cleaned_data['archived'] class Meta: model = Theme exclude = [] The former code inflicted the error after I did makemigrations: File "/home/michael/PycharmProjects/articles_outer/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: themes_theme Well, the latter code works with migrations. Could you explain to me why the former code is erroneous whereas the latter code is fine? -
Problem while deploying a webapp toheroku
I've been trying to deploy a webapp written in django to heroku but there always is an error: remote: Building source: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: e533e6e087af4e4a8897664c179c241ddd2833c3 remote: ! remote: ! We have detected that you have triggered a build from source code with version e533e6e087af4e4a8897664c179c241ddd2833c3 remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku :main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: remote: Verifying deploy... remote: remote: ! Push rejected to radiant-lake-54163 I tried somethings. Firstly, I created a new account in heroku and then tried and I still received … -
writing django queries for one to many relationships, (django query and taggit)
So i have a model called "Ad", for the sake of my question, let's say this is my model: from django.core.validators import MinLengthValidator from taggit.managers import TaggableManager title = models.CharField( max_length=200, validators=[MinLengthValidator(2, "Title must be greater than 2 characters")] ) tags = TaggableManager(blank=True) where TaggableManager is from django-taggit module In my views, i am implementing search, which gives result filtering results based on title field: from django.db.models import Q class view(View): def get(self, request): strval = request.GET.get("search", False) if strval : query = Q(title__icontains=strval) query.add(Q(text__icontains=strval), Q.OR) ad_list = Ad.objects.filter(query).select_related().order_by('-updated_at')[:10] What i wish to add is: if a user types in keywords which are from a tag rather than a tittle, the result should display the Ads which have those tags. I know it is possible to add this feature as i saw the support for ManyToMany Fields in django queries, but i am not sure if that would work with django taggit. Can someone please help me with this? -
How to convert image url into ImageField - Django
am creating a donation web application. Users are able to fill out a form and there donation is submitted into the database, I was wondering how I can have the user submit a url of an image and save it in the database, and then render it on another page. For example, if the user fills out the form and submits a url like https://images.unsplash.com/photo-1481349518771-20055b2a7b24?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8cmFuZG9tfGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&w=1000&q=80, how would I save this to the database as an Image and not a URL? I should then be able to render it out on another page. Html Form: <label class="label-input100" for="image">Image</label> <div class="wrap-input100"> <input id="phone" class="input100" type="text" name="image" placeholder="Please enter the url of your image" required> <span class="focus-input100"></span> </div> My view: (There is a lot of stuff here that do not pertain to my question, I just included it in case it is needed) def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] date = datetime.datetime.now().date() ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, date = date ) ins.save() # New part. Update donor's stats. UserDetail.objects.filter(user=request.user).update(donations=F('donations') … -
Getting error DecimalFields must define a 'max_digits' attribute
I'm having a problem with these DecimalField types. I have the next model: class Mediciones(models.Model): id = models.AutoField(primary_key=True) nombre = models.CharField(max_length=30, verbose_name='Nombre dispositivo') dispositivo = models.ForeignKey(Dispositivos, on_delete=models.CASCADE) temperatura = models.DecimalField(max_digits=5, decimal_places=2) humedad = models.DecimalField(max_digits=5, decimal_places=2) ruido = models.DecimalField(max_digits=7, decimal_places=2) c02 = models.DecimalField(max_digits=7, decimal_places=2) alerta = models.BooleanField(null=False) fecha = models.DateTimeField(verbose_name="Fecha", blank = False) As you can see, I have four DecimalField, and all of them have defined both "max_digits" and "decimal_places", and max_digits is greater than decimal_places. Despite of that, I'm getting errors "DecimalFields must define a 'max_digits' attribute." when I try to make a migration. Do you know why? Thanks in advance! -
Optimal way to create test requests for Python (Django) REST APIs
I have an API/microservice written in Django which is computational in nature. Depending on the request parameters, the API does some computations and gives an output. I need to test the API by simulating various possible combinations of requests and corresponding responses. A few points to consider about my API: The request consists of around 20 parameters. Each parameter can be of different type, for eg. binary, lists, dictionary, etc. Based on the whole input request, the API does some computation which I need to test. Example of a dummy request with just 3 params: { param1: True/False, param2: list of strings param3: list of dictionaries } Each combination of parameter gives a different output. For example in the above request with 3 params, I can have 2 scenarios to test - by putting param1 as True and False. Similarly I can pass various strings in param2 list ( I have predefined set of eligible strings) and so on. Thus with around 20-25 parameters, I have a lot of requests possible with different combinations of parameters taken at a time. Currently I am storing each request in a file by manually creating the request for various combinations possible. Then I … -
Multiple Login Backend with django rest auth
I am using Django rest auth token authentication for a particular project. There are four different types of users (agent, admin, buyer, seller). I have implemented a custom login serializer with a contact number & password for login. But actually, for agent users, I want only employee id to authenticate the user, I have created the unique employee id. but don't know how to implement a different login backend for this particular user. can you share some ideas for this? For buyer, seller, the default login backend working with no issue. But for agents, I need to implement differently. -
Django - handling guest users
I have a general question about how to best handle the logic for guest users. What I have is a website (sort of HacknPlan clone) and when a non-registered (guest) user accesses the page, he/she can interact with the page (create tasks,...) the same as a registered one, but with limitations. I'm using this logic to determine and create a guest user in a database: class Account: def __init__(self, request): self.request = request def getUser(self): if not self.request.user.is_authenticated: ip = get_client_ip(self.request) if UserAccount.objects.filter(ip_address=ip).exists(): return UserAccount.objects.get(ip_address=ip) random_username = f"{randomString(10)}_guest" random_email = f"{randomString(5)}_guest@example.com" guest_user = UserAccount.objects.create( username=random_username, email=random_email, ip_address=ip, is_active=False ) return guest_user else: return self.request.user As you can see, I'm also adding the IP address to the guest user, so when the guest refreshes or revisits the page, I can get this particular guest from the database. Previously, instead of saving its IP, I was saving the session key, but I noticed the key was changing when for example I would log in with an already registered user. This was causing the creation of a new guest user every time I would log out a registered user. If the guest uses chooses to become a registered one, this I how the … -
Django get_FOO_Display() for range list choices
STATUS_APPROVE, STATUS_REJECT, STATUS_PROC, STATUS_PEND, STATUS_PAID = range(5) STATUS_CHOICES = ( (STATUS_APPROVE, 'Approved'), (STATUS_REJECT, 'Rejected'), (STATUS_PROC, 'Processing'), (STATUS_PEND, 'Pending'), (STATUS_PAID, 'Paid'), ) class ExpenseClaim(TimeStampedModel): status = models.PositiveIntegerField(default=STATUS_PEND, choices=STATUS_CHOICES, blank=False) class MileageClaimSerializer(serializers.ModelSerializer): status = serializers.ChoiceField(choices=STATUS_CHOICES) I cannot work out a way to get foo display for a choice list with range. So the range keys are used to store the point in list. I need the serializer to return the word and not the key. -
How to add a commented line with relative path to the first line of vim file
I am making a Django web app using Vim, and I want to add a commented line to the top of each file, I open or create, with its relative path. For example: # config/urls.py, using c-r and c-% for its relative path. So far I've been working on this bash script. #!/bin/bash echo "Enter file name" read newfile if [[ $newfile = *.py ]]; then `touch $newfile && echo "# $PWD"/"$newfile">>$newfile` vim $newfile; elif [[ $newfile = *.html ]]; then `touch $newfile && echo "<!-- $PWD"/"$newfile -->">>$newfile` vim $newfile; elif [[ $newfile = *.css ]]; then `touch $newfile && echo "/* $PWD"/"$newfile */">>$newfile` vim $newfile; else vim $newfile fi That opens with # /home/menashe/testdir/test1.py. How do I only add the relative path testdir/test1.py? Is it possible to put the Vim commands in the script? How do I append a comment to the first line of a file that isn't empty? Thank you -
Resizing images with django-resized
I'm using django-resized to reduce sizes of images when they are uploaded to AWS S3. The resizing works fine when the image is wider than its height. However, when image height is bigger than its width then the output image is rotated by 90 degrees and its width is bigger than its height. models.py from django_resized import ResizedImageField class Catch(models.Model): fish_type = models.CharField("Fish Type", max_length=50, choices=fish_choices, default="Carp") catch_id = models.AutoField(primary_key=True) weight = models.DecimalField("Weight", max_digits=5, decimal_places=2) length = models.DecimalField("Length", max_digits=5, decimal_places=2, blank=True, null=True) datetime = models.DateTimeField("Catch Time", auto_now=False, auto_now_add=False) image = ResizedImageField(size=[1080, 1350], quality=95, null=True, blank=True, default="default_img.png", upload_to="catch_images/") fisherman = models.ForeignKey(Fisherman, on_delete=models.CASCADE) trip = models.ForeignKey(Trips, on_delete=models.CASCADE) hookbait_name = models.CharField('Csali megnevezése', max_length=120, blank=True, null=True) hookbait = models.ForeignKey(HookBait, on_delete=models.SET_NULL, blank=True, null=True) settings.py DJANGORESIZED_DEFAULT_KEEP_META = True DJANGORESIZED_DEFAULT_FORCE_FORMAT = 'JPEG' DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {'JPEG': ".jpg"} DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True I only want to reduce sizes of images while they're preserving the aspect ratio. Thanks in advance for any help.