Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'RefreshToken' object has no attribute 'blacklist_after'
I am working on a django project. I am using a custom user model (not using django's Abstract User or anything) during Verify OTP i am using if not user.refresh_token or RefreshToken(user.refresh_token).blacklist_after: refresh = RefreshToken.for_user(user) user.refresh_token = str(refresh) user.save() else: refresh = RefreshToken(user.refresh_token) access_token = str(refresh.access_token) and I am getting the error: AttributeError: 'RefreshToken' object has no attribute 'blacklist_after' My Question is that is there anyway that if the RefreshToken is expired in the database, make a new one and store it in the User Object by using user.save() ?? i tried the following code if not user.refresh_token or RefreshToken(user.refresh_token).blacklist_after: refresh = RefreshToken.for_user(user) user.refresh_token = str(refresh) user.save() else: refresh = RefreshToken(user.refresh_token) access_token = str(refresh.access_token) i was expecting that if the refresh token is valid, it will make an access token and if invalid or expired it will create a new refresh token and save it in db. but i got attribute error.d -
How to add Chosen Groups or Chosen user permissions in Django Admin Panel
I'm fairly new to the Django Framework so this might be very easy I'm trying to replicate the result picture below enter image description here using this code i was able to add the Available Groups to the panel ('Permissions', { 'fields': ('is_active', 'is_staff','is_superuser','groups','user_permissions',) }), however i wasn't able to find the name of the attribute for either chosen groups or chosen user permissions. I would appreciate it if you could point out the name and a link to the django documentation regarding this below is the picture of the panel i have made so far enter image description here I read the documentation regarding the django admin panel but wasn't able to find the correct name of the attributes. -
Trouble Deleting Items from Cart Using AJAX In Django
I am new in Stack overflow and I am getting problem during deleting product from cart In my cart.html: <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button> This is the delete button I created. Now also I created js for this button so in my cart.js: console.log("Hi"); $(document).on("click", '.delete-item' ,function(){ let this_val=$(this) var _pID=$(this).attr('data-item'); console.log(_pID); $.ajax({ url: '/delete-from-cart', data: { 'id': _pID, }, dataType: 'json', beforeSend: function(){ this_val.hide() }, success: function(response){ this_val.show() $(".cart-items-count").text(response.totalcartitems) $("#cart-list").html(response.data) } }) }) for the js file when i am clicking on the delete button I am getting product ids as output I also created a views for it. So, In my views.py: def delete_item_from_cart(request): product_id=str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data=request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) and then In urls.py: path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"), this is my url Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id you can see this in the … -
GeoDjango: How can I calculate the distance between two points on a linestring?
I have two points with srid 4326 and linestring with srid 4326. I want to calculate the distance between two points on a line string with django geo -
Adding index.FilterField for Page object in Wagtail?
I need to implement a language-specific search in Wagtail, so I modified the default search/views.py like this: def search(request): search_query = request.GET.get("query", None) page = request.GET.get("page", 1) language = request.LANGUAGE_CODE if search_query: search_results = Page.objects.live().filter(locale__language_code=language).search(search_query) The result is an error message: Please add index.FilterField('language_code') to Page.search_fields Adding index.FilterField('language_code') to my classes derived from Page does not work – so how can I add that filter field index to wagtailcore.Page? -
Django translation doesnt work in python code
I have an application with the default language set to RU. My 2nd second language on the page is en. Everything in my HTML templates seem to be working except this part of code If I set the translation to the code below. I will get only english translation, it means even if my page is in russian, i will get english translation of the text below anyway. from django.utils.translation import gettext_lazy as _ def get_country_info(country): country_info = { "Germany": _("Германия - это страна с богатой историей и культурой, расположенная в центре Европы. Она является домом для таких всемирно известных городов, как Берлин, Мюнхен, Гамбург и Кёльн. Германия славится своей архитектурой, музеями, пивом и колбасой."), "USA": _("США - это крупнейшая страна мира по площади и населению. Она расположена в Северной Америке и является ведущим мировым экономическим и культурным центром. США известны своими небоскрёбами, Голливудом, Диснейлендом и Ниагарским водопадом."), "UK": _("Соединённое Королевство - это островное государство, расположенное в Северной Атлантике. Оно включает в себя Англию, Шотландию, Уэльс и Северную Ирландию. Великобритания является родиной английского языка, парламента, Биг-Бена и королевы Елизаветы II."), "Turkey": _("Турция - это страна, расположенная на стыке Европы и Азии. Она известна своими пляжами, древними руинами, мечетями и базарами. … -
MySQLdb installation issue on Mac. Required for MySQL connectivity with Django
I am creating a Django project on Mac. I want to use MySQL for database. I am trying to install MySQLdb which gives the following error: (djangodev) $ pip3 install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip (108 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [8 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/9z/lf5bsw2929j34m5g6g9qcfqm0000gn/T/pip-install-5qv449ur/mysql-python_191252dd91f14deab09b6860c8c503d9/setup.py", line 13, in <module> from setup_posix import get_config File "/private/var/folders/9z/lf5bsw2929j34m5g6g9qcfqm0000gn/T/pip-install-5qv449ur/mysql-python_191252dd91f14deab09b6860c8c503d9/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
Redirect URI mismatch error with LinkedIn OAuth in Django Allauth on localhost
I am developing a LinkedIn sign-in feature for my Django application using Django Allauth. Everything seems to be configured correctly, and authentication works fine up until the point where LinkedIn attempts to redirect back to my application. I'm working on localhost and I'm receiving an error stating "The redirect_uri does not match the registered value" after attempting to authenticate with LinkedIn. I'm using http://127.0.0.1:8000/accounts/linkedin/login/callback/ as my redirect URI during tests in my local environment. Question: Could anyone provide some guidance or help on this matter? Does LinkedIn allow redirect URIs to localhost for development testing, or is there something else I'm missing here? Ensuring the redirect URI in my LinkedIn application matches exactly with what I'm using in my local environment. Checking for any typos or mismatches in the URL scheme, port, path, or query parameters between my Django application configuration and the LinkedIn application. Attempting to use both localhost and 127.0.0.1 to make sure the issue isn’t with the hostname resolution. What I expected: I expected LinkedIn to successfully redirect to my local Django app and complete the authentication process. -
Issues with sending emails through Outlook using the Win32 library in Django
I'm using Win32 for sending emails on my website. In general, the emails are sent and reach the recipient, but the problem is that the recipient does not change. Initially, when I started this project, I used a single test email to use in different scenarios. This email was "email1@outlook.com". Later, I added another email for another user named User 2 with their own email "email2@outlook.com". The problem is that the recipient does not change. I specifically select that my recipient is "email2@outlook.com", but I always receive all emails at "email1@outlook.com". mail = outlook.CreateItem(0) mail.SentOnBehalfOfName = 'xxxxxxxx@outlook.com' mail.To = admin_email mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO' mail.BodyFormat = 2 html_body = f""" <html> <body style="font-family: 'Arial', sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;"> <div style="max-width: 600px; margin: 20px auto; background-color: #ffffff; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);"> <h1 style="color: #333; margin-bottom: 10px;">Nueva solicitud de pruebas de laboratorio de {full_name}</h1> <p style="color: #555; margin-bottom: 20px;">El usuario {full_name} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}. A continuación, se detallan más información y enlaces:</p> <ul style="list-style-type: none; padding: 0;"> <li><strong>Cliente:</strong> {customer}</li> <li><strong>Usuario:</strong> … -
Python & Django web app button click not working
I had a web app developed by another person who is no longer willing to help with bugs. I have some experience, but not enough apparently to fix this issue. In the web app, there is a button that does nothing when clicked. It should save user information to a database. I do not understand how the click event ties back to possibly the views.py file. In my templates/add-inventory.html I see: <a href="{% url 'crm:inventory' %}" class="btn btn-light rounded-pill me-1"> Cancel </a> <button type="submit" class="btn btn-success rounded-pill"> Save </button> The save button is not doing anything. I see in the views.py: @login_required(login_url='crm:login') @permission_required("crm.add_inventory", raise_exception=True) def addInventory(request): form = InventoryForm() staff = User.objects.all().order_by('first_name') vendor_form = VendorForm() if request.method == 'POST': form = InventoryForm(request.POST) if form.is_valid(): inventory_instance = form.save() if not request.POST.get('vendor'): vendor_form = VendorForm(request.POST) if vendor_form.is_valid(): vendor = vendor_form.save(commit=False) vendor.added_by = request.user vendor.save() inventory_instance.vendor = vendor inventory_instance.save() stocks = request.POST.getlist('stock') for i in range(len(staff)): if int(stocks[i]) > 0: InventoryStock.objects.create( inventory = inventory_instance, user = staff[i], stock = stocks[i] ) messages.success(request, 'Item added successfully') return redirect('crm:inventory') How does the button call the code in views.py? Any help is appreciated. I downloaded all files locally and am using VS Code to debug, but … -
Login and authentication with Django REST framework
I would like help from someone who has more experience with the Django REST framework, to tell me if the login and authentication system I created follows the right framework standards I'm in doubt whether or not Django's login() function should be used in some part of my code, in the client views I want to avoid any direct access to the server, so I do all the logic involving the database in the microservice views, in my "UserLoginAPI" microservice view, should I use the login(request, user) function to log in the user? I saw in some discussions that I should replace login() with update_last_login(None, user) and that's what I did but I'm not sure if it's right I would also like to know if my authentication middleware is correct, both to ignore public views and to check the token and update the user in the session I don't have a lot of experience and I would appreciate it if you could tell me if my code is following the right standards or if there is something I can improve, a certain problem that I can avoid. My login flow is: The HTML form, through a POST request, sends the … -
Changin beheaviour of django-two-factor-auth package
I have being using django-two-factor-auth package and it was really simple to set up. Unfortunately my boss wants to do some changes which more advanced for my junior level. Firstly, we are working in a type of browser dashboard web app and so all users needs to authenticate before logging in. So the first view needs to be the login. Secondly, i was asked that if the user hasnt enabled the two-factor qr code, the authentication needs to redirect the user to the set up view to enable it. So users wont be able to use the app unless they have the 2FA enabled. How can i achieve this? I tried to dig into the documentation but im feelling too lost right now and i would appreciate some insight on the matter. Thank you all. I tried looking into the documentation but got lost on it. Then i tried to see if i can change the package code but couldnt find it. Also tried to add a path with name 'login' but it doesnt work. -
I am looking for experiences with AI Application devlopment companies from India? [closed]
How Can identify whether an Off-shore AI Development company for example from India is a serious and competent partner for my AI Application development project? Any Experiences? Thank you in advance! Because the web is full such companies, but it is difficult to evaluate them and seprate good from bad and serious and scams! -
Making changes in the Django models VS. making changes directly on the database vs
This question is motivated by another question I posted yesterday where the migrations I have applied are not altering the database tables. So, my only solution to do that change is to alter the database directly through SQL commands. Specifically, I want to allow nulls in a particular table field. Are there any pitfalls I should be aware of before doing that change directly on the PostGreSQL database? -
How to add custom js for select in Wagtail choice block
My goal is to have select (dropdowns) handled by custom-select js library for blocks in Wagtail Stream Field. As it is quite easy to add for normal fields when event DOMContentLoaded is triggered. But is there any event or hook for adding a block to StreamField? I tried even calling my function in html template for block. But it seems to be called too early because styles are not applied to selects in this html. this is my .js (typescript) const initColorChoosers = () => { const colorChoosers = Array.from(document.querySelectorAll('.color-chooser select')) as HTMLSelectElement[]; colorChoosers.forEach((chooser) => { if (!chooser.hasAttribute('custom')) { chooser.setAttribute("custom", "true") new CustomSelect(chooser, { customOptionClass: 'option--hero-glow-color' }) } }) } document.addEventListener("DOMContentLoaded", function (event) { window.myfuncs.initColorChoosers = () => initColorChoosers(); }); and my color chooser: class Colors(blocks.ChoiceBlock): choices = [ ('color1', 'color1'), ('color2', 'color2'), ('color2', 'color2'), ] required = False, class Meta: form_classname = 'color-chooser' icon = 'copy' and block template at the end contains: <script> window.myfuncs.initColorChoosers() </script> And it works.. but for already added blocks not for the current one. So if I add a block which contains ColorChooser, it won't apply logic from custom-select but when I add another one, for the first one changes will be applied. -
Django. "dictionary changed size during iteration" while not changing anything
I think I am going insane here. I am trying to iterate over a dictionary containing lists. This is my code: (Yes i know this is not enough to accomplish what I am trying to do, but I have shaved the code down to the minimum while still causing the problem): {% for wc in response %} <tr> <td>{{ response.wc }}</td> </tr> {% endfor %} But i get this error "dictionary changed size during iteration" As anybody with half a brain can see, I am very much not changing ANYTHING in the dict of lists. I am thinking of a hacky solution, just pass another list of of the keys to the template, which I can use to iterate over the list, like: {%for key in keys%} response.key. This just seems like the wrong way to do it. -
Django: annotate query of one model with count of different non-related model which is filtered by a field of first model
Long title in short : I have a complex annotate query to work with. Example Models: class FirstModel(models.Model): master_tag = models.CharField() ... other fields class SecondModel(models.Model): ref_name = models.CharField() I want to fetch all objects from FirstModel with count of all objects from SecondModel if ref_name of this objects are same as master_tag of FirstModel object. What i tried: I tried using annotate with Subquery and OuterRef but can not get this to work as getting constant errors. from django.db.models import OuterRef, Subquery, Count sub_query = Subquery( SecondModel.objects.filter(ref_name=OuterRef("master_tag")).values_list("pk", flat=True) ) FirstModel.objects.annotate(sm_count=Count(sub_query)) This gave me error : "django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression" I tried lots of other things one of which is putting ".count()" at the end of subquery but that causes another error as count tries to evaluate query eagerly and fails due to OuterRef. So is there a way to fetch a query like this with the count annotation ? Any stupid mistakes i made in writing above query ? -
"matching query does not exist" when creating an object
I have: class GoogleSignIn(APIView): def post(self, request): settings = request.settings code = request.data['code'] # Verify the OAuth code with Google try: google_user_info = verify_user(code) except Exception as e: print(str(e)) return Response({'error': 'Failed to verify with Google.'}) email = google_user_info['email'] picture = google_user_info['picture'] try: user = User.objects.get(email=email) user_info = UserInfo.objects.get(user=user) except User.DoesNotExist: first_name = google_user_info['given_name'] user = User.objects.create_user( email = email, username = email, first_name = first_name, last_name = google_user_info['family_name'], password=None) user_info = UserInfo.objects.create( user = user, credits = request.settings.INITIAL_CREDITS, expiry = compute_credits_expiry( num_days=settings.FREE_CREDITS_EXPIRY_IN_DAYS)) The last statement (that is, creating the UserInfo object in the exception handler) produces an exception: accounts.models.UserInfo.DoesNotExist: UserInfo matching query does not exist. What does it mean? The complete output: Internal Server Error: /accounts/google-sign-in/ Traceback (most recent call last): File "/mnt/c/Dropbox/Parnasa/Web/wherewasit/backend/accounts/views.py", line 129, in post user = User.objects.get(email=email) File "/usr/lib/python3/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File … -
how can I do django custom authorization? I need admin auth by username and password and users by only phone number
How can I realize this code? admin use only admin panel for authorization users doesn't use admin panel therefore they use only app for authorization with OTP phonenumber. from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifier for authentication instead of usernames. """ # oddiy userlar yaratish uchun def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Users must have an email address')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user # supper user yaratish uchun def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) I have manager class and I looked similar code. from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None I looked some video in youtube I didn't find. -
Django: collectstatic is not collecting static files
I found a github proyect. Copied it locally, but running collecstatic does not copy files to staticfiles folder. Why? If I do the full path search: python manage.py findstatic D:\web_proyects\imprenta_gallito\static\css\home.css I get error: django.core.exceptions.SuspiciousFileOperation: The joined path (D:\web_proyects\imprenta_gallito\static\css\home.css) is located outside of the base path component (D:\virtual_envs\imprenta_gallito\Lib\site-packages\django\contrib\admin\static) settings.py: import os import os import secrets from pathlib import Path import dj_database_url from decouple import config # SITE_ROOT = root() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get( "SECRET_KEY", default=secrets.token_urlsafe(nbytes=64), ) #DEBUG = config('DEBUG', default=False, cast=bool) # The `DYNO` env var is set on Heroku CI, but it's not a real Heroku app, so we have to # also explicitly exclude CI: # https://devcenter.heroku.com/articles/heroku-ci#immutable-environment-variables IS_HEROKU_APP = "DYNO" in os.environ and not "CI" in os.environ # SECURITY WARNING: don't run with debug turned on in production! if not IS_HEROKU_APP: DEBUG = True # On Heroku, it's safe to use a wildcard for `ALLOWED_HOSTS``, since the Heroku router performs # validation of the Host header in the incoming HTTP request. On other platforms … -
How to fix Django regualr expression Problem
Django Rest Framework after User registration sends out an Email for the new User to verify the EMail adress. The link attached is like https://my_domain.com/api/verify_email/?token=ddfddjrf....fddkfjdjh my api.urls.py file looks like: api.urls.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^verify_email/(?P<token>[\w.-]+)/',views.verify_email, name="verify_email"), [ and in project urls.py ... path('api/', include("api.urls")), ... When I try to run that link I get: Page not found (404) The current path api/verify_email/, didn't match any of these. I can see a URL pattern from the URL.conf: Django tried these URL patterns,in this order. ... api/ ^verify_email/(?P[\w.-]+)/ [name='verify_email'] ... I hope somebody can help because I can't find a solution somewhere .... And I tried several things to fix it. But without any success. Thank's a lot. Greetings RR -
Django filter in other model without foreign key
I have two different models: class AggUii(Model): year = models.IntegerField(blank=True, null=True) month = models.CharField(max_length=2, blank=True, null=True) country = models.CharField(max_length=7, blank=True, null=True) service = models.CharField(max_length=16, blank=True, null=True) doc_id = models.CharField(max_length=100, blank=True, null=True) counts = models.IntegerField(blank=True, null=True) data_type = models.CharField(max_length=200, blank=True, null=True) section_type = models.CharField(max_length=200, blank=True, null=True) yop = models.CharField(db_column='YOP', max_length=4, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'agg_uii' class HierarchieIndexDocid(Model): ancestor = models.CharField(max_length=255) descendant_docid = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'hierarchie_index_docid' As you can see, these tables aren't connected by a Foreign Key. Is there any way, I can rebuild this MySQL statement in Django ORM? The meta_id is passed as a parameter. SELECT agg_uii.year, SUM(agg_uii.counts) FROM agg_uii,hierarchie_index_doc_id WHERE (agg_uii.doc_id=hierarchie_index_doc_id.descendant_docid and hierarchie_index_docid.ancestor="meta_id") GROUP BY agg_uii.year; Thank you! -
Getting errors in installing redux-devtools-extension in react project
I am getting errors while installing redux-devtools-extension uisng npm command in react-redux-django project. -
Prefetch related n+1 problem with django. How can i solve it?
I have three Models named 'Route', 'Place', 'PlaceImage'. class Route(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=False, blank=False) day = models.IntegerField(null=False, blank=False) order = models.IntegerField(null=False, blank=False) class Place(models.Model): name = models.CharField(null=False, blank=False) class PlaceImage(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=False, blank=False) image = models.ImageField(null=False, blank=False) I want to display routes and place image based on Route Model. Original code was... # views.py response_obj = (Route.objects.filter(day=day).prefetch_related("place__image").order_by('order')) serializer = RouteSerializer(response_obj, many=True, context={'request': request}) # Part of RouteSerializer in serializers.py placeImage = serializers.SerializerMethodField("get_placeImage_prefetch_related") def get_placeImage_prefetch_related(self, group): request = self.context.get('request') image = group.place.image return request.build_absolute_uri(image.first().image.url) And I have N+1 Query at getting place image like this (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 80 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(80,); alias=default (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 79 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(79,); alias=default (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 78 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(78,); alias=default How can I solve this n+1 problem? In views.py, I tried prefetch_related(Prefetch('place__image', queryset=PlaceImage.objects.all().only('image'))) but error occurred. AttributeError: 'PlaceImage' object has no attribute '_add_hints' -
data transfer into sql
from django.shortcuts import render import json from .models import MyModel import os def display(request): json_file_path = os.path.join(os.path.dirname(__file__), '..', '..', './jsondata.json') try: with open(json_file_path, 'r') as f: data = json.load(f) for item in data: my_model_instance = MyModel(end_year=item['end_year'], intensity=item['intensity'], sector=item['sector'], topic=item['topic'], insight=item['insight'], url=item['url'], region=item['region'], start_year=item['start_year'], impact=item['impact'], added=item['added'], published=item['published'], country=item['country'], relevance=item['relevance'], pestle=item['pestle'], source=item['source'], title=item['title'], likelihood=item['likelihood']) my_model_instance.save() except FileNotFoundError: data = [] template_name = 'display' return render(request, template_name, {'data': data}) i am trying to transfer the data from json into sql using django