Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reverse for 'new_entry' with arguments '(")' not found. 1 pattern tried: ['new_entry'/int:topic_id>/']
I am receiving this error when i run my program. The error is said to occur in my topic.html but i am unsure what I typed in wrong for topic_id to return with an empty string. views.py from django.shortcuts import render, redirect from .models import Topic from .forms import TopicForm, EntryForm Create your views here. def index(request): """The home page for Test log""" return render(request, 'test_logs/index.html') def topics(request): """Show all topics""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'test_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'test_logs/topic.html', context) def new_topic(request): """Add new topic""" if request.method != 'POST': \#No data submitted; create a blank form. form = TopicForm() else: \# POST data submitted; process data. form = TopicForm(request.POST) if form.is_valid(): form.save() return redirect('test_logs:topics') context = {'form': form} return render(request, 'test_logs/new_topic.html', context) def new_entry(request, topic_id): """Add a new entry for a particular topic""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_vaild(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return … -
Theme Customize on Django CMS [closed]
Hello I'm trying to find cms like WordPress on django -
How to protect or secure API routes access Django Rest_framework? [duplicate]
I built my personal website with ReactJS on the client side and Django with Rest_framework for API, Django is serving staticfiles. My personal website has nothing crazy just one API that handles the email. If someone want to get in contact with me then they can fill the form with their email name etc, however. I was able to get access to that api by use typing in the url https:.//www.personalwebsiteurl.com/api/contact-by-email, see screenshot below. Ever since, i got hired as an intern at a small company working with MEAN Stack, i totally forgot most of Django workaround. Thus, how could i secure access to this api/route or if this could potentially cause a security incident on my website? Thank you in advance, not necessarily looking for an a solution with the code but rather than a guide to come up with solution this is my urls.py under api module this is my urls.py under the server -
AxiosError: Network Error in React Native and Django
I am new in Django and React Native. Im using Django rest framework to connect my front end to backend. and I am using "axios" in sending request to django I am trying send URL in django. After receiving, the django will give the length of the url as a response to the react native. I access the path of django in my browser and I think it works fine However, the react native shows "[AxiosError: Network Error]". Your help is deeply appreacited. React Native It sends URL to django const [countChar, setcountChar] = useState() const sendData = async() =>{ const url = "Hello" const response = await axios.post( 'http://127.0.0.1:8000/validationServer/validate/', { url } ); setcountChar(response.data.character_count); console.log(countChar) } <TouchableOpacity style={{backgroundColor:"white" ,padding:20}} onPress={ () => sendData()}> <Text>Send</Text> </TouchableOpacity> validationServer/ view.py from rest_framework.decorators import api_view from rest_framework.response import Response from .serializer import UrlSerializer @api_view(['POST']) def validation (request): if request.method == 'POST': serializer = UrlSerializer(data=request.data) if serializer.is_valid(): url = serializer.validated_data['url'] character_count = len(url) return Response({'character_count': character_count}) return Response(serializer.errors, status=400) validationServer/ serializer.py from rest_framework import serializers class UrlSerializer(serializers.Serializer): url = serializers.CharField(max_length=2048) validationServer /urls.py from django.urls import path from . import views urlpatterns = [ path ("validate/",views.validation, name='url-character') ] // main / urls.py from django.contrib import … -
How to fix port error when creating Django backend service on Google Cloud Run?
I have a Django REST backend image in which I tried to create a service for it on Google Cloud Run. In the Google Cloud Run, I set the port to 6000, and when I tried to create it, it showed these errors: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2002, "Can't connect to MySQL server on '35.226.227.51' (115)") The user-provided container failed to start and listen on the port defined provided by the PORT=6000 environment variable. Default STARTUP TCP probe failed 1 time consecutively for container "backend" on port 6000. The instance was not started. The last 2 layers on the Dockerfile of my backend are: EXPOSE 6000 CMD python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:6000 I am not sure how to fix this for this is my first time trying to deploy a website. For the database error, I have checked the database credentials and configured my Django settings.py to connect to my Google Cloud SQL, MySQL instance with the public IP address as shown and made sure the configuration is correct, but not really sure why it is showing that error. Any help would be … -
Django/DRF GET list of objects including object with FK to that object
I have an API endpoint that returns a list of objects (Orders). class Order(models.Model): item_name = models.CharField(max_length=120) Each of these Orders also has multiple associated Statuses, which acts similar to tracking the location of a package. A new one is created whenever the status changes, with the new status and a timestamp. class OrderStatus(models.Model): status = models.CharField(max_length=30) timestamp = models.DateTimeField(auto_now_add=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="order_statuses") When I query a list of the current Orders, I want to return the most recent OrderStatus associated with it. Such as this: { "count": 2, "next": null, "previous": null, "results": [ { "item_name": "Something", "order_status": { "status": "Processing" "timestamp": "2023-09-25T12:31:12Z" } }, { "item_name": "Other Thing", "order_status": { "status": "Completed" "timestamp": "2023-08-15T10:41:32Z" } } ] } I have tried using prefetch_related() in my View, but that seems to be for the reverse situation (When the query is for the object that has the FK in it's class definition - which here would be if I wanted to list the fields on Order when I query for the OrderStatus). -
Google Charts - Very Slow Loading Time
I'm relatively new to web development and I like the look of Google Charts. I wanna load some Django data with it, but the load time is extremely slow. I have a simple chart here with only a single point. It takes 3-5 seconds to appear, after everything else on the webpage has already shown up. Am I doing anything wrong or could something be causing the lag? // chart google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data = new google.visualization.DataTable(); data.addColumn('date', 'Year'); data.addColumn('number', 'Msgs'); data.addRow([new Date('2023-08-25'), 5]) var options = { hAxis: { title: 'Time' }, vAxis: { title: 'Number of Messages' }, backgroundColor: '#2C2F33' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } Thank you. -
Django - Any ideas on how to mimic the way Amazon handles their progress bar? [closed]
I have tried using Bootstap, which can produce a strait line. But I like the way Amazon's progress bar has node bubbles that show a checkmark in them when it reaches a certain point. I have considered just using a preset image, but if I have like 6 nodes minimum, with multiple options that those nodes can be, that can be a lot of image files. And if something were to change in the flow, it could potentially be a lot of work to update these files. So looking for an alternative -
Getting invalid_grant when trying to exchange tokens using Django-oauth-toolkit
I am trying to use the django-oauth-toolkit but continually hitting an invalid_grant error. I believe I have followed the instructions at https://django-oauth-toolkit.readthedocs.io/en/latest/getting_started.html#oauth2-authorization-grants to the letter. I have created the following script to test with (mostly just extracted the code mentioned in the above page: import random import string import base64 import hashlib code_verifier = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(random.randint(43, 128))) code_verifier = base64.urlsafe_b64encode(code_verifier.encode('utf-8')) code_challenge = hashlib.sha256(code_verifier).digest() code_challenge = base64.urlsafe_b64encode(code_challenge).decode('utf-8').replace('=', '') client_id = input("Enter client id: ") client_secret = input("Enter client secret: ") redirect_url = input("Enter callback url: ") print(f'vist http://127.0.0.1:8000/o/authorize/?response_type=code&code_challenge={code_challenge}&code_challenge_method=S256&client_id={client_id}&redirect_uri={redirect_url}') code = input("Enter code: ") print(f'enter: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id={client_id}" -d "client_secret={client_secret}" -d "code={code}" -d "code_verifier={code_verifier}" -d "redirect_uri={redirect_url}" -d "grant_type=authorization_code"') The following shows the output (I haven't redacted the details, they are only temporary): (venv) (base) peter@Peters-MacBook-Air Intra-Site % python api_test.py Enter client id: sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N Enter client secret: GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng Enter callback url: https://192.168.1.44/authenticate/callback vist http://127.0.0.1:8000/o/authorize/?response_type=code&code_challenge=WiaJdysQ6aFnmkaO8yztt9kPBGUj-aqZSFVgmWYRBlU&code_challenge_method=S256&client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N&redirect_uri=https://192.168.1.44/authenticate/callback Enter code: hrLeADVEmQF8mDLKJXhAZJRQ2dElV7 enter: curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N" -d "client_secret=GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng" -d "code=hrLeADVEmQF8mDLKJXhAZJRQ2dElV7" -d "code_verifier=b'UDZGREwyR0ZVMjNCTzRBQlFaVlBUQk9TWkVRUDlCQzFSUTY1MkFNMUUzRTVCRVBNNlkwR0k4UEtGMUhaVVlTVkQ0QVowMzJUR0xLTDQ1U0VNOEtaWVcxT0tP'" -d "redirect_uri=https://192.168.1.44/authenticate/callback" -d "grant_type=authorization_code" (venv) (base) peter@Peters-MacBook-Air Intra-Site % curl -X POST -H "Cache-Control: no-cache" -H "Content-Type: application/x-www-form-urlencoded" "http://127.0.0.1:8000/o/token/" -d "client_id=sJ3ijzbmdogfBZPfhkF6hOqifPuPSKKpOnN8hq1N" -d "client_secret=GnXNWqw7t1OwPRbOWTmDXKiuaqeJ7LRMhY9g2CWe00f3QrHLvx6aDKjGf5eF1t6QPkD1YO8BR43HNmzCjZYBW81FIjTng7QnVypzshMljEJRGTj5N7r8giwjKIiXyVng" … -
Query child objects through parent model - Django
Is it possible to query all child objects through parent model and eventually get the subclass of every element in the queryset. models.py class employee(models.model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) def __str__(self): return self.first_name class teacher(employee): school=models.CharField(max_length=30) district=models.CharField(max_length=30) subject=models.CharField(max_length=30) class doctor(employee): hospital=models.CharField(max_length=30) specialty=models.CharField(max_length=30) If I make a query to get all employees queryset = employee.objects.all() How to get every employee's subclass without making queries for subclasses. Is the subclass repesented with a field in the parent model -
WebSocket with Django and Expo not working
I am building an expo app that uses Django for backend. For the app I need to use WebSocket. But when I try to connect to the WebSocket on my Django project, I get Not Found: /ws/ [25/Sep/2023 19:34:58] "GET /ws/ HTTP/1.1" 404 2678 This is my Expo code: const socket = React.useRef(new WebSocket('ws://myIP:8000/ws/')).current; console.log(socket) if (socket) { // Now you can safely work with the WebSocket object } else { console.error('WebSocket is undefined.'); } socket.onmessage = (event) => { console.log(event.data) // Handle incoming messages from the WebSocket server }; socket.onopen = () => { // WebSocket connection opened console.log("opened") }; socket.onclose = (event) => { // WebSocket connection closed }; socket.onerror = (error) => { // Handle WebSocket errors console.log("error") }; This is my Django code: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', 'channels', ] ASGI_APPLICATION = 'API.routing.application' routing.py from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from .consumers import YourWebSocketConsumer from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "API.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( [ path("ws/", YourWebSocketConsumer.as_asgi()), # Add more WebSocket consumers and paths as needed ] ), }) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class YourWebSocketConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async … -
Migrating an application with subdomains to a single URL
I currently have an application that uses django-tenants with subdomains for each tenant (tenant1.domain.com, tenant2.domain.com...) It uses individual authentication, the auth models are in the schemas So my question is: Is it possible to migrate to a single URL model both for authentication and navigation? I tried many solutions, some managed to authenticate my user, but none managed to make me navigate in a tenant using a "schema-free" URL In short none maintained/created a session -
'InnerDoc' object has no attribute 'pk'
I'm encountering an issue with Elasticsearch-dsl when trying to use a custom serializer with Django REST framework. The error message I'm getting is: 'InnerDoc' object has no attribute 'pk' This error originates in the line serializer = self.serializer_class(results, many=True) from the following code snippet in my PaginatedElasticSearchAPIView: class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression.""" def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute() print(f'Found {response.hits.total.value} hit(s) for query: "{query}"') results = self.paginate_queryset(response, request, view=self) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) except Exception as e: return HttpResponse(e, status=500) I've checked my serializer, and it seems to have the primary key ("id") defined correctly: class OfficeSerializer(serializers.ModelSerializer): # ... class Meta: model = Office fields = [ "id", # ... ] My Elasticsearch document, defined as OfficeDocument, also appears to have the primary key ("id") defined correctly: @registry.register_document class OfficeDocument(Document): # ... class Django: model = Office fields = [ "id", # ... ] Despite this, I was still encountering the "'InnerDoc' object has no attribute 'pk'" error. Then I recreated all models without explicitly setting ids and removed the ids references … -
Using a Custom Django FilterSet and OrderingFilter at the Same Time Breaks My FilterSet
So I have MyFilterSet and CustomOrderingFilter both working perfectly by themselves but when I try to put both into the view at the same time the FilterSet breaks. I've removed the unnecessary business logic from the functions and just included the parts that matter. I tried to put the OrderingFilter inside the FilterSet (to no avail). (There are no errors generated. I'm using Django 1.14, Python 2.7.17 and PostgreSQL 10.23 and it will be near impossible to change those versions at the moment but if changing is the answer I'd like to know that too.) in filters.py: class MyFilterSet(FilterSet): id = filters.NumberFilter(name='id', lookup_expr='exact') class Meta: model = TheModel fields = list() exclude = [] class CustomOrderingFilter(OrderingFilter): fields_related = { 'vendor': { 'data_type': 'text', 'loc': 'thing__vendor',}, } def get_ordering(self, request, queryset, view): param = request.query_params.get(self.ordering_param) if param: return param return self.get_default_ordering(view) def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering in self.fields_related.keys(): return queryset.order_by(ordering) return queryset in views.py class getMyListAPIView(generics.ListAPIView): serializer_class = MySerializer filter_class = MyFilterSet filter_backends = [CustomOrderingFilter] def get_queryset(self): models = TheModel.objects return models -
How to implement connection requests in a room? [closed]
There is a room that can create any user, and he will automatically become its administrator. There may be people in this room who have entered the room code in a specific field. Now the user connects immediately, but I need that after sending the room code, the administrator sitting in the room receives a connection request (relatively speaking, block with the name of the person connecting and the “accept” and “reject” buttons). If the administrator accepts the connection, the user will be in the room, otherwise not. How to do it? Websockets? If yes, can you provide more details? Or maybe there is another way to implement all this? -
Why cant I add a new page to my Django project?
I am trying to add another page to my Django project. At first the problem was that the tutorial I was using was asking to use url so i switched it to re_path but it is still not working and giving me many errors. Right now my urls.py looks like this: from django.contrib import admin from django.urls import path, re_path, include from myapp import views urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^hello/$', include (views.hello)), ] However I keep getting an error that says "File "C:\Program Files\Python311\Lib\site-packages\django\urls\resolvers.py", line 725, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<function hello at 0x000001C657C0F2E0>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import." Amonge other errors for files I have not edited yet. -
Tuples in Django models
I want to write the whole word on the website when entering the product information by entering the first letter of the status field. But here it receives the information correctly, but only displays the first letter on the web page. class Product(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default = True) def __str__(self): return self.get_status_display() This is one of the ways to display this field. <a><a>Status: </a>{{ product.status }}</a><br> -
Connect SQL Server in Django Socker
Outside of Docker, my app works well, and I can connect to two SQL Server databases, on two diferent servers. Inside Docker, I can't connect to the second DB. I ger a timeout error. Can someone help me? settings.py DATABASES = { 'default': { 'ENGINE' : config('DB_ENGINE'), 'NAME' : config('DB_DEFAULT_NAME'), 'USER' : config('DB_DEFAULT_USERNAME'), 'PASSWORD': config('DB_DEFAULT_PASS'), 'HOST' : config('DB_HOST_DEFAULT'), 'PORT' : '', 'OPTIONS': { 'driver': config('DATABASE_DRIVER'), }, }, 'otherbd': { 'ENGINE' : 'mssql', 'NAME' : 'serverbd', 'USER' : 'user', 'PASSWORD': 'pw', 'HOST' : '192.168.1.165', 'PORT' : '63649', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } views.py def ordens_e_ensaques(request): try: second_db = connections['otherbd'] cursor = second_db.cursor() # Consulta para obter as ordens cursor.execute("SELECT * FROM Ordens WHERE ORD_Estado = '1'") print('Consulta SQL de Ordens executada com sucesso!') resultados_ordens = cursor.fetchall() # Consulta para obter os ensaques cursor.execute("SELECT * FROM OrdensEnsaqueActivas") print('Consulta SQL de Ensaques executada com sucesso!') resultados_ensaques = cursor.fetchall() context = { 'resultados_ordens': resultados_ordens, 'resultados_ensaques': resultados_ensaques } return render(request, 'pages/producoes.html', context) except Exception as e: print("Erro ao conectar ao banco de dados: ", e) return HttpResponse("Erro ao conectar ao banco de dados: " + str(e)) -
Implementation of binary tree in django
i am planing to implement binary tree for recommendation where a user can enroll any number of user but i want to keep all the user in binary tree A / \ B c / \ / \ D E F G how can i store this data in database i have tried creating model class Tremodel(models.Model): refered_by = foreign key user left = foreign key user right = foreign key user how can i query 15 level from there where A is the root but for the B/C tree start from it and B/C is the root where tree can go up to any level i just need to calculate up to 15 level in its branch i tried creating the model i have shown above but i am totally confused how to query it` -
Fast Refresh not happening using React js and Django
Im very new to react js and Django and i want to experiment how the screen changes whenever i save the codes. But currently whenever i do the changes, i need to press the refresh button on the browser manually to check the changes. After a lot of research i found the way to automatically do that is via Fast Refresh. I have tried a lot of things for it to work using the links below but none have worked so far. https://dev.to/thestl/react-fast-refresh-in-django-react-kn7 Development server of create-react-app does not auto refresh I am using webpack 5.88.2, babel/core 7.22.20,react 18.2.0 Please let me know how i can do this. Thanks -
How can I integrate djangocms-link in Ckeditor
I would like to use the functionality of the djangocms-link Plugin within the Ckeditor suche that I can add any and numerous links to my text. So far I have only found this feature. But this does not provide the flexibility I need (to add multiple links in various positions. Thanks a lot -
Customizing Permissions and Groups models in Django
I want to modify the Permissions and Group models from django.contrib.auth. I have extended them but am unable to understand how to use these extended models in my project. I had researched about it again and again but could not find the solution. Can any one help me? I had to add two extra fields in Permission model and 4 additional fields in Group model. I had extended both models but when I replace the permissions attribute of Group class it gives error that local fields cannot replace existing. Further, I cannot use add/contribute to original class methods as it is dangerous to replace original files and is not a good programming practice too. Is there any way to change permissions in Group model. Secondly, how can I use these new models in User model? -
How to differentiate created objects and updated objects in Django bulk_create?
I am using bulk_create to create objects in one query. I set update_conflicts to True to update permission level if the record already exists. bulk_create returns the created and updated objects. How can I separate the created object and updated ones? class UserPermission(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='permissions') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='permissions') permission_level = models.SmallIntegerField(default=1) class Meta: unique_together = ('project', 'user') permissions = UserPermission.objects.bulk_create( user_permissions, update_conflicts=True, update_fields=['permission_level'], unique_fields=['project', 'user'], ) -
Receiving Sendgrid Inbound Email webhook attachments as strings (not files)
I'm receiving multiple inbound email webhook requests from Sendgrid (a Django/DRF application on my side) with attachments that are strings rather than actual files. This results in an error when trying to save the files (because 'str' object has no attribute 'file' when trying to file.read()). It apparently happens to approx. 5-10% of all inbound emails and seems to only happen with image files (JPGs, GIFs etc), I did not encounter a PDF file passed this way. Before saving the files I iterate over attachments-info keys to get a list of attachments, here's an example result [ '����\x00\x10JFIF\x00\x01\x01\x01\x00`\x00`\x00\x00��\x10�Exif\x00\x00MM\x00*\x00\x00\x00\x08\x00\x04\x01;\x00\x02\x00\x00\x00\r\x00\x00\x08J�i\x00\x04\x00\x00\x00\x01\x00\x00\x08X��\x00\x01\x00\x00\x00\x1a\x00\x00\x10��\x1c\x00\x07\x00\x00\x08\x0c\x00\x00\x00>\x00\x00\x00\x00\x1c�\x00\x00\x00\x08\x00..., <InMemoryUploadedFile: 40896630.pdf (application/octet-stream)> ] What exactly is this string? Why does that happen? How can I decode it (assuming all I have is the original file name and content type) -
"cannot cast type bigint to uuid" while changing db from sqLite3 to PostgressSql
So here is my Pet model and PetAttachmentImage model as well, in case if it can give any extra info. The problem is that I created my whole backend on Django using default engine (sqlite3) and now I need to deploy it on a cloud, in my case its neonDb - which uses postgres as engine. When I'm trying to migrate my data from sqlite3 on my local storage to postgress on neonDb I get this error - psycopg2.errors.CannotCoerce: cannot cast type bigint to uuid So I've done my research and found similar problem even here on StackOverflow,however it's solution doesn't work in my case, and I don't understand why. Also I use uuid as my primary key, I created id only to make it explicit about the fact that I don't want to use it, and to alter it with my custom one if it's somehow still exists by default. class Pet(models.Model): id = models.BigIntegerField(blank=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, blank=False, null=False) name = models.CharField(max_length=150, default="Unnamed") animal = models.CharField(max_length=150, default="") breed = models.CharField(max_length=150, default="") location = models.CharField(max_length=150, blank=True, null=True) image = models.ImageField(upload_to='images/', default='images/pet.png', blank=True, null=True) description = models.TextField(max_length=1000, blank=True, null=True) info = models.TextField(max_length=1000, blank=True, null=True) def __str__(self): return f"{self.animal} …