Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM query with IN + LIKE
Lets suppose the following model: class Person(models.Model): name = models.CharField(null=False) ... I know that I can filter Persons with a name that contains the letter a using Person.objects.filter(name__contains='a'). And I know that I can filter Persons with name is in a list using Person.objects.filter(name__in=['John Doe', 'Mary Jane']). Its possible ( or, whats the performative way ) to do the two things using just one filter ? I know that I can do 2 queries (maybe more) and fetch the data. But in my current case, I have a method on my view called get_filters that returns a Q object that will be used in get_queryset method. So I need to implement this inside a Q object and fetching only 1 query. Its possible ? -
Is it possible to use django-parler with static model classes
I am trying to migrate from django-hvad to django-parler for translation in a django app I am working on. After replacing django-hvad with django-parler in the app when I run it I get this error: raise TypeError("Can't create TranslatedFieldsModel for abstract class {0}".format(shared_model.__name__)) TypeError: Can't create TranslatedFieldsModel for abstract class MyClass I have read the documentation https://django-parler.readthedocs.io/en/latest/api/parler.models.html and have seen how TranslatedField is explained and used in an example there but I don't want to use this approach because it won't work in my case. How can I use django-parler with my abstract class, is it possible? If it's not possible is there an alternative package that works with static model classes I can use in place of django-parler? -
Django queryset return DurationField value in seconds
I have two models: Post, Comment (Comment has FK relation to Post). Now I want to return all posts with theirs "response time". I get this response time in timedelta format. Can I receive it in seconds instead? I tried ExtractSecond but it is not what I'm looking for: base_posts_queryset.annotate( min_commnet_date=Min("comment_set__date_created"), response_time=ExpressionWrapper(F("min_commnet_date") - F("date_created"), output_field=DurationField()), response_time_in_sec=ExtractSecond(F("response_time")) ).filter(response_time__isnull=False).values("response_time", "response_time_in_sec") This code returns following objects: {'response_time': datetime.timedelta(days=11, seconds=74024, microseconds=920107), 'response_time_in_sec': 44} What I want to achieve is basically call .seconds for each item in result queryset. I could do this in python, but mb it could be done on db level? -
What is the best practice / best place for enabling/disabling site-wide admin functionality
Situation: I have a Django project with multiple applications, each of which have one or more models. I have added custom admin actions for some of the models and got the "Delete selected" action for free. I want to disable this for all models in all applications. I'm aware how to disable the "Delete selected" action for the whole project, i.e. by using admin.site.disable_action('delete_selected') but I simply don't know where to put it. I've put it in the admin.py file of one application and that definitely works, but that bugs me as (in my opinion) a site-wide change, also affecting other applications, shouldn't be caused by the admin configuration of a single application. I was hoping to find some way to have a "project-level" admin.py file, but it seems that only fully customizing the AdminSite will do the trick, which I think is a bit overkill if I only want to disable the "delete_selected" action globally. Any thoughts? -
Django ModuleNotFoundError. Everything is fine, but i am unable to run a server
I have started going through "Django for Beginners" book and copied code example from 2nd chapter, but it doesnt work because of the ModuleNotFoundError ModuleNotFoundError: No module named 'pages.apps.PagesConfigdjango'; 'pages.apps' is not a package My app urls seem to be fine from django.urls import path from .views import homePageView urlpatterns = [ path('', homePageView, name = 'home') ] As well as INSTALLED_APPS 'pages.apps.PagesConfig' What is the possible problem? -
Django Formset POST not registering in views.py
I have a View that creates multiple formsets and displays them in a template, from the customers list page I have an Ajax call that passes the Selected Customer ID through to this view for intial data display. Here is the views: views.py def mod_customer(request): print(request.body) try: params = json.loads(request.body) selection = params['cst_id'] obj = AppCustomerCst.objects.get(id_cst=selection) instance = get_object_or_404(AppCustomerCst, id_cst=selection) form = CustomerMaintForm(request.POST or None, instance=instance) ContactFormSet = modelformset_factory(AppContactCnt, can_delete=True, fields=( 'name_cnt', 'phone_cnt', 'email_cnt', 'note_cnt', 'receives_emails_cnt')) formset = ContactFormSet(queryset=AppContactCnt.objects.filter(idcst_cnt=selection), prefix='contact') tpList = AppCustomerTpRel.objects.filter(idcst_rel=selection).select_related('idcst_rel', 'idtrp_rel').values( 'idtrp_rel__id_trp', 'idtrp_rel__tpid_trp', 'idtrp_rel__name_trp', 'sender_id_rel', 'category_rel', 'cust_vendor_rel') TPFormSet = formset_factory(TPListForm, can_delete=True) tp_formset = TPFormSet(initial=tpList, prefix='tp') doc_list = DocData.objects.document_list(selection) DocFormSet = formset_factory(DocumentListForm) # print(formset) DocFormSet = formset_factory(DocumentListForm) doc_formset = DocFormSet(initial=doc_list, prefix='doc') context = {'form': form, 'formset': formset, 'tp_formset': tp_formset, 'doc_formset': doc_formset} print(form.errors) # context = {'form': form} return render(request, 'mod_customer.html', context=context) except ValueError: print(request.POST) if '_edit' in request.POST: # This works with Customer Name, but would prefer to use Customer ID -- Need to figure that out. cust_name = request.POST['name_cst'] instance = get_object_or_404(AppCustomerCst, name_cst=cust_name) form = CustomerMaintForm(request.POST, instance=instance) cntct_instance = get_list_or_404(AppContactCnt, idcst_cnt=selection) # print(cntct_instance) contact_form = ContactsForm(request.POST or None, instance=cntct_instance) if form.is_valid(): # print('made it to valid point') form.save() return render(request, 'customers.html') else: context = {'form': form, 'contact_form': … -
How can i use django template based package in jinja2
I'm developing website based on django. In my project, there are some third party package which is based on django templates engine, now is there any to integrate this package with jinja templates -
Error with Docker Compose Django and PostgreSql
I got a problem when i create any object with my on Admin show me this error: LINE 1: SELECT (1) AS "a" FROM "license_portal_client" WHERE I'm new with docker-compose so i appreciate if anyone knows how to solve it. Here is My DockerFile: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ Here is my docker-compose.yml: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python license_portal/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db My Database settings.py and i add my app on installed apps: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } And here is my models.py test: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) And the last one admin.py from django.contrib import admin from license_portal.models import Person admin.site.register(Person) -
Specify a Django model field as a query expression
How do I specify that a model field is implemented by a database expression instead of a table column? I have this model: class URLProbe(models.Model): url = models.CharField(max_length=MAX_URL_LENGTH) timestamp = models.DateTimeField(auto_now_add=True) status_code = models.SmallIntegerField(null=True, blank=True) # The HTTP status code error = models.TextField(blank=True) # stores non-HTTP errors, e.g. connection failures def ok(self): return self.status_code == 200 ok.boolean = True ok.admin_order_field = Case( When(status_code__exact=200, then=True), default=False, output_field=BooleanField() ) def errmsg(self): if self.ok(): return '' if self.status_code is not None: return f'Error: HTTP status {self.status_code}' return self.error errmsg.admin_order_field = Case( When(status_code__exact=200, then=Value('')), When(status_code__isnull=False, then=Concat(Value('Error: HTTP status '), 'status_code')), default='error', output_field=CharField() ) The model represents an attempt to retrieve an url, recording whether the HTTP call succeeded or what the error was. The ok and errmsg fields here are implemented as methods, but I want to be able to use them in the Django admin as regular fields (sort/filter on them) and to sort and/or filter on them in queries. That is possible, but I need to define the query expression multiple times: in an admin_order_field, in a Django admin custom filter, and in queries where I want to use them. So that duplicates a lot of code, both for the multiple expressions … -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' error html form
I'm getting this error while trying to run a html django program . File "C:\Users\ankit\project\detri\calc\views.py", line 22, in speedup m1 = int(request.POST.get('mi1')) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' function ```def speedup(request): #line22 m1 = int(request.POST.get('mi1')) m3 = int(request.POST.get('mi3')) #calculation stuff return render(request, 'Speed Result.html', {"days": T})``` html form ```<form action= "{%url 'sp'%}" method="POST" > {% csrf_token %} <label for="mi1"> Enter 1 minute :</label> <br><input type="number" id="mi1" name="mi1" ><br> <label for="mi3"> Enter 3 minute :</label> <br><input type="number" id="mi3" name="mi3" ><br> </html>``` -
SlideShow of Images with title having Different time durations in django
how i can make Slide Show of Images with title having Different time durations in django and set url and images from my database for example : {% for photo in Photos%} <label id="label_main_app"> <a href=" {{ photo.page_url }} " style="color:#033457" > <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{ photo.get_image }}" alt="no image found !" height="160" width="165" > </a> <a href=" {{ photo.page_url }} " style="color:#033457" > {{ photo.name }} </a><br><br> <p id="p_size_first_page"> {{ photo.app_contect}} <br> <br> <a href=" {{ photo.page_url }} " type="button" class="btn btn-dark"><big> See More </big> </a> </p> </label> {% endfor %} -
Heroku has issues in deploying Django Channels app for development purposes
I have been on this issue for some hours now, can someone help please. Thank You for your time, I appreciate it. I have been trying to publish this DRF app that is using Django Channels for websocket support. I want to use this only for further development for now and hence thought of deploying it to Heroku. But Heroku keeps giving me this Push Rejected Error. in settings.py : # Development CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } in routing.py : # imports from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat application = ProtocolTypeRouter({ # (http->django views is added by default) 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) channel_routing = {} In asgi.py : import django import os from channels.routing import get_default_application from channels.layers import get_channel_layer from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppBackend.settings') # application = get_asgi_application() django.setup() application = get_default_application() channel_layer = get_channel_layer() (Heroku) Procfile : web: gunicorn app_xxx.wsgi --log-file - web2: daphne AppBackend.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 chatworker: python manage.py runworker --settings=AppBackend.settings.production -v2 (Heroku) requirements.txt : django gunicorn django-heroku channels djangorestframework (Heroku) runtime.txt : python-3.7.8 (Heroku) Error Message : (django-env) D:\Code\Projects\social-media-app-backend\AppBackend>git push heroku master Enumerating objects: … -
Using string parameter on django template
I'm having some trouble passing a string parameter to a href from withing a template. I have the following url pattern path('current_observations/<str:mongo_id>', views.specific_observation, name='specific_observation') At current_observations I have several objects which have the mongo ID as an attribute. The idea is to send this id to the new url. I tried doing the following withoud success <a href="{% url 'VM_OrchestratorApp:specific_observation' resource.id|stringformat:s %}"> {{ resource.TITLE }} </a> Which returns Failed to lookup for key [s] Tried doing the following also <a href="{% url 'VM_OrchestratorApp:specific_observation' resource.id|stringformat:'s' %}"> {{ resource.TITLE }} </a> But in this case the argument is not being recognized at all. NOTE: By doing <a href="{% url 'VM_OrchestratorApp:specific_observation' 'hello' %}"> {{ resource.TITLE }} </a> I get redirected to current_observations/hello which is the expected behaviour. Any idea on what could be going wrong with the string formatting? -
How to change list of foreign keys for a formset generated by django inlineformset_factory?
I have the following models: class Organization(models.Model): name = models.CharField(max_length=255) owner = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return f"{self.name}" class Category(models.Model): name = models.CharField(max_length=255) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='categories') class Meta: verbose_name = "category" verbose_name_plural = "categories" order_with_respect_to = 'organization' def __str__(self): return self.name class Product(models.Model): brand = models.CharField(max_length=255, blank=True, null=True) name = models.CharField(max_length=255) code = models.CharField(max_length=255) sale_price = models.DecimalField(decimal_places=2, max_digits=12) stock = models.DecimalField(decimal_places=2, max_digits=12) organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='products') category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='producs', null=True, blank=True) class Meta: order_with_respect_to = 'organization' I want an inline formset where the user can add products, but I want to show only the categories that are registered to the current user's organization(accessible by request.user.organization) Right now, this is how the formset is set up: def addProducts(request): ProductFormSet = inlineformset_factory(Organization, Product, exclude=('organization',), extra=5) organization = request.user.organization if request.method == "POST": formset = ProductFormSet(request.POST, instance=organization, queryset=Product.objects.none()) else: formset = ProductFormSet( instance=organization, queryset=Product.objects.none()) context = {"forms": formset} return render(request, "products/product_form.html", context=context) But, as you can probably guess, the select field is showing all categories, not just the one's that have the same organization. How do I pass Category.objects.filter(organization=organization) to the select field? -
How to add/update/remove value in existing values list in redis cache using django
I am storing data in redis as below: key: "fruitList" values: [{"a": "apple", "id": 1}, {"b": "banana", "id": 2}, {"m": "mango", "id": 3}] to add following data, I used conn = cache.client.get_client() conn.lpush(key, *values) Now I want to update/remove some element of a value eg. removing {"b": "banana", "id": 2} from values. I have huge list of values. How would I do that. Please help -
Can't retrieve multiple results sets from a stored procedure using django.db.backends.mysql
I'm using django.db.backends.mysql, NOT mysql.connector.django, and I can't get nextset() to work for retrieving multiple result sets from my stored procedure. I suspect that this is a limitation of my setup (I am using Django 2.2.5 with Python 3.7.6), but I can't find confirmation of that. If this is a limitation, my option might be to switch to using mysql.connector.django, which I know will retrieve the records using stored_results() in that specific case, but won't work for the site in general because I think it only supports Python 2.7. My question is: Does anyone know a solution to this issue using my particular setup and keeping django.db.backends.mysql?? I know that this code works (using mysql.connector.django and stored_results()): import mysql.connector def execute_sql(sql_statement, params): conn = mysql.connector.connect(user=settings.DATABASES['default']['USER'], password=settings.DATABASES['default']['PASSWORD'], host=settings.DATABASES['default']['HOST'], database=settings.DATABASES['default']['NAME']) cursor = conn.cursor() cursor.callproc(sql_statement, params) for result in cursor.stored_results(): print(result.fetchall()) I'd like an alternative using django.db.backends.mysql with Python 3.7.6. -
AttributeError: 'NoneType' object has no attribute 'lower'. for django-comments-dab app
I want to use django-comments-dab but I meet this Error, AttributeError: 'NoneType' object has no attribute 'lower'. Request Method: GET Request URL: http://127.0.0.1:8000/2020/9/6/test4 Django Version: 3.1.1 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'lower' Exception Location: D:\amirblog\venv\lib\site-packages\comment\utils.py, line 26, in get_model_obj Python Executable: D:\amirblog\venv\Scripts\python.exe utils.py def get_model_obj(app_name, model_name, model_id): content_type = ContentType.objects.get(app_label=app_name, model=model_name.lower()) model_object = content_type.get_object_for_this_type(id=model_id) return model_object -
Add new record if record exists
I Have a Form where id is hidden field from a model UserFileUploadModel. when I submit the form I save this info to other Model DecryptRequestModel. But here the id used is from UserFileUploadModel, So when i submit the form second time I get error, <ul class="errorlist"><li>id<ul class="errorlist"><li>Decrypt request model with this Id already exists.</li></ul></li></ul> So how can I, Let Django handle the id's for DecryptRequestModel, which will get incremented with each submission. OR Directly update the previous entry, where only one field will change. HTML Form:- <form method="post" action="{% url 'decrypt' %}" enctype="multipart/form-data"> {% csrf_token %} {% for i in objects %} <input type="hidden" name="id" value="{{i.id}}" readonly> # ID from other table <input type="text" name="email" value="{{i.filename}}" readonly> <input type="hidden" name="algorithms" value="{{i.algorithms}}"> {% if i.algorithms == 'BLOWFISH' or i.algorithms == 'AES-256' %} <input type="text" name="key" required="True" placeholder="Enter the Secret Key"> {% else %} <input type="file" name="private_key" required/> {% endif %} <input type="submit" id="redirect" name="decrypt" value="Download"> {% endfor %} </form> View.py :- def DecryptFile(request): if 'isloggedin' in request.session: if request.method == 'POST': id = request.POST.get('id') # instance = DecryptRequestModel.objects.get(id=id) form = DecryptRequestForm(request.POST,request.FILES) if form.is_valid(): algorithm = form.cleaned_data['algorithms'] print(algorithm) form.save() Models: class DecryptRequestModel(models.Model): id = models.IntegerField(primary_key=True) file_name = models.CharField(max_length=200) algorithms = models.CharField(max_length=200) … -
Django Rest Framework pagination and filtering
Hi guys i am trying to make filtering with pagination but i cannot get the result i want. This is my function in views.py. class OyunlarList(generics.ListAPIView): # queryset = Oyunlar.objects.all() pagination_class = StandardPagesPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['categories__name', 'platform'] # serializer_class = OyunlarSerializer def get_queryset(self): queryset=Oyunlar.objects.all() oyunlar=OyunlarSerializer.setup_eager_loading(queryset) return oyunlar def get(self,request,*args,**kwargs): queryset = self.get_queryset() serializer=OyunlarSerializer(queryset,many=True) page=self.paginate_queryset(serializer.data) return self.get_paginated_response(page) This is my pagination class. class StandardPagesPagination(PageNumberPagination): page_size = 10 And this is the json i got but when i write localhost/api/games?platform=pc or localhost/api/games?categories=Action it is not working. { "count": 18105, "next": "http://127.0.0.1:8000/api/oyunlar?categories__name=&page=2&platform=pc", "previous": null, "results": [ { "game_id": 3, "title": "The Savior's Gang", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP3729-CUSA23817_00-THESAVIORSGANG00/1599234859000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [], "release_date": null }, { "game_id": 8, "title": "Spellbreak", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP0795-CUSA18527_00-SPELLBREAK000000/1599612713000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [], "release_date": null }, { "game_id": 11, "title": "Marvel's Avengers", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP0082-CUSA14030_00-BASEGAME0001SIEE/1599653581000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [], "release_date": null }, { "game_id": 24, "title": "The Suicide of Rachel Foster", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP8923-CUSA19152_00-DAEEUTSORF000001/1599610166000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [ { "category_id": 2, "name": "Casual" }, { "category_id": 5, "name": "İndie" }, { "category_id": 8, "name": "Adventure" } ], "release_date": "2020-09-09" }, { "game_id": 25, "title": "Takotan", "platform": "ps4", "image": "https://store.playstation.com/store/api/chihiro/00_09_000/container/TR/en/999/EP2005-CUSA24716_00-TKTN000000000000/1599610166000/image?w=240&h=240&bg_color=000000&opacity=100&_version=00_09_000", "categories": [ { "category_id": 1, "name": "Action" }, { "category_id": 12, "name": "Arcade" … -
elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fc1cad35390>:
I have this in my docker-compose.yml elastic: image: docker.elastic.co/elasticsearch/elasticsearch:7.5.1 ports: - 9260:9200 environment: http.host: 0.0.0.0 transport.host: 127.0.0.1 volumes: - ./config/elastic/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml - elasticsearch:/usr/share/elasticsearch/data and in my staging.py ELASTICSEARCH_DSL={ 'default': { 'hosts': '127.0.0.1:9260' }, } in my jenkins when it tries to deploy to staging, it fails with the following error elasticsearch.exceptions.ConnectionError: ConnectionError(<urllib3.connection.HTTPConnection object at 0x7fc1cad35390>: Failed to establish a new connection: [Errno 111] Connection refused) caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7fc1cad35390>: Failed to establish a new connection: [Errno 111] Connection refused) I got the same error when I tried to run my test scripts in my local with python manage.py test In my settings/test.py I replaced ELASTICSEARCH_DSL={ 'default': { 'hosts': 'elastic:9200' }, } with ELASTICSEARCH_DSL={ 'default': { 'hosts': 'elastic:9260' }, } and the error was gone. Any help will be greatly appreciated. Thank you in advance. -
What exactly is "is_paginated" ? Django Documentation
I've been learning Django for the past couple of months and have found out that the documentation is not very good, or maybe I don't know how to use, but in many occasions I find myself doubtful when looking where every thing comes from. As long as I know, is_paginated is a boolean in the context that returns True if the results are paginated, I found this information here: https://docs.djangoproject.com/en/3.1/ref/class-based-views/mixins-multiple-object/ But in that link from the documentation says it is from the Multiple Object Mixin, and in a Django youtube tuorial I've seen he uses it within a generic class-based DetaiView template, so I've tried to look in the documentation for it and I could not find anything so satisfice my curiosity, maybe I'm not seeing something but I don't like just copying code without knowing where exactly it comes from and what does it do. -
i was heroku run python manage.py migrate but programmingerror is continue
enter image description hereenter image description hereenter image description hereJiQ.png 내가 생각하기에 아무런 문제도 없어야 한다. 나는 migrate도 진행했으며, sqlmigrate, showmigrations로 확인 하였을 때, 정상 적으로 model이 만들어 져 있다는 것도 확인 하였다. 그러나 여전히 heroku는 해당 모델을 찾지 못하고 있다. 어떻게 해야 하는가? -
Getting background-image from GCP storage bucket using django static
I am using django-storages GCP storage backend to serve static to my site from a storage bucket. However, I'm encountering an issue with using the background-image CSS property in conjunction with django's {% static %} tag. In particular, I have the following CSS embedded into the page: <style> .my-background { background-image: url({% static 'foo/bar/example.jpg' %}); } </style> And then if I include the following in the HTML for the page: <div class="my-background"></div> <img src="{% static 'foo/bar/example.jpg' %}"> The <img> tag retrieves the image just fine, but the background-image gets a 403 error with AccessDenied returned from the storage bucket call. I can't figure out why they should be treated differently, any help much appreciated. -
Why django debug tool calculate different CPU time for same functions in different runs?
I am using Django debug tool to calculate the CPU time used by my Django app. Each time I run a particular page in my app, I get different CPU times(difference of 100MS). Why the CPU time fluctuates for the same function in the Django app? -
Get User Details from database in Django
I am working in site which display the details of a contact registered in my app, the error I have is when retrieving the data does not show and cannot find the Ajax request, any help would be appreciated urls.py from django.urls import path from app_2 import views as app2 urlpatterns = [ #app_2 path('user', app2.userPanel), path('get_user_info', app2.getUserInfo, name = 'get_user_info'), ] Script in user.html <script type="text/javascript"> $(document).ready(function(){ $("#users").change(function(e){ e.preventDefault(); var username = $(this).val(); var data = {username}; $.ajax({ type : 'GET', url : "{% url 'get_user_inf' %}", data : data, success : function(response){ $("#user_info table tbody").html(`<tr> <td>${response.user_info.first_name || "-"}</td> <td>${response.user_info.last_name || "-"}</td> <td>${response.user_info.email || "-"}</td> <td>${response.user_info.is_active}</td> <td>${response.user_info.joined}</td> </tr>`) }, error : function(response){ console.log(response) } }) }) }) </script>