Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mypy variable type hints - are they assertions or declarations?
I'm very confused what variable type hints in python (using mypy) actually do. My understanding is that they are useful for asserting the right hand side of assignment actually has the same type as the type hint on the left hand side. But it looks like there is some declaration component as well. I am looking at this function. When I run mypy, I get the following error: def get_organization_from_query_params(query_params: QueryDict) -> Organization: organization_id = query_params.get("organization_id") organization = get_object_or_404(Organization.objects.active(), pk=organization_id) return organization mypy --strict --follow-imports=silent reports: error: Returning Any from function declared to return "Organization" [no-any-return] However, when I add type hints to organization by changing the line into organization: Organization = get_object_or_404(Organization.objects.active(), pk=organization_id), mypy is super happy with no problem. In this case, does mypy just automatically assume that from this point going forward organization is of type Organization? How can it assume that's correct if previously mypy thought get_object_or_404 returns an object of type Any, but I didn't change the functionality at all, and now it believes the fact that get_object_or_404 returns an object of type Organization? Does writing a type hint trigger BOTH an assertion and a declaration?? -
Do I need to put all __pycache__ folders in project folder and apps folders?
I've seen people add a pycache folder in .gitignore. But never seen adding each __pycache__ folder in each folder of the project tho it feels logical to include every __pycache__ folder to .gitignore like so: hello_world/__pycache__ pages/__pycache__ (hello_world is the project name and pages is an app name) Do I need to add all the __pycache__ folders in .gitignore? -
Customizing template while implementing login with Google oauth in Django
When I press the "Login with Google button", I want to go straight to the Google login screen, but I have to press the “Continue” button in the picture below to proceed. Does anyone know a way to eliminate this process...? enter image description here this is my code <div class="social-login"> <h2>또는</h2> <a href="{% provider_login_url 'google' %}">Login with Google button</a> </div> I also changed the settings.py settings as follows. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'preprint', 'users', 'accounts', # 소셜로그인 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ] SITE_ID = 1 LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' SOCIALACCOUNT_AUTO_SIGNUP = True SOCIALACCOUNT_ADAPTER = 'accounts.adapter.MySocialAccountAdapter' -
Yet another questions for missing migration files
I inherited a Django app without the migration files. I suppose the app was developed with an older Django version that the one on the server. The first time python manage.py makemigrations is executed it is successful and produces 0001_initial.py file Migration (python manage.py migrate) or new executions of makemigrations with existent 0001_initial.py fail with a weird error: File "/afat/afatprivate/AFATdashboard/migrations/0001_initial.py", line 223, in Migration bases=(models.Model, AFATdashboard.models.__support), AttributeError: module 'AFATdashboard.models' has no attribute '_Migration__support' I searched for _Migration__support and found nothing useful. The error is the same with an empty database too, so this related answer didn't solve the problem Code from 0001_initial.py, last line is 223 migrations.CreateModel( name='EconCostoCorpiIdrici3', fields=[ ('waterbodycode', models.CharField(blank=True, db_column='waterBodyCode', max_length=255, null=True)), ('waterbodyname', models.CharField(blank=True, db_column='waterBodyName', max_length=255, null=True)), ('numinterventi', models.BigIntegerField(blank=True, db_column='numInterventi', null=True)), ('numinterventiconcosto', models.BigIntegerField(blank=True, db_column='numInterventiConCosto', null=True)), ('costocorpoidrico2227', models.DecimalField(blank=True, db_column='costoCorpoIdrico2227', decimal_places=65535, max_digits=65535, null=True)), ('coperturafinanziariacorpoidrico', models.DecimalField(blank=True, db_column='coperturaFinanziariaCorpoIdrico', decimal_places=65535, max_digits=65535, null=True)), ('percentualecoperturafinanziaria', models.DecimalField(blank=True, db_column='percentualeCoperturaFinanziaria', decimal_places=65535, max_digits=65535, null=True)), ('waterbodycostconfidence', models.DecimalField(blank=True, db_column='waterBodyCostConfidence', decimal_places=65535, max_digits=65535, null=True)), ('costocorpoidrico2227color', models.TextField(blank=True, db_column='costoCorpoIdrico2227Color', null=True)), ('recid', models.TextField(db_column='recId', primary_key=True, serialize=False)), ], options={ 'db_table': 'ECON_costo_corpi_idrici_3', 'managed': False, }, bases=(models.Model, AFATdashboard.models.__support), ), What can I do ? -
Can’t connect PostgreSQL to my Django App in Azure VM
I am build a django app that I am deploying through a CI/CD pipeline into my Azure VM. I already created a PostgreSQL database. When I deploy my docker container in my VM and try to connect to my database I get the following error : django.db.utils.OperationalError: connection to server at “127.0.0.1”, port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Knowing that the that I get the following when running “netstat -an | grep 5432” : enter image description here Can you please help me, I looked for two days in all forums for a solution for this error, but still nothing worked ! Thanks in advance. I am expecting to be able to connect my docker container (django app) with my the VM postgresql database. -
Translating model fields in Django - are choices a valid alternative?
I am trying to figure out the best way to translate model fields in my Django application. After looking at the available libraries (django-modeltranslation, django-modeltrans, etc.) I started thinking: What if I set all the fields that I know will require translation as choices using enums? That way, translations can be handled just like everything else across the application. When creating objects in the Django admin, instead of typing the values I will simply choose them from a dropdown and create one object per choice (or more if there are permutations of multiple fields). This won't be a problem because I already know what the objects will be, and if I ever have to create more I can just add choices. I guess there are some drawbacks: Whenever I need to add a new object, I first need to add the choice to the code and redeploy instead of just doing it from the Django admin diretcly Users won't be able to add their own objects (which is fine as I don't plan to give them that option anyway) I haven't found much online listing this as a valid alternative. Am I missing anything here? -
Django API which has Azure Active Directory Authentication Backend using Postman
I have set up a django project using the django_auth_adfs library to use the Azure Active Directory for the authentication phase. I have set up its API using rest_framework and now, I am trying to send requests to it using Postman. My problem is that if I send a request with or without an access token, my result is nothing but the raw html code of the Microsoft login page. I used this link for generating my access token: https://dev.to/425show/calling-an-azure-ad-secured-api-with-postman-22co I tried different API Permissions for my Azure App such as Azure Active Directory Graph, Microsoft Graph, and one under my own project name which comes from the one I configured as a scope in the Expose an API. Also I wonder if the company should grant access to the api I configured in the Expose an API? -
django.db.utils.IntegrityError: insert or update on table while mi8grating netbox > nautobot using nautobot-netbox-importer
I am trying to Migrate data from Netbox 3.7.4 to Nautobot 2.X using nautobot-netbox-importer. I tried the migration with the netbox-demo.3.7. data and worked fine but with the data I have I have been getting this error > sys.exit(main()) File "/opt/nautobot/lib/python3.10/site-packages/nautobot/core/cli/__init__.py", line 293, in main execute_from_command_line([sys.argv[0], *unparsed_args]) File "/opt/nautobot/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/opt/nautobot/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/opt/nautobot/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/opt/nautobot/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/opt/nautobot/lib/python3.10/site-packages/nautobot_netbox_importer/management/commands/import_netbox.py", line 89, in handle adapter.import_to_nautobot() File "/opt/nautobot/lib/python3.10/site-packages/nautobot_netbox_importer/diffsync/adapters/netbox.py", line 97, in import_to_nautobot self._atomic_import() File "/usr/lib/python3.10/contextlib.py", line 78, in inner with self._recreate_cm(): File "/opt/nautobot/lib/python3.10/site-packages/django/db/transaction.py", line 246, in __exit__ connection.commit() File "/opt/nautobot/lib/python3.10/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/opt/nautobot/lib/python3.10/site-packages/django/db/backends/base/base.py", line 266, in commit self._commit() File "/opt/nautobot/lib/python3.10/site-packages/django/db/backends/base/base.py", line 241, in _commit with self.wrap_database_errors: File "/opt/nautobot/lib/python3.10/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/opt/nautobot/lib/python3.10/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() django.db.utils.IntegrityError: insert or update on table "dcim_device" violates foreign key constraint "dcim_device_primary_ip4_id_2ccd943a_fk_ipam_ipaddress_id" DETAIL: Key (primary_ip4_id)=(some UUID) is not present in table "ipam_ipaddress". I tried multiple things like 1. Dropping constraints in DB 2. Disabling Foreign key Constraints but nothing worked. Can someone please point me to correct direction? -
Airtime/Data via APIs
I have a website that sales data and airtime together with TV subscriptions and electric bill payment. I used third party APIs to send airtime/data of network like MTN,aitel, Glo and Etisalat to users. The problem is their discount is very small and I barely make $5 a month Wich is affecting my site maintenance. I want to know is there is a way I can buy these services directly from these networks and not via third party APIs I used Python (Django) for the sites backend and react js for the frontend -
Query elements by attribute of Foreignkey Relation and also Query Foreign attributes most efficient
There are three models Product: Having an id, a name Storage: Having an id, a name, a color and a branch ProductStorage: Maps each Product to a Storage and has some extra attributes. I want to list all ProductStorages with a specific Storage.branch value grouped by the Storage, displaying storage name and color too. Is it possible to do this in one query? I am new to Django and I am unsure how to do this in the most efficient way. I know that I could query all ProductStorages and filter by branch. Then sort them maybe afterwards by their storages and query the storage-attributes in a second query. But I guess this won't be the best way to do it. -
In Django how to define test database and keep records inserted in test database until cleaned in tearDown method of testcase
I want a test database created for my default database in Django latest version, for that I configured in project settings.py file as below. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', 'TEST': { 'NAME': BASE_DIR / 'test_db.sqlite3', } } } I have a model Topic in my models.py file and have run makemigrtions & migrate cmds to have table in sqlite db. I have created TestTopic class in my app(first_app) tests.py file as below from django.test import TestCase,SimpleTestCase from .models import Topic class TestTopic(TestCase): def setUp(self): Topic.objects.create(top_name='Test topic1') Topic.objects.create(top_name='Test topic2') Topic.objects.create(top_name='Test topic3') def test_create_topic(self): all_topics = Topic.objects.count() self.assertEqual(all_topics, 3) def tearDown(self) -> None: return super().tearDown() I am executing cmd below to run my app(first_app) tests. Passing --keepdb for preserving test_db. py manage.py test first_app --keepdb After this I see test case pass. But when I am checking test_db.sqlite in sqlite db browser app to see test topics I created in test case, I do not see them. I want to have those records in test_db until I clear them manually or in tearDown method of my test case. ( Below is sqlite db browser of test_db.sqlite topics table. -
Django Channels: Connection gets accepted, loads initial messages, but no new messages are being sent via the channel
I have a Django Channels consumer class. The WebSocket connection establishes without any issues, and initial messages are also loaded. However, when I try to send a message, it does not trigger the async_to_sync method and the chat_message function. I have attempted this multiple times. The print statement inside the chat_message function is not working, and although I tried catching exceptions, there are no errors as well. I have checked the channel layer and Redis through the shell, and they are working fine. New messages are created in the backend, and notifications are received, but no message is being sent to the client side. class ChatConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.user = None self.room_group_name = None self.room_code = None def connect(self): self.room_code = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = f'chat_{self.room_code}' self.room = get_object_or_404(ChatRoom, room_code=self.room_code) try: try: self.user = self.scope['user'] except Exception as e: self.user = None if self.user == None: self.close() return # Join room group self.channel_layer.group_add( self.room_group_name, self.channel_name ) self.accept() self.load_initial_messages() except Exception as e: print(str(e)) self.close() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] msg = Message.objects.create(room=self.room, user=self.user.username, message=message,) message_data = { 'roomCode': self.room_code, 'user': msg.user, 'message': msg.message, } try: async_to_sync(self.channel_layer.group_send)( … -
Getting CORS Error for only DELETE Request (Have no issues with PUT, POST and GET) DRF and React project
I have been facing this following error whenever I make the request from my react.js frontend. I am using django DRF on backend and nginx as reverse proxy. Both are deployed in gcp cloud run as different services. Meaning frontend and backend are in different origins, that prompted me to enable the CORS policy. I am fairly new to both of the technologies. Access to XMLHttpRequest at 'https://backend-service/api/employee/' from origin 'https://frontend-service' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The weird part is, it's throwing the above error but the item is getting deleted in the database. My views.py, @api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']) def handle_crud_operations(request, SerializerClass): if not SerializerClass: return Response({'message': 'Invalid serializer specified'}, status=status.HTTP_400_BAD_REQUEST) # GET method to retrieve all objects of the specified model if request.method == 'GET': model_objects = SerializerClass.Meta.model.objects.all() serializer = SerializerClass(model_objects, many=True) return Response({'message': 'Successfully retrieved data', 'data': serializer.data}, status=status.HTTP_200_OK) # POST method to create a new object elif request.method == 'POST': serializer = SerializerClass(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': f'{SerializerClass.Meta.model.__name__} created successfully', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # PUT method to update an object (full update) elif request.method == 'PUT': obj = get_object_or_404(SerializerClass.Meta.model, pk=request.data.get('id')) serializer … -
Django - FOREIGN KEY constraint failed
In this part of the code for syncing an excel sheet to the database: for record in lesson_records: try: date = parser.parse(record['Date']).date() start_time = parser.parse(record['Start Time']).time() end_time = parser.parse(record['End Time']).time() primary_tutor = get_object_or_404(Staff, gmail=record['Primary Tutor Email']) logger.info(primary_tutor) course = get_object_or_404(Course, course_code=record['Course Code']) logger.info(course) lesson, created = Lesson.objects.update_or_create( lesson_code=record['Lesson Code'], defaults={ 'course_code': course, 'date': date, 'start_time': start_time, 'end_time': end_time, 'lesson_no': record['Lesson Number'], 'school': record['School / Customer'], 'teacher': record['Teacher'], 'teacher_contact': record['Teacher Contact'], 'venue': record['Venue'], 'remarks': record['Remark'], 'delivery_format': record['Delivery Format'], 'primary_tutor': primary_tutor } ) logger.info(record['Lesson Code']) except Exception as e: lesson_errors.append(f"Error in Lesson {record['Lesson Code']}: {str(e)}") logger.error(f"Error in {record['Lesson Code']}: {str(e)}") I recieve a Error in [course code]: FOREIGN KEY constraint failed for every single course. The primary_tutor and course are both correctly logged, so both get_object_or_404 succeeded and they both exists in the database, but it still failed the foreign key constraint. This is the model: class Lesson(models.Model): course_code = models.ForeignKey(Course, on_delete=models.CASCADE) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() lesson_no = models.IntegerField() lesson_code = models.CharField(max_length=20, primary_key=True) school = models.CharField(max_length=100) teacher = models.CharField(max_length=10) teacher_contact = models.CharField(max_length=100) teacher_email = models.EmailField(blank=True, null=True) venue = models.CharField(max_length=100) remarks = models.TextField(blank=True, null=True) delivery_format = models.CharField(max_length=10) primary_tutor = models.ForeignKey(Staff, on_delete=models.CASCADE, related_name='primary_tutor') other_tutors = models.ManyToManyField(Staff) calender_id = models.CharField(max_length=100, … -
xhtml2pdf when works with a parsed table or content div breaks <li> numeration
I need to create pdf document with xhtml2pdf. Everything is great with html, but pdf document breaks the numeration while working with tables or parsed div containers. pdf html I've tried to change that block to many divs and the numeration returned, but it didn't look like something I've needed. But when I changed formatting to the way I want, the numeration disappeared again. Can't understand the reason of this behaviour. -
How to catch failed rows during the bulk_create in Django?
I process large CSV, Excel files and save result using Django bulk_create method. But some of rows may have corrupted data and in that case all rows will not be saved to database. Ideally I want to catch failed rows and show users which rows are failed to save. Then users can make decision whether skip failed rows or upload new file. I try to catch failed rows during the bulk_create in Django. -
Stripe payment not going through in production but working in development
I have a django project that I am deploying and have a stripe integration for payments in it. It works perfectly fine locally and goes through but does not work on my linux server. What could be causing this and how can I make the payment work on my deployed version? Lead: The only hit of issue I am getting is that my gunicorn logs show that the /charge/ endpoint that I am using to charge is forbidden, but I'm not sure what is really causing this as this is so bizarre. Thank you so much! Context: I have https, and the code doesnt detect any errors (redirects to success page and stripe doesnt give errors). I just allowed all of the stripe IP's through my firewalls using sudo ufw (the api.stripe.com ones: https://docs.stripe.com/ips). The code is the exact same, the api keys are the same -
Django ModuleNotFoundError in Vercel production
I'm trying to deploy an api on vercel in Django, however when I call my api I get an error that a module does not exist. I don't get this error locally. I've tried several solutions: adding a route to the folder in settings.py, installing modules with build_files.sh. I still have the same problem, even though the files are present in the aborescense of my production project. Here is the link to my github repository: https://github.com/SkyBLUE62/osint_sherlock_api vercel.json { "version": 2, "builds": [ { "src": "api/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "api/wsgi.py" } ] } build_files.sh echo "BUILD START" # create a virtual environment named 'venv' if it doesn't already exist python3.9 -m venv venv # activate the virtual environment source venv/bin/activate # install all deps in the venv pip install -r requirements.txt # collect static files using the Python interpreter from venv python manage.py collectstatic --noinput python manage.py makemigrations python manage.py migrate python manage.py runserver echo "BUILD END" # [optional] Start the application here # python manage.py runserver api/settings.py """ Django settings for api project. Generated by 'django-admin startproject' using Django 3.1.4. … -
Half space in django CKEditor
I am developing a website that requires an advanced text editor for Persian, and I have used CKEditor. When I copy text from Microsoft Word and paste it into CKEditor, it does not paste all the half spaces correctly. For example, if the text of an article has 10 half spaces or somebody may call it semi space, after pasting it into the CKEditor, it might only display 7 half spaces correctly, and the rest are missing. Have you encountered a similar issue? What is your opinion? -
Django reversed for loop slice
I am currently trying to reverse a slice of a list going from 0 to 11 Here is part of index.html <div> {% for i in game.board|slice:"6:12" reversed%} <a href="{% url 'make_move' forloop.counter0 %}" > {{ i }} </a> {% endfor %} </div> Here is what I have in views.py def make_move(request, pit): print(f"Make move called. Pit: {pit}") pit will always print from 0 to 5, when I expect it to print 11, 10, 9, etc It feels that slice and reversed have no effect on i in this case -
How to use <img src ""> in django
I am making a website using django and flowbite tailwind component library i want to add a carousel to my website ` ` in normal websites we use something like <img src="./img.jpg> This is what i had already tried its a response from chatgpt its not working To access an image stored at webdept/home/media/image.jpg in your Django template (webdept/home/template/home/home.html), you need to ensure a few configurations are in place and use the appropriate template tags. Here's how you can do it: Configure MEDIA_URL and MEDIA_ROOT in your settings.py: # settings.py import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Set up your URL patterns to serve media files during development: # urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # Your other URL patterns ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Access the image in your template using the MEDIA_URL context: First, ensure you load the static template tag at the top of your template: {% load static %} Then, you can use the MEDIA_URL to access your image: <img src="{{ MEDIA_URL }}image.jpg" alt="Image Description"> Example home.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Home Page</title> </head> <body> … -
Problem in deploying django app using plesk
I am trying to deploy my django app and i am using plesk as a host. But i have 2 problems In order to reach the website instead of typing mydomain/login i have to type mydomain/templates/login.html The page appears broken as the picture below. I have checked and collected the static files and the urls seem fine. I don't understand what i am missing. I would appreciate a helping hand! Thank you -
postgres.fields.JSONField and models.JSONField
I have a model in some django project it has a JSONField in it. I want to connect to the table of that model from another django project so i copied the model from first django project and move it to second one. The first django project uses from django.contrib.postgres.fields import JSONField but i can't use same JSONField in second django project (because of django version in second project it does not support postgres.field.JSONField). My question is can i use from django.db.models import JSONField in second django project with no errors and connect to the same database? -
why my django save_model not saving manytomany relation
I'm having issues with ManytoMany Relationships that are not saving in a model when I save it (via the admin). i want to auto add title in tags. admin.py def save_model(self, request: Any, obj: Any, form: Any, change: Any) -> None: post = Fa.objects.get(id = obj.id) #return the current post fields for i in post.title.split(' '): try: t = FaTag.objects.get(title = i) post.tag.add(t) except: pass return super(FaAdmin,self).save_model(request, obj, form, change) when i print this line: obj.tag.all() it gives me the queryset that is currect but it wont save anything in database -
'django-admin' is not recognized as an internal or external command, operable program or batch file
Yesterday I installed Python and added it to PATH. Then I created a virtual environment using virtualenv. I then activated the environment and pip-installed django (using pip install django) and started a project by django-admin startproject project_name. Then I moved the virtual environment folder inside the project directory (formerly it was its sibling dirctory). I worked with the project and everything was fine until today when I opened it again. python manage.py runserver still does good but when I use django-admin commands it gives the error in the question title. It's not recognized but yesterday it was when I started the project (I did activate the environment again). The only difference from yesterday is that I upgraded pip. I looked up stackoverflow and it had plenty of questions for my problem but most of them had problem with PATH (which I had configured correctly and didn't have a problem with) or they had used django instead of django-admin or they were on Linux and had problems with sudo (but I'm on Windows 10). What can I do to solve this?