Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a one-time code and a specific time
I want to generate a random code for user registration on the website And the time to use the random code is 3 minutes my class: class Otp(models.Model): token = models.CharField(max_length=200, null=True) phone_number = models.CharField(max_length=11) code = models.SmallIntegerField() expiration_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.phone_number my view: class CheckOtpView(View): def get(self, request): form = CheckOtp() return render(request, 'userlogin/verify-phone-number.html', {'register': form}) def post(self, request): token = request.GET.get('token') form = CheckOtp(request.POST) if form.is_valid(): cd = form.cleaned_data if Otp.objects.filter(code=cd['code'], token=token).exists(): otp = Otp.objects.get(token=token) user, is_create = User.objects.get_or_create(phone=otp.phone_number) login(request, user) otp.delete() next_page = request.GET.get('next') if next_page: return redirect(next_page) return redirect('userlogin:welcome') return render(request, 'userlogin/verify-phone-number.html', {'register': form}) my form: class CheckOtp(forms.Form): code = forms.CharField(widget=forms.TextInput(attrs={'class': 'number-email-input'}), validators=[validators.MaxLengthValidator(5), validators.MinLengthValidator(5)]) -
AWS ECS with Django + Python + Alpine produce Segmentation Fault
we are currently having trouble with Alpine Linux, since the Update to Version>=17. It seems that since alpine17 the openssl library in alpine was updated to openssl3. The problem is that we have our Django application, which is built via Dockerfile does not work with alpine>=17 on AWS ECS anymore. We are installing additional dependencies, such as: gcc, build-base, bind-tools, mysql-client, mariadb-dev, postgresql14-client, xmlsec, git, util-linux, curl-dev, openssl, libffi-dev Then we tested different images, e.g. python3.11.9-alpine3.20,python3.11.9-alpine3.18, python3.11.3-alpine3.17, python3.12.4-alpine3.18 etc. It worked with python3.11.3-alpine3.16. The strange thing is: it does actually work if we built and deploy the django application locally via docker-compose and use python3.11.9-alpine3.20 for example. But if we build the containers (nginx, django, worker, beat) via git-ci and deploy them on AWS ECS with Fargate or EC2 as launch types, it gives those errors. The log in the django-container simply states: !!! uWSGI process 35 got Segmentation Fault !!! Then the worker process is terminated. This error arises everytime a connection to django, to nginx or to the loadbalancer is done. Locally we also see the output: 485BA4DBE17F0000:error:0A000126:SSL routines:ssl3_read_n:unexpected eof while reading:ssl/record/rec_layer_s3.c:322: ssl_client: SSL_connect We assume that there might be some incompatibility between the new openssl3, the openssl … -
How to add a template using {% include %} tag, by comparing which user is logged in, on django?
My asset_list html is like this <div class="right"> <div class="search-container"> <input type="text" id="searchInput" placeholder="Search by AssetName..." aria-label="Search"> <button class="add-button" aria-label="Add Asset" id="addUserButton"><i class="fas fa-plus"></i> Add</button> </div> login database is like this , with roles admin and user class UserDetails(models.Model): username = models.CharField(max_length=100, unique=True) password = models.CharField(max_length=100) # Ideally, this should be hashed role = models.CharField(max_length=45) views for asset list def asset_list(request): users = Asset_Table.objects.all() return render(request, 'asset_mng/asset_pro.html', {'users': users}) I have 2 roles Admin and User , when Admin is logged in, I want to show admin side bar and if user is logged in , show user sidebar. {% include 'admin_sidebar.html'%} or {% include 'user_sidebar.html'%} <div class="right"> <div class="search-container"> <input type="text" id="searchInput" placeholder="Search by AssetName..." aria-label="Search"> <button class="add-button" aria-label="Add Asset" id="addUserButton"><i class="fas fa-plus"></i> Add</button> </div> -
Difficulty adding page numbers to printed table using Paged.js without content overflow
I have a table with numerous elements in its , and I'm attempting to add page numbers to each printed page using Paged.js. However, I'm encountering issues where the table content overflows the page or the layout doesn't respect margins properly when using Paged.js. -
Wagtail 5.0 to 5.2
I have a wagtail project and developed in version 5.0. I want to upgrade it to 5.2. But, I'm not fully experienced in Wagtail. I don't know what to do. Please help me. Are there any potential problems or issues in doing so? I never tried. I don't know what to do. -
Vuetify icons not loading properly (Vuetify2 + Django)
I want to embed vuetify into my project, everything is ok with the connection, but the standard vuetify icons are not loading no matter what I do main.js import Vue from 'vue'; import App from './App.vue'; import vuetify from './plugins/vuetify'; import store from './store'; import 'material-design-icons-iconfont/dist/material-design-icons.css' new Vue({ vuetify, store, render: h => h(App) }).$mount('#app'); vuetify.js import Vue from 'vue'; import Vuetify from 'vuetify'; import 'vuetify/dist/vuetify.min.css'; import 'material-design-icons-iconfont/dist/material-design-icons.css' Vue.use(Vuetify); export default new Vuetify({ icons: { iconfont: 'mdi', } }); { "name": "frontend", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build --dest ../static/vue-build-files/main-builds", "lint": "vue-cli-service lint", "dev": "vue-cli-service build --dest ../static/vue-build-files --mode=development --watch" }, "dependencies": { "@mdi/font": "^7.4.47", "core-js": "^3.8.3", "file-loader": "^6.2.0", "material-design-icons-iconfont": "^6.7.0", "vue": "^2.6.14", "vuetify": "^2.7.2", "vuex": "^4.1.0" }, "devDependencies": { "@babel/core": "^7.12.16", "@babel/eslint-parser": "^7.12.16", "@vue/cli-plugin-babel": "~5.0.0", "@vue/cli-plugin-eslint": "~5.0.0", "@vue/cli-service": "~5.0.0", "eslint": "^7.32.0", "eslint-plugin-vue": "^8.0.3", "vue-template-compiler": "^2.6.14" }, "eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/essential", "eslint:recommended" ], "parserOptions": { "parser": "@babel/eslint-parser" }, "rules": {} }, "browserslist": [ "> 1%", "last 2 versions", "not dead" ] } after build/dev/serve command vue start working but there is no standart vuetify icons (example below), how do i manage this problem? after dev/build command … -
django Add a button that creates a new entry field each time it's clicked
I am creating a Recipe app- currently for my form I have Title, Ingredients and Description as text inputs. However I want the user to be able to individually input the ingredients so I can manipulate the inputted data- for instance I want Carrot | 700 | g to come in as three inputs rather than currently where it comes in as text. So my question a) would be how you can horizontally supply form inputs so I can take the three values together side by side a.k.a Ingredient: Input1(textfield) | Input 2(int) | Input 3(dropdown menu) question b) is how you can allow for the user to add an additional field on a button click. I won't know how many ingredients they want to input so by default I would give maybe 5 rows of input and then when they button press it allows them to input a new row? New to Django so appreciate the help and some direction on where I should be going with this- is the easiest solution to use ArrayFields and Javascript? I am more experienced with Python but can figure it out with Javascript if that is the way to go- Here is … -
How can I troubleshoot Django POST request issues despite correct form handling?
I'm having an issue in Django where when I click save on a form, it sends a GET request instead of a POST. I'm not sure why this is happening. Hola, estoy con un problema en django, que cuando apretó guardar en un formulario se envía un GET en lugar de un POST, no entiendo bien por que pasa. subir_noticia.html `{% extends "homepage/base.html" %} {% block title %}Estacion Obrera{% endblock %} {% block content %} \<!-- Formulario para subir una noticia --\> \<form action="" method="POST" enctype="multipart/form-data"\> {% csrf_token %} {{ form.as_p }} \<input type="submit" value="Guardar" class="btn btn-dark"\> \</form\> {% endblock %}` view.py ` def crear_noticia(request): if request.method == 'POST': form = NoticiaForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('ver_noticias_pendietes.html') else: form = NoticiaForm() return render(request, 'administrar_noticias/subir_noticia.html', {'form': form})` terminal `\[15/Jul/2024 23:50:30\] "GET /administrar_noticias/subir_noticia/?busqueda=&csrfmiddlewaretoken=6JWbqf0Dgo1AExf6P27MzAPlXc06iyvFquFaZ4ztBJSsa0Z1qjK1F5BXjV1Wg88A&titulo=Prueba&subtitulo=pruebita&categoria=hjkhk&cuerpo_noticia=asda&pie_de_foto=ada&imagen=WhatsApp+Image+2024-07-08+at+23.23.38+%281%29.jpeg&autor=asda HTTP/1.1" 200 5097 ` urls.py `urlpatterns = \[ path("subir_noticia/", views.crear_noticia, name='subir_noticia'), path("ver_noticias_pendientes/", views.ver_noticias_pendientes, name='ver_noticias_pendientes'), \] ` forms.py `class NoticiaForm(forms.ModelForm): class Meta: model = Noticia fields = \['titulo', 'subtitulo', 'categoria', 'cuerpo_noticia', 'pie_de_foto', 'imagen','autor'\] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)` models.py `class Noticia(models.Model): ESTADOS = ( ('pendiente', 'Pendiente'), ('publicado', 'Publicado'), ('oculto', 'Oculto'), ) categoria = models.CharField(max_length=50, unique=True) titulo = models.CharField(max_length=255, unique=True) subtitulo = models.CharField(max_length=255) cuerpo_noticia = models.TextField() autor = models.CharField(max_length=255) … -
How can I configure Django to search for the Redis backend on the server instead of localhost?
I am working on updating an old Django 2.2 app, and am running into an issue with the connections between Celery, Django, Docker, and Redis. I am using Docker Compose to build the app, and using Celery to schedule tasks with Redis as a backend. Celery schedules emails to be sent and I am able to receive those emails, so I am pretty sure that Celery is properly connected to Redis. When running django.contrib.auth.login(), I run into an error TypeError: Cannot create property 'status' on string 'ConnectionError at /api/auth/registration/register_pro/ Error 99 connecting to localhost:6379. Cannot assign requested address. The error message prints all the config and environment variables of the Django app, and it shows that everywhere in the app redis_url, result_backend, and broker_url are configured as redis://<NO_USERNAME_HERE>:<REDIS_PASSWORD>@redis:6379. This should be the correct URL since it works for Celery, but it doesn't work for Django, which searches for Redis on localhost. I've searched the entire app for any references to localhost, but there are none. I've tried adding and removing env variables, changing the Django config, running Django in development and production environments, building my own Redis docker image, tweaking redis.conf, and so many other suggested fixes on Stackoverflow, GitHub … -
Activate/deactivate filtering in django based on condition
I have a bool and if it is True, I want to filter in my query by some stuff, if not I don't want to filter. At the moment my solution is this: if my_boolean: objects = Class.objects.filter(argument=valuexyz)... else: objects = Class.objects... My real query is much longer. I just used this for simplification. Now my questions is could I do this inline? Like: objects = Class.objects.filter( if my_boolean: argument=valuexyz; else: no_filtering) Is there a way to do it like this somehow? This would save me quite some redundant lines of code. -
Django app on Heroku: email sending failure using AWS SES non-default region
I have two django projects at Heroku and use AWS SES for emails. Requirements: django 4.2.10, django-ses 3.5.2. Domain project-one.com is verified at aws us-east-1. These are my settings: ADMINS = ( ('John Smith', 'jsmith@gmail.com'), ) # Setup email backend. if DEBUG: EMAIL_PORT = 1025 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' else: EMAIL_BACKEND = 'django_ses.SESBackend' SERVER_EMAIL = "Project One <no-reply@project-one.com>" DEFAULT_FROM_EMAIL = "Project One <no-reply@project-one.com>" ACCOUNT_EMAIL_SUBJECT_PREFIX = 'Project One ' Emails are correctly sent from no-reply@project-one.com. This works. Domain project-two.com is verified at aws eu-west-1. These are my settings: ADMINS = ( ('John Smith', 'jsmith@gmail.com'), ) # Setup email backend. if DEBUG: EMAIL_PORT = 1025 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' else: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_REGION_NAME = 'eu-west-1' AWS_SES_REGION_ENDPOINT = 'email.eu-west-1.amazonaws.com' SERVER_EMAIL = "Project Two <no-reply@project-two.com>" DEFAULT_FROM_EMAIL = "Project Two <no-reply@project-two.com>" ACCOUNT_EMAIL_SUBJECT_PREFIX = 'Project Two ' This results in application trying to send emails from admin email jsmith@gmail.com and I get: botocore.errorfactory.MessageRejected: An error occurred (MessageRejected) when calling the SendRawEmail operation: Email address is not verified. The following identities failed the check in region EU-WEST-1: jsmith@gmail.com Any idea why defining AWS_SES_REGION_NAME / ENDPOINT in settings results is admin email being used as sender? If I omit specifying the region, sender is no-reply@project-two.com, but that domain is … -
Django Admin updating tabularinline forms
I have a django modeladmin like so: Class PlanInline(admin.TabularInLine): model = Plan form = PlanForm Class SettingsInline(admin.TabularInLine): model = Settings form = SettingsForm Class StoreAdmin(admin.ModelAdmin): form = StoreForm inlines = (PlanInline, SettingsInline,) .... And I need to pass a value from my Plan form field into my settings form field ss this possible to do from the parent admin form or any method? -
Website giving "an error repeatedly occurred" error in both safari and chrome for iPhone
I am at my wits end. I have tested my website on multiple devices and keep getting mixed results. I can't reliably recreate the issue. The website I am trying to diagnose is clawson-honda-staging.herokuapp.com (this is the staging area that is having the same issue as the main website). When I navigate to this website on some iPhones, can't tell you which one in particular since it happens on 15 pro max, 14 pro max, 14, 13, and 11 so far and not every one, I get "an error repeatedly occurred..." error. I have debugged the website by taking the third party plugins off of the website in a staging area and the problem still occurs. I have broken the website down to just the base html with no css or js, I have tried everything. i have debugged on a mac for hours with multiple devices. Some I could recreate the issue over and over again, some I never get the error. I have not been able to find any patterns or issues that would fix anything reliably. I have taken absolute positioning and translate3d out of the entire application and it's still has the error. Please help!!! -
What's the workaround for Django/PostgreSQL GeneratedField error
When defining a GeneratedFieldedField with PostgreSQL, it is not uncommon to encounter the: django.db.utils.ProgrammingError: generation expression is not immutable. This error is mentioned in the docs about PostgreSQL-specific restriction: ...PostgreSQL requires functions and operators referenced in a generated column to be marked as IMMUTABLE. This error occurs with almost all Func() expressions (with a specified database function). For example: age_func = Func("date_of_birth", function="age") age_years = Func(Value("year"), age_func, function="date_part", output_field=...) This will throw the above error ifage_years is used in GeneratedField expression. Another reproducible example is with Concat() function. If used as is, Concat will also raise the same error, but there is a workaround for it (this custom implementation may not be necessary in Django 5.1). If I was defining these functions in sql, I suppose it wouldn't be a problem marking them as IMMUTABLE. My question is, working with only Django, how do we implement IMMUTABLE functions /expressions? I assume there is a way of passing extra arguments/options that will be used to specify whether the database function will be IMMUTABLE, STABLE, VOLATILE, etc., but I have no clue how to specify this. Perhaps we could subclass Func and override some sql-generating method, but again, I don't know whicker … -
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.