Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is using base.hml in django templates good option?
I know extends base.html file in other html page is good to avoid repetition of same html tags , But is it good when come to page load speed does it increase load time of page ? , is page load time that extends from base.html same as page who does not ? -
Django Model does not exist error When accessing tabel from admin Panel
Ok so I was working on a project locally and then I followed a guide https://www.codingforentrepreneurs.com/blog/deploy-django-to-digitalocean-app-platform in order to deploy on digital ocean and i did successfully, However; When I open the Django admin panel and try to access my tables, some of the tables open up just fine while two other tables give the following error as illustrated.Error 1,Error 2. After hours and hours of searching questions here I reached a conclusion that something is wrong with the migrations. Regardless of how much I tried I failed to make it work. I will provide the Logs maybe it helps you out more. 10.244.3.92 - - [10/Dec/2021:22:08:06 +0000] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 3912 "https://scheduler-live-rcfr9.ondigitalocean.app/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" [scheduler-live] [2021-12-10 22:08:06] Not Found: /static/admin/js/nav_sidebar.js [scheduler-live] [2021-12-10 22:08:06] 10.244.3.92 - - [10/Dec/2021:22:08:06 +0000] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 404 3906 "https://scheduler-live-rcfr9.ondigitalocean.app/admin/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36" [scheduler-live] [2021-12-10 22:08:08] Internal Server Error: /admin/myapi/schedule/ [scheduler-live] [2021-12-10 22:08:08] Traceback (most recent call last): [scheduler-live] [2021-12-10 22:08:08] File "/workspace/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute [scheduler-live] [2021-12-10 22:08:08] return self.cursor.execute(sql, params) [scheduler-live] [2021-12-10 22:08:08] psycopg2.errors.UndefinedColumn: column myapi_schedule.Start_Time does not exist [scheduler-live] [2021-12-10 22:08:08] … -
Dango - How to use "setUpTestData" with TransactionTestCase
I've created a test class, which is a TransactionTestCase and I tried setting up the test data as so test.py class SomeTester(TransactionTestCase): @classmethod def setUpTestData(cls) -> None: cls.some_data = 'stuff" but when I reference self.some_data in test functions it says self.some_data is not defined. Can you not use setUpTestData with TransactionTestCase? This works with TestCase class. -
Initialize field to constant value in django Form
How can I set up a model/form combination so that the field in the model is initialized to a fixed value and there is no form element displayed when the form is presented to the user? I just want to initialize Source.updated = datetime.datetime(2000, 1, 1, 0, 0, 0, 0) each time a new Source is created from a form. The user cannot over-ride this initial default. (Subsequent interaction with the app will cause this field value to change, but it's not just auto_now because I want the initial value to be far in the past.) What I have now is class Source(Model): name = models.CharField(max_length=168, help_text="Source name") link = models.URLField(primary_key=True, help_text="Data source link") type = models.CharField(max_length=64, help_text="Data source type") # TODO: add this field to the model. # have it initialize to 2000-01-01 #updated = models.DateTimeField(help_text="Most recent time this source has been updated") class SourcesForm(forms.ModelForm): class Meta: model = models.Source fields = ['name', 'link', 'type',] # TBD: how to configure the form so that # it initializes the "updated" field with a fixed value # when .save() is called The logic I'm trying to implement is that: we're getting data from a remote source, so I want to know … -
is there a way to fluidly calculating total sales using JS with Django
I'm looking for a way to take the information being entered into a database and not only calculate the overall total for a year but also calculate the total for individual months. I'm using Django and Javascript. The Django View: @login_required def proposal_signed(request): prop = Proposal.objects.all().order_by('proposal_approved_date') return render(request, 'client/proposal_signed.html', { 'prop': prop, }) The HTML and JS: {% extends 'client/base.html' %} {% block content %} <br> <div class="jumbotron jumbotron-fluid"> <div class="container"> <div class="text-center"> <h1 class="display-4"> Sales For Signed Proposals </h1> </div> </div> </div> <head> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> <title></title> </head> <div class="container"> <table id="countit"> <tr> <th><strong>Approval Date:</strong></th> <th><strong>Job Type:</strong></th> <th><strong>Address:</strong> <th><strong>Client:</strong></th> <th><strong>Bid/Job Total:</strong></th> </tr> {% for item in prop %} {% if item.proposal_approved_date %} <tr> <td>{{ item.proposal_approved_date }}</td> <td>{{ item.client.requested_service }}</td> <td>{{ item.client.work_site_address }}</td> <td>{{ item.who_to_bill_name }}</td> <td class="count-me">{{ item.client.invoice_set.get.bill_amount }}</td> </tr> {% endif %} {% endfor %} </table> <script language="javascript" type="text/javascript"> var tds = document.getElementById('countit').getElementsByTagName('td'); var sum = 0; for(var i = 0; i < tds.length; i ++) { if(tds[i].className === 'count-me') { sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML); } } document.getElementById('countit').innerHTML += … -
Django4 + Jinja2 href url not working in template
I can't get simple urls to work in my Jinja2 templates in Django 4. This literally should be the easiest code, but it keeps throwing errors like this: ("Encountered unknown tag 'url'.",) Request Method: GET Request URL: http://127.0.0.1:8000/browse/a/ Django Version: 4.0 Exception Type: TemplateSyntaxError Exception Value: ("Encountered unknown tag 'url'.",) Exception Location: /home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/lib/python3.8/site-packages/django/template/backends/jinja2.py, line 47, in get_template Python Executable: /home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/bin/python Python Version: 3.8.10 Python Path: ['/home/joop/sites/khinsider', '/snap/pycharm-community/261/plugins/python-ce/helpers/pydev', '/home/joop/sites/khinsider', '/snap/pycharm-community/261/plugins/python-ce/helpers/third_party/thriftpy', '/snap/pycharm-community/261/plugins/python-ce/helpers/pydev', '/home/joop/.cache/JetBrains/PyCharmCE2021.3/cythonExtensions', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/joop/.local/share/virtualenvs/khinsider-gSzZqK6P/lib/python3.8/site-packages'] This is the template code: <a href="{% url 'browse' 'a' %}">test</a>. The urls.py path: path('browse/<str:char>/', main.views.browse, name='browse') The settings TEMPLATES config: TEMPLATES = [ { "BACKEND": "django.template.backends.jinja2.Jinja2", "DIRS": ['jinja2'], "APP_DIRS": True, }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I tried all kinda of variations but nothing works. -
Django models & relationship with store products? how to solve relationship?
I have a relationship that makes my website unable to function properly? I have a picture of my debugging situation, do you why it shows the wrong line error? debugging result debugging result 2 from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField # Create your models here. class Customer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True, upload_to='Products/') updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() # to call out the table orderitem in reverse all total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) … -
Django/Ubuntu: Error 1045, "Access denied for user 'www-data'@'localhost' (using password: YES)"
I am trying to test out a Log-In page for a Django site hosted publicly on Apache2 by logging in remotely. However when entering any credentials to test I get the following error: [1045, "Access denied for user 'www-data'@'localhost' (using password: YES)"] I am assuming that this means the www-data Apache2 default user can't access my MySQL table? What would be the best way to allow access safely? -
React working on local machine but not on other local network machine
I am hosting a reactjs project on port 3000 as front end and django project on port 8000 as backend on the same machine. So when rending, reactjs will get data by calling django APIs. I (thought I) had correctly setup CORS headers in Django settings. Both http://localhost:3000/ and http://192.168.86.21:3000/ are working on my local machine. 192.168.86.21 is my LAN IP. But when I access http://192.168.86.21:3000/ on another machine or tablet in my LAN. Only static files are rendered. I inspect the Chrome it shows: " Access to fetch at '..django_ip_port...' from origin '..my_ip_port..' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. " It's really weird. -
django rest api deleting data from db
Whenever I access data using django rest api it gets deleted. Getall seems to work but view detail or update deletes the data. When I create I get a "201 Created" but the information is not stored in db. I am using the django sql_lite db and even with superuser it still gets deleted. I have checked my serializers, models and views for errors. I have to create data directly into the db. I have checked migrations to make sure they were up to date. views.py from django.shortcuts import render from rest_framework import generics from .serializers import RoomListSerializer, RoomDetailSerializer from .models import Room class RoomListAPIView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomListSerializer class RoomRetrieveAPIView(generics.RetrieveAPIView): lookup_field = "id" queryset = Room.objects.all() serializer_class = RoomDetailSerializer class RoomCreateAPIView(generics.CreateAPIView): queryset = Room.objects.all() print(queryset) serializer_class = RoomDetailSerializer class RoomRetrieveUpdateAPIView(generics.RetrieveUpdateAPIView): lookup_field = "id" queryset = Room.objects.all() serializer_class = RoomDetailSerializer class RoomDestroyAPIView(generics.DestroyAPIView): lookup_field = "id" queryset = Room.objects.all() models.py from django.db import models class Room(models.Model): room_name = models.CharField(max_length=200, blank=False) description = models.TextField(blank=True) width = models.CharField(blank=False, default="5", max_length=10) length = models.CharField(blank=False, default="5", max_length=10) def __str__(self): return f"{self.room_name}: {self.width} by {self.length}" serializers.py from rest_framework import serializers from .models import Room from rest_framework.reverse import reverse class RoomListSerializer(serializers.ModelSerializer): absolute = serializers.SerializerMethodField() class … -
can not connect to clearDBmySQL from django
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'tajaratdatabase', 'USER': '', #here I am using my username 'PASSWORD':'', #here I am using my password 'HOST':'us-cdbr-east-04.cleardb.com', 'PORT':'3306', } } I f I use the same credentials on MySQLworkbench my connection is successfully established but if I try to connect from my terminal and run command python manage.py makemigrations I got an error django.db.utils.OperationalError: (1044, "Access denied for user 'bf76.....'@'%' to database 'tajaratdatabase'") how can I remove this error and can make my connection successful -
How to build a demo for a Web Dashboard App in 28 days?
Here is my situation: I need to present a demo of an online dashboard app in beginning of January. Skills: I know some Python (especially the data science frameworks) but have not yet worked with django / flask or other languages than Python. Goal: The app does not have to have many features. Mainly: login and visualisation of data, maybe some filters like date or category. It mainly needs to LOOK really good but can involve some parts being hard-coded. My first approach: I saw bootstrap templates which look good already but is using django with such templates really the most efficient way for only a demo? I guess there is some really nice way which may not even involve extensive coding but still offers some flexibility regarding page elements? Thank you for your advice! -
Trying to write a script to upload files to a django project
I have a django 3.x project where I can upload multiple files and associated form data through the admin pages to a model called Document. However, I need to upload a large number of files, so I wrote a small python script to automate that process. I am having one problem with the script. I can't seem to set the name of the file as it is set when uploaded through the admin page. Here is the script...I had a few problems getting the csrf token working correctly, so there may be some redundant code for that. import requests # Set up the urls to login to the admin pages and access the correct add page URL1='http://localhost:8000/admin/' URL2='http://localhost:8000/admin/login/?next=/admin/' URL3 = 'http://localhost:8090/admin/memorabilia/document/add/' USER='admin' PASSWORD='xxxxxxxxxxxxx' client = requests.session() # Retrieve the CSRF token first client.get(URL1) # sets the cookie csrftoken = client.cookies['csrftoken'] print("csrftoken1=%s" % csrftoken) login_data = dict(username=USER, password=PASSWORD, csrfmiddlewaretoken=csrftoken) r = client.post(URL2, data=login_data, headers={"Referer": "foo"}) r = client.get(URL3) csrftoken = client.cookies['csrftoken'] print("csrftoken2=%s" % csrftoken) cookies = dict(csrftoken= csrftoken) headers = {'X-CSRFToken': csrftoken} file_path = "/media/mark/ea00fd8e-4330-4d76-81d8-8fe7dde2cb95/2017/Memorable/20047/Still Images/Photos/20047_Phillips_Photo_052_002.jpg" data = { "csrfmiddlewaretoken": csrftoken, "documentType_id": '1', "rotation" : '0', "TBD": '350', "Title": "A test title", "Period": "353", "Source Folder": '258', "Decade": "168", "Location": "352", … -
Save sensor data in a Django database
Im doing a Django app that tries to show data taken from an ultrasonic sensor. What I want is to take the distance from the sensor and save it in its Django table. Normally this is done with a form, but i want it to be done in the backend for each sensor object. This is the code that i have for the moment: Ultrasonicsensor.py import time from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger def main(): # Grove - Ultrasonic Ranger connected to port D16 sensor = GroveUltrasonicRanger(16) counter = 10 while (counter < 10): distance = sensor.get_distance() #This is the distance i want to save for each sensor object distance = (float(distance) / 100) print('{:.4f} m'.format(distance)) if distance < 1: print('Cerca') elif 1 <= distance <= 1.9: print('Medio') else: print('Lejos') time.sleep(1) counter = counter + 1 Models.py class UltrasonicSensor(models.Model): name = models.CharField(max_length=50, default="HC-SR04") description = models.TextField() pin = models.IntegerField() distance = models.DecimalField(max_digits=20, decimal_places=4) date = models.DateTimeField(auto_now_add=True) Views.py class uSensorDetailView(DetailView): template_name = 'sensor_detail.html' context_object_name = 'sensor' def get_queryset(self): return UltrasonicSensor.objects.all() -
Getting wrong headers for Traefik ForwardAuth middleware
I've been trying to develop a custom auth thing for Traefik using Django and the ForwardAuth middleware. Unfortunately, I'm having troubles with the provided headers for my application: My auth app has three endpoints: /auth/, which checks whether the user is authenticated. If it is, returns a "OK" with status code 200. If it's not, tries to get the X-Forwarded-Host in order to build a redirect argument using f"?redirect={request.headers['X-Forwarded-Proto']}://{request.headers['X-Forwarded-Host']}" and then redirect to /auth/login/{redirect_url} /auth/login, which renders a form and then authenticates with Django (it uses the same logic as /auth/ for setting up a redirect URL /auth/logout It's exposed at https://auth.my-ip.nip.io, using the following: apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: django-auth spec: entryPoints: - websecure routes: - match: Host(`auth.my-ip.nip.io`) kind: Rule services: - name: django-auth port: 80 tls: secretName: auth.my-ip.nip.io The middleware is configured as follows: apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: django-auth spec: forwardAuth: address: https://auth.my-ip.nip.io:443/auth/ trustForwardHeader: true Finally, I've got an example app exposed and using the django-auth middleware: apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: game-2048 spec: entryPoints: - web - websecure routes: - match: Host(`2048.my-ip.nip.io`) kind: Rule services: - name: game-2048 port: 80 middlewares: - name: django-auth tls: secretName: 2048.my-ip.nip.io But then, when I try to … -
Django deployment with docker - create superuser
I have 3 environments set up and cannot createsuperuser. The way I migrate and runserver now follows the container so I have an entrypoint.sh: #!/bin/sh 1 2 echo "${RTE} Runtime Environment - Running entrypoint." 3 4 if [ "$RTE" = "dev" ]; then 5 6 python manage.py makemigrations --merge 7 python manage.py migrate --noinput 8 python manage.py runserver 0:8000 9 10 python manage.py createsuperuser --username "admin" --email "admin@banl.com" --password "superuser" 11 echo "created superuser" 12 13 elif [ "$RTE" = "test" ]; then 14 15 echo "This is tets." 16 python manage.py makemigrations 17 python manage.py migrate 18 python manage.py runserver 19 20 elif [ "$RTE" = "prod" ]; then 21 22 python manage.py check --deploy 23 python manage.py collectstatic --noinput 24 gunicorn kea_bank.asgi:application -b 0.0.0.0:8080 -k uvicorn.workers.UvicornWorker 25 26 fi lines 10/11 is what I want to make work, I think I have a syntax issue. Originally I wanted the password and username to be variables stored in an env file: 1 RTE=dev 1 POSTGRES_USER=pguser 2 POSTGRES_PASSWORD=pgpassword 3 POSTGRES_DB=devdb 4 DJANGO_SUPERUSER_PASSWORD=superuser 5 DJANGO_SUPERUSER_EMAIL=admin@bank.com 6 DJANGO_SUPERUSER_USERNAME=admin But now I just want it to work, I need to create a superuser account in order to develop. Can anyone spot what's wrong? … -
react-django connectivity issues, 500 internal server errors
I’m working on a project using react as the frontend and Django rest api as backend. Unfortunately, I’m having some issues. Here are the issues I’m facing: From the Django setting.py file, I set the static directory folder to “build” (for css, images and JavaScript) and media folder (for user uploaded files) file to “media” as shown below. But I observed that only the “media” folder shows up in the directory structure and not the “build” folder. PLEASE WHAT COULD BE PREVENTING THE “BUILD” FOLDER FROM SHOWING? STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/medial/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I understand that normally when you run “npm build” and copy the build folder generated from the frontend to replace the one in the Django backend, then you can begin to use “localhost:8000” to access your pages rather than continue to use “localhost:3000”. I did the above, but I wasn’t able to load the pages using “localhost:8000” but instead getting 404 error. PLEASE WHAT COULD BE THE ISSUES? I created some routes (post and get), tested all the routes in postman as well as the browser, and they (routes) are all working perfectly. … -
Django - Translate variable before rendering to template
I am currently using Django Translation in order to switch between en/es and viceversa. And I know that I can use {%blocktrans%} in order to translate a variable inside a template. The problem is that I have no access to the template of this particular feature where I need to translate several words. How do I translate a variable before rendering it into a template? -
Problems to display the Form in the Template using CreateView
What happens is that I am using CreateView and I find it curious that the code works when I put {{form}}, it displays all the fields and saves in the database (everything works very well) but when I break down the values one by one for example: {{form.plates}}, {{form.type}}, it does not send anything to the database and it stays on the same page. Why is that? I just need it broken down clientes-add.html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row mb-3"> <div class="col-md-3"> <div class="mb-3"> <label>Customer type</label> <br> <div class="form-check form-check-inline"> {{ form.tipo }} </div> </div> </div> </div> <div class="row mb-3 only-corp hide-item"> <div class="col-md-12"> <div class="mb-3"> <label>Corporation name</label> {{ form.corporacion }} </div> </div> </div> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> -
Django pasar parametros por url
a través de una etiqueta y href paso parametros por url. Las etiquetas son del navbar y funcionan como filtro el problema esta en que al seleccionar una segunda opción la url no se maxaca y vuelve a insertar la ruta a la view. Esto como se puede solucionar? views.py: def pueblo(request, pueblo): activo = establecimientos.objects.filter(pueblo=pueblo) context = {'establecimientos_objects':activo} return render(request, 'orders/establecimientos.html', context) urls.py: path('pueblo/<str:pueblo>',views.pueblo, name='pueblo'), template: <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="pueblo/opcion1" class="nav-link link-dark" aria-current="page"> opcion1 </a> </li> <li> <a href="pueblo/opcion2" class="nav-link link-dark"> opcion2 </a> </li> <li> <a href="pueblo/opcion3" class="nav-link link-dark"> opcion3 </a> </li> </ul> -
Django background_task results in BrokenPipeError
I'm using django 3.1.4, django-background-tasks 1.2.5. I have a task registered which runs to completion successfully when I perform updateProducts.now() from the shell, but for some reason when it's automatically ran, it results in BrokenPipeError at different parts of the code. Often it refers to a collection not being undefined in a dictionary which is in the constructor of the GClient class. All collections are defined in the GClient class constructor. @background(schedule=timezone.now()) def updateProducts() -> None: client = GClient() db_client = DBClient() total_products = 0 collections = ["collection1", "collection2", "collection3", "collection4"] for collection in collections: products = client.getProductOfCollection(collection) if products is None: continue total_products += len(products) for product in products: db_client.addProduct(product) if "inventoryQuantity" in product and product["inventoryQuantity"] > 0: notify_restock(product["id"], db_client) print(db_client.updateErrors) db_client.updateErrors = {} print(f"Done Updating {total_products} Products") if not Task.objects.filter(verbose_name="Update Products").exists(): updateProducts(verbose_name="Update Products", repeat=7200, repeat_until=None) getProductOfCollection - Performs a GraphQL request for an array of products which can take anywhere between 3secs to 1min to fulfill, it checks periodically whether it's been fulfilled. Once fulfilled, it receives a link with a json to download, it downloads the json, parses it, stores all the products in an array and returns it. -
ERROR code 1452 mysql in windows and but not in linux
I have a django project that creates tables after manage.py migrate. I use some LOAD DATA LOCAL INFILE MySQL queries for both. I have 7 tables. All the first 6 tables are populated the same way in both Linux and Windows. Except for the last table that has some foreign keys in previous ones. Linux MySQL Output Windows MySQL Output Both Windows and Linux tables are in InnoDB and the parent table has exactly the same data. Table information in Linux Table information in Windows Section Table keys in Linux Section Table keys in Windows INSERT INTO `seas_database`.`section_t` (`eSession`,`eDays`,`dYear`,`nSectionNumber`,`nSectionCapacity`,`nEnrolled`,`bIsBlocked`,`tStartTime`,`tEndTime`,`cCoffCode_ID`,`cFaculty_ID`,`cRoom_ID`) VALUES ("Spring","F",2009,1,250,43,0,"14:00","15:30","AAT101","T001","C10210-S"); Proof that AAT101 exists in Windows Yet i get this error in Windows ONLY. Not in Linux. Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`seas_database`.`section_t`, CONSTRAINT `section_t_cCoffCode_ID_ade53504_fk_cooffered` FOREIGN KEY (`cCoffCode_ID`) REFERENCES `coofferedcourse_t` (`cCoffCode_ID`)) Linux MySQL version : mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server - GPL) Windows MySQL version: C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe Ver 8.0.27 for Win64 on x86_64 (MySQL Community Server - GPL) If it helps, the csv for which the LOAD DATA INFILE was ran, it was modified and created by Pandas from an xlsx file. -
how to search table by QR code scanning in django admin
Lookup Records with Qr code scanning in Django how we can add search option by QR scanning in django on the table.i wanna create the table .every item has unique QR code and i wanna search by scanning QR code (using mobile ) and show the matching data can i do in Django admin ??? -
How to Share single App to Django Developer?
I am developing a big application. How to share only single app to a developer. For Example there are 5 developers working on a Project. I want each developer to see only single app. Not complete code. Problem i am facing is with Django ORM. Since we import Django models inside the views. So other apps should be present in Django project to work. Approach which i found → Instead of Django ORM use Sqlalchemy. Here i can give access to specific app to developer. If he require some other table then i give him permission from Postgres to that corresponding table. I am confused in this method. Do big companies like Instagram provide code to every developer? Any blog or any answer is appreciated. -
Is it possible to create related objects on parent creation automatically in Django?
I have a Profile model and NotificationSettings model with OneToOne relation. There is more than one way to create Profile, but NotificationSettings must be created with all of them. I don't want to write same code for every view that creates Profile. So i was hoping that there is some event that i can track so NotificationSettings would be created automatically. Something similar to RubyOnRails' after_create callback