Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MPTT - can't update TreeForeignKey data (lft, rgth... etc)
my model class Category(MPTTModel, models.Model): api_uuid = models.UUIDField(null=False, blank=False, unique=True) department = models.ForeignKey(Department, on_delete=models.DO_NOTHING, related_name='categories', to_field='api_uuid', db_column='department_api_uuid', blank=True, null=True, db_constraint=False) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.DO_NOTHING, help_text=_("Parent's UUID")) name = JSONField(blank=True, null=True, default=dict) code = models.IntegerField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "category" category section from the view: for category_data in categories_data[1:]: category_api_uuid = category_data.pop('uuid', None) category_data['api_uuid'] = category_api_uuid department_uuid = category_data.pop('department_uuid', None) department = departments.filter(api_uuid=department_uuid).first() category_data['department'] = department parent_uuid = category_data.pop('parent', None) parent_category = Category.objects.filter(api_uuid=parent_uuid).first() category_data['parent'] = parent_category category = Category.objects.filter(api_uuid=category_api_uuid).first() if category: instance = Category(category.id, **category_data) instance.save() else: instance = Category(**category_data) instance.save() I am getting data from the API and can successfully create instances in the database on the first try. Whenever I try to update instances in the databases everything except 'parent' related fields get updated. fields that does not update: (leftt, rightt, level, parent, parent_id) can anyone help with this one?? Appreciate any help -
How to get coverage report 100% in my Django project
I have written test cases for all my views in my Django project views.py. For example I have written test case for coupons page here is my code snippet in views.py def coupons(request): try: email = request.session.get('email') # From 'master_table' model filtering items by type_of_product 'C' and getting query set. coupon = master_table.objects.filter(type_of_product='C').order_by('-rebate') couponBMC = vk_master_table.objects.filter(type_of_product='BMC').order_by('-rebate') # Counting no.of objects from query set. count_c = master_table.objects.filter(type_of_product='C').order_by('-rebate').count() countBMC = master_table.objects.filter(type_of_product='BMC').order_by('-rebate').count() count = count_c + countBMC # Pagination by using query set and count(counting number of objects in query set). coupons = random.sample(list(chain(coupon, couponBMC)), k=count) # First page by default. page = request.GET.get('page', 1) # Per page we are setting 40 objects. paginator = Paginator(coupons, 40) coupons = paginator.page(page) except PageNotAnInteger: coupons = paginator.page(1) except EmptyPage: coupons = paginator.page(paginator.num_pages) except Exception as e: logging.error(e) return render(request, "coupons.html", {'error': error, 'banners': bestDeals(), 'form': HomeForm(), 'ClassifiedBar': Extras.ClassifiedBar(request), 'time': settings.SESSION_IDLE_TIMEOUT, 'name': first_last_initial(email), 'fullname': fullname(email), 'CategoriesBar': Extras.CategoriesBar(request), 'AdvertiserBar': Extras.AdvertisersBar(request), 'KA_Banner': advertiser_banners.KA_Banners(request), 'LA_Banner': advertiser_banners.LA_Banners(request), 'id': request.session.get('id'), 'BB_Banner': advertiser_banners.BB_Banners(request)}) return render(request, "coupons.html", {'Coupons': coupons, 'banners': bestDeals(), 'form': HomeForm(), 'ClassifiedBar': Extras.ClassifiedBar(request), 'time': settings.SESSION_IDLE_TIMEOUT, 'name': first_last_initial(email), 'fullname': fullname(email), 'CategoriesBar': Extras.CategoriesBar(request), 'AdvertiserBar': Extras.AdvertisersBar(request), 'id': request.session.get('id'), 'KA_Banner': advertiser_banners.KA_Banners(request), 'LA_Banner': advertiser_banners.LA_Banners(request), 'BB_Banner': advertiser_banners.BB_Banners(request) }) Here is my test case for above snippet @pytest.mark.django_db … -
Delete Image on Cloudinary via Django Admin
I am not sure what code to paste here, but I am using CKEditor in Django Admin and Cloudinary as the image storage server. CKEditor has this problem that when a post is deleted the accompanying images are not deleted. I thought there could be a way to manually delete pictures using a file browser. But https://django-filebrowser.readthedocs.io/en/latest/ does not support cloudinary. Is there any file-browser that can seamlessly work with cloudinary? -
Django: Show logging WITHOUT creating mysite.log file
I don't want the mysite.log file with my basic Django logging setup because the file typically ends up being massive and I don't use it. How can I still have the error messages show up when running python manage.py runserver and in my Heroku logs WITHOUT having a mysite.log file created? My logging settings in my settings.py file are below (note: these settings were copy & pasted from another stackoverflow post): DEBUG_PROPAGATE_EXCEPTIONS = True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt' : "%d/%b/%Y %H:%M:%S" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'mysite.log', 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers':['file'], 'propagate': True, 'level':'DEBUG', }, 'MYAPP': { 'handlers': ['file'], 'level': 'DEBUG', }, } } -
Videos in Django didn't go forward in the duration
Videos in Django didn't go forward in the duration, is this a public problem in Django or just because I working in the virtual environment, I road a lot about this problem and this is a lot of opinions, some problem because the problem in HTTP and another because I Working in the virtual environment, so I tried my website in the all kind of the browsers and didn't work finally except the Firefox, that only one I able to going forward in the video duration. So my question is when I deploy my website is this will continue or Not? -
Django model saves when it shouldn't
I'm trying to set custom validation rules on my Django models. I have the following code: Entity.py from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from django.db import models class Entity(models.Model): TYPE_CHOICES = [ ('asset', 'asset'), ('company', 'company') ] entity_type = models.CharField(max_length=25, choices=TYPE_CHOICES) ... class Asset(Entity): ... class Company(Entity): ... Security.py from django.core.exceptions import ObjectDoesNotExist, PermissionDenied, ValidationError from django.db import models from .Entity import Entity class Security(models.Model): ... entities = models.ManyToManyField(Entity) def clean(self, *args, **kwargs) -> None: try: # Check that object has already been saved Security.objects.get(name=self.name) print("All entities:", self.entities.all()) if len([e for e in self.entities.all() if e.entity_type == 'company']) > 1: raise ValidationError("A security can only be related to one company") except ObjectDoesNotExist: pass return super(Security, self).clean(*args, **kwargs) def save(self, *args, **kwargs): try: self.full_clean() return super(Security, self).save(*args, **kwargs) except ValidationError: raise ValidationError("A security can only be related to one company") class Bond(Security): ... class Equity(Security): ... What I'm trying to do is to prevent a Security from being saved if its field entities holds more than 1 company. The entities field is a ManyToMany relationship with Entity, as it can hold multiple Asset objects but only one Company. This is my test file class EntityTestCase(TestCase): def test_multiple_companies_fail(self): b = Bond.objects.get(name='Bond 1') c1 … -
Django app extremely slow when using MYSQL database
I have developed my first Django application which runs fine locally when using a sqlite database however when I change my settings to use a RDS MYSQL database (hosted in the same region on AWS) each page takes up to 40 seconds to load as apposed to 0.4 seconds before. I expected performance to decrease using a remote database but a 95%% drop has me thinking I may be doing something wrong. Below are the performance stats loading my homepage using Django-debug-toolbar. MYSQL SQL: 2752.0 ms (5 queries ) CPU: 824.7ms Request: 7910.2ms Local SQLite SQL: 1.8ms (3 queries) CPU: 340.9ms Request: 360.0ms -
using raw sql join querry with pyodbc mssql django
hey guys am back again. So now i am trying to perform some raw join statements but they are not working. All the examples i see are either with php admin. i am using ms sql. I dont want do do the joins using the the django models instead i want to use raw querries to perform the join and render it to my html page. Plesa can someone tell me how to do the same. Here are my codes models.py from django.db import models class Company(models.Model): name = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) address = models.TextField(max_length=255) ph_no = models.CharField(max_length=17) tele = models.CharField(max_length=17) mail = models.EmailField(max_length=150) is_active = models.BinaryField(default=0) class Client(models.Model): company_id = models.IntegerField() first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) ph_no = models.CharField(max_length=17) tele = models.CharField(max_length=17) mail = models.CharField(max_length=100) is_active = models.BinaryField(default=1)``` views.py from django.shortcuts import render from .models import Company, Client import pyodbc import datetime import pytz con = pyodbc.connect('Driver={SQL server};' 'Server=;' 'Database=Shipping;' 'Trusted_Connection=True;') cursor = con.cursor() con.autocommit = False sql_join_client = ''' select Client.Client_id,Company.name,Client.first_name,Client.last_name, Client.ph_no,Client.tele,Client.mail,Client.IsActive,Client.last_update from Client join Company on Client.company_id=Company.company_id ''' #some names in model differ from the actual names in the db tables def showclient(request): cursor.execute(sql_join_client) # join result = cursor.fetchall() return render(request, 'client.html', {'Client': result}) client.html … -
Access webapp (django) externally cors?
I did follow some tutorial to create a webapp with django which hosts a bot widget.. When running locally (0.0.0.0:8000) everything works and the communication to the bot works perfectly ...When accessing the webapp via 192.xxx.xxx.xxx:8000 i get the website but the bot internally does not response... When i inspect the site....i get in the console an error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5005/webhooks/rest/webhook. (Reason: CORS request did not succeed)." in django in the setting.py file i do start django with source venv/bin/activate . && python manage.py runserver 0.0.0.0:8000 What do i miss....i guess the problem has to be in the communicaiton with the widget... I just wonder why it works if i run it locally... -
How to make this simple calendar example add remove and edit events
I need help converting this calendar to one that can add, remove, and edit events. I am using django through visual studio, so I need to know how to add the events to the database and how to manipulate them. I am thinking of using an add event button that will pull up a form created from django that you can submit and then it shows up on the calendar and if you refresh the page it stays there. This is the js code ;(function ($, window, document, undefined) { "use strict"; // Create the defaults once var pluginName = "simpleCalendar", defaults = { months: ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'], //string of months starting from january days: ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'], //string of days starting from sunday displayYear: true, // display year in header fixedStartDay: true, // Week begin always by monday or by day set by number 0 = sunday, 7 = saturday, false = month always begin by first day of the month displayEvent: true, // display existing event disableEventDetails: false, // disable showing event details disableEmptyDetails: false, // disable showing empty date details events: [], // List … -
Django with HAPROXY -Session cookie setup - set_cookie('haproxy_cookie_name, 'new_value') doesn't set the new value
I have a Django app with a HAPROXY load-balancer. I am using the Session cookie setup by the Load-Balancer to make the user go always for the same server to provide persistence as shown in this link: [https://www.haproxy.com/blog/load-balancing-affinity-persistence-sticky-sessions-what-you-need-to-know/#session-cookie-setup-by-the-load-balancer][1] for some reason I am wanting to be able to set the cookie So I can choose which server to access each time but reaponse.set.cookie('haproxy_cookie_name, 'new_value') doesn't set the new value I have also checked the reaponse.set.cookie works on other cookie and it works fine. Do anyone have any idea why this doesn't work? Is there other option to set the cookie value (from the server) -
UnboundLocalError while submitting radio button form in django
I am new to Django and I am working on a site which should take user input from Radio Button and use the selected value for further operations. I have seen some ways using Database, but I want to use a simple way to directly get the value of the selected radio button from the template. I am using Django forms and I am getting UnboundLocalError when submitting the form in HTML. It shows that local variable 'selected' referenced before assignment. I understand that the form is not valid, but I do not know why kindly help me out. PFA my codes. views.py (Only the part where value of selected radio button is accessed) def index(request): if "GET" == request.method: return render(request, 'index.html') else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file) form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("NUMS") else: form = CHOICES() worksheet = wb["Observed"] worksheet1 = wb[selected] forms.py from django import forms NUMS= [ ('one', 'one'), ('two', 'two'), ('three', 'three'), ('four', 'four'), ('five', 'five') ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(widget=forms.RadioSelect, choices=NUMS) index.html (Only the part of Radio buttons) <form action="index" method="POST"> {% csrf_token %} {{form.NUMS}} <input type="radio" id="NUMS" name="NUMS" value="1 Day Lead"> <label for="NUMS">1 Day Lead</label> <input type="radio" id="NUMS" … -
Unable to use and set up django-instagram package
I'm following the exact instructions in here https://github.com/marcopompili/django-instagram but I keep getting the error: django_instagram.templatetags.instagram_client - WARNING - variable name "instagram_profile_name" not found in context! Using a raw string as input is DEPRECATED. Please use a template variable instead! although I added to my urls.py the following: path('', TemplateView.as_view(template_name='index.html', extra_context={ "instagram_profile_name": "amd" })), I can't find any other resource to learn how to use this package, any help? -
How to subtract/Compare Date obtained from Query params and Django TimeZone?
I have certain date obtained from query params and I want to compare the date with Django timezone.now().date() but I am getting error as '<' not supported between instances of 'str' and 'datetime.date' I know query params date have come in str format and timezone.now().date() is in datetime.date format. here is my code so far def _validate_departure_date(self): print('-------') print(type(timezone.now().date())) if self._query_params.get('departure_date') < timezone.now().date(): raise ValidationError({'departure_date': 'Departure date should not be in past.'}) How to compare these dates? -
Difference Between Model , AbstractUser in Django
1>> Here we can create a News model from django.db import models class News(models.Model): title = models.CharField(max_length=180) slug = models.CharField(max_length=254) author = models.CharField(max_length=100) 2>> how this is different from above model from django.contrib.auth.models import AbstractUser class User(AbstractUser): name = models.CharField(max_length=70, null=True, blank=True) country = models.CharField(max_length=70, null=True, blank=True) region = models.CharField(max_length=70, null=True, blank=True) 3>> and django already create model with this name is it different from above two? can we add field what ever we like in this User Model instead of first_name,last_name,email(which django already provide) from django.contrib.auth.models import User -
Django QuerySet ordering by related fields length
I am beginner at django and trying to build a project with it. So I have 'Question' and 'Tag' models. I used ManytoMany relation between two. Like this: models.py class Question(models.Model): title = models.CharField(max_length=200) tags = models.ManyToManyField(Tag, blank=True) Here is my question: I'm using class based views for listing tags. At get_queryset() method, I want to return all 'Tag' objects ordered by number of questions they related. Shortly, I want to order data by another related datas lenght. How can i do that? Thanks for answers. -
V- model on input texbox on key up updates text on other v model input text in django for loop
I have this Django for loop where i have this form with input textbox that has v model. When i type a text on it , on key up it updates text on ther input texbox inside this django for loop : {% for drama in theatre %} <div class="comment-input" id="postcomment-{{tweet.id}}"> <form v-on:submit.prevent="submit0comment({{tweet.id}})" id="comment-{{tweet.id}}" > <input id=".input_1" type="text" v-model="comment_body" class="form-control"> <div class="fonts"> <button class="btn-share">Post</button> </div> </form> </div> <br> <div class="d-flex flex-row mb-2" v-for="comment in comments"> <img :src="comment.avatar" width="40" class="rounded-image"> <div class="d-flex flex-column ml-2"> <span class="name">[[comment.commenter]]</span> <small class="comment-text">[[ comment.comment_body]]</small> <div class="d-flex flex-row align-items-center status"> <small>Like</small> <small>Reply</small> <small>[[ comment.created_at ]]</small> </div> </div> </div> {% endfor %} -
When I use created_at__range to specify a range, the range is shifted by one day
I'm currently using the filter "created_at__range" to specify the first and last day of the month, but this code doesn't reflect the data registered today. this_month = datetime.datetime.today() first_day = datetime.datetime(this_month.year, this_month.month, 1) this_month = this_month.strftime('%Y-%m-%d') first_day = first_day.strftime('%Y-%m-%d') time = obj.filter(created_at__range=(first_day, this_month)).aggregate( time=Sum('time'))['time'] Currently, I'm using timedelta(days=1) to add a day, but if I do this, for example, if the date is 3/31, it will be 4/1 and the tally will be wrong. this_month = datetime.datetime.today() + timedelta(days=1) Why is this happening? If anyone knows how to improve it, I'd appreciate it if you could let me know. -
django social auth don't associate new users correctly
I am trying to use social auth in Django in my Django GraphQL API (an alternative to rest api). However, after I created the social auth I created a costume user which make things a bit complicated. Also, it worked at the begging very well but and it created the user called weplutus.1 very well, but later after I did few small changes that I don't think they coul matter atall, and I did migrations and migrate as well after that I don't know what helped exactly but it when new users register the social auth associate it the admin despite the admin have a different email. # settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '*****' DEBUG = True ALLOWED_HOSTS = ["*"] # TODO change this in preduction CORS_ORIGIN_ALLOW_ALL = True # TODO change this in preduction # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'graphene_django', 'corsheaders', 'api', 'django_filters', 'social_django', ] SITE_ID = 1 MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', … -
How can show which product is selected without submit
I create a category and product drop down menu, but when i select the category and press the select button it not show which category is selected same with product menu. I just want to show the message which category and product is selected. I used Django message but when i submit the page it show the product id. I want to show the selected category and product name before submit View.py class OrderProduct(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): allOrder = OrdersModel.objects.all() categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') predoct = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'product': predoct, 'allOrder': allOrder} return render(request, self.template_name, args) def post(self, request): productobj = self.request.GET.get('SelectProduct') if productobj: messages.info(request, productobj) try: data = self.request.POST.get orderProduct = OrdersModel( product_id=productobj, description=data('description'), quantity=data('quantity'), ) orderProduct.save() return redirect('orderProduct') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory"> <option disabled="disabled" selected> Select Category</option> {% for category in categories %} <option value="{{ category.id }}"> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> <label> <select name="SelectProduct"> <option disabled="disabled" selected> Select Category</option> {% for products in product %} <option value="{{ products.id }}"> {{ products.name }} </option> {% endfor … -
How do I set the dialect for a SQLAlchemy connection pool with PostgreSQL in Django Python? Needed for pre-ping feature enabled
What I'm trying to achieve I need to activate the pre-ping feature for as SQLAlchemy db pool in Django Python. Error When I set the pre_ping property to True, I get the following error which says I need to pass a dialect to the connection pool when using the pre-ping feature: The ping feature requires that a dialect is passed to the connection pool. Code Code for the connection pool creator/handler: import psycopg2 from sqlalchemy import create_engine import traceback from mbrain import settings from dataClasses.EmptyObject import * import json import sqlalchemy.pool as pool from sqlalchemy.pool import QueuePool dbPool = None class DbPoolHelper: def ensurePoolCreated(self): global dbPool if dbPool != None: return self.createPool() def dbConnect(self): dbConfig = self.getDbPoolConfig() dbConnection = psycopg2.connect(user=dbConfig.user, password=dbConfig.password, dbname=dbConfig.dbName, host=dbConfig.host, port=dbConfig.port) print("=========== POOL CONNECTED =================") return dbConnection def createPool(self): dbConnection = self.dbConnect global dbPool dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5, pre_ping=True) print("=========== POOL CREATED =================") def execute(self, sql, sqlParams): try: global dbPool self.ensurePoolCreated() poolConnection = dbPool.connect() cursor = poolConnection.cursor() cursor.execute(sql, sqlParams) poolConnection.commit() result = cursor.fetchall() cursor.close() poolConnection.close() return result except Exception as e: print(e) return e def getDbPoolConfig(self): settingName = "pool" dbConfig = EmptyObject() dbConfig.host = settings.DATABASES[settingName]["HOST"] dbConfig.port = settings.DATABASES[settingName]["PORT"] dbConfig.user = settings.DATABASES[settingName]["USER"] dbConfig.password = settings.DATABASES[settingName]["PASSWORD"] dbConfig.dbName = … -
How do you set Django environment variables with venv on linux?
I've tried using Python's os, manually typing the variables into the terminal, and using a .env file to set my environment variables but always get raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. Python import os os.environ['SECRET_KEY'] = '<my secret key>' Inside .env export SECRET_KEY=<my secret key> In the terminal echo $SECRET_KEY >>>os.getenv('SECRET_KEY') both manage to print the variable. Ubuntu 20.04.02 Django 3.1 Using VSCode I have double checked the correct venv activated. What am I doing wrong! Thanks -
Django Access id field from parent model with javascript
here is my problem : In my template, I want to access the primary key of a queryset element which is a child of a parent model where the id attribute "id" is explicitly given. I gave it to my template using JSON serialization but I can't access the fields of the parent model. But when I use the python interpreter, I have no problem to access it, just like if it was the child's attribute. Here is the code : models.py class Correspondant(models.Model): nom = models.CharField(max_length=70) id = models.IntegerField(primary_key=True) class GRP(Correspondant): numTel = models.CharField(max_length=70) libelle = models.CharField(max_length=70) views.py : def index(request): listeGRP = serializers.serialize("json",GRP.objects.all()) context={'listeGRP':listeGRP} return render(request, 'annuaire/index.html', context) and how I access the GRP attributes with javascript : var tabGRPs = JSON.parse('{{ listeGRP|safe }}'); console.log(tabGRPs[0]["fields"]); which gives the following result : Object { numTel: "333333", libelle: "CATC Test 1" } As you can see, there are not the attributes of 'Correspondant' which is a parent of 'GRP'. Anyone has any solution ? Thank you ! -
JS fetch multiple pics (as FormData) to Django to save
I'm sure this seems so basic but it's my first attempt to try to upload files to django using fetch and I'm not sure how to manipulate and access FormData in Django.This create so many non-working jpg files. How to fix it? HTML: <div> <textarea></textarea> <input type="file" multiple></input> <button onClick="dothis" >Sound</button> </div> JS: function dothis(){ let data = new FormData(); let input = event.target.previousElementSibling; for (let file of input.files){ d.append( "hello", file); } fetch("/images", { credentials: "include", method: "POST", mode: "same-origin", headers: { "Accept": "application/json", "Content-Type": "application/json", // or "multipart/form-data"?? "X-CSRFToken": csrf }, body: data }) .then(response => response.json()) .then(result => { console.log("Well?"); }) Django views.by: def images(request): print(request.body) form = request.body filename = 0 for f in form: filename += 1 with open(f"{filename}.jpg", "wb+") as f: f.write(form) return JsonResponse(status=201) -
Migrate SQLite to PostgreSQL in DRF
I am trying to change my DB from SQLite to PostgreSQL. The problem which I am facing the size of the SQLite after dumpdata is 1.96GB. and when I am trying to load data I am getting an error: MemoryError: Problem installing fixture The command which I am using to import is : python manage.py loaddata dumpdata.json I can't find any external way to insert this JSON file directly to PostgreSQL. Can you help me what will be the best way to loaddata to Postgresql?