Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Getting Connection refused Error When Creating PDF Using xhtml2pdf
I have deployed a Django app in digitalocean and I getting this error when creating PDF file using xhtml2pdf. In my local environment everything works OK, no errors at all. In anyone has ideas about how to solve, please share those. Thanks in advance [Errno 111] Connection refused Request Method: GET Request URL: Django Version: 2.2.7 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /usr/lib/python3.7/socket.py in create_connection, line 716 Python Executable: /home/eslcrm/bin/python3.7 Python Version: 3.7.6 -
How to fix django settings rest_flex_fields import error?
I have a django app deployed in a docker container and I used drf-flex-fields for performing ?expand on my serializer. I'm looking to enable query optimization as you can see here I updated my settings.py with: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ( 'rest_flex_fields.filter_backends.FlexFieldsFilterBackend', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'PAGE_SIZE': None } In requirements.txt, I included: drf-flex-fields==0.7.5 But when I run docker-compose build and docker-compose up on my app, I get the following error: app_1 | ImportError: Could not import 'rest_flex_fields.filter_backends.FlexFieldsFilterBackend' for API setting 'DEFAULT_FILTER_BACKENDS'. ImportError: cannot import name 'GenericViewSet'. -
Ignoring Django Migrations in pyproject.toml file for Black formatter
I just got Black and Pre-Commit set up for my Django repository. I used the default config for Black from the tutorial I followed and it's been working great, but I am having trouble excluding my migrations files from it. Here is the default configuration I've been using: pyproject.toml [tool.black] line-length = 79 include = '\.pyi?$' exclude = ''' /( \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist )/ ''' I used Regex101.com to make sure that ^.*\b(migrations)\b.*$ matched apps/examples/migrations/test.py. [tool.black] line-length = 79 include = '\.pyi?$' exclude = ''' /( \.git | \.hg | \.mypy_cache | \.tox | \.venv | _build | buck-out | build | dist | ^.*\b(migrations)\b.*$ )/ ''' When I add that regex line to my config file, and run pre-commit run --all-files, it ignores the .git folder but still formats the migrations files. -
Django OperationalError: no such column
I'm trying to read values from an sqlite db I added to my Django project but it doesn't work. I did a test in the Python shell and all it returned was the following error when I tried looking into the data (I entered 'from myapp.models import my_data' followed by 'my_data.objects.all()'): OperationalError: no such column: my_table_name.id This is how my models.py file looks like: class my_data(models.Model): status = models.TextField(db_column='STATUS', blank=True, null=True) name_1 = models.TextField(db_column='NAME_1', blank=True, null=True) name_2 = models.TextField(db_column='NAME_2', blank=True, null=True) dep = models.IntegerField(db_column='DEP', blank=True, null=True) name_reg = models.TextField(db_column='NAME_REG', blank=True, null=True) reg = models.IntegerField(db_column='REG', blank=True, null=True) name_com = models.TextField(db_column='NAME_COM', blank=True, null=True) avgp = models.IntegerField(db_column='AVGP', blank=True, null=True) class Meta: managed = True db_table = 'my_table_name' My settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'my_table_name': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_my_table_name.sqlite3'), } } Also, I performed the 'python manage.py makemigrations' and 'python manage.py migrate' commands. Any idea what I am doing wrong? -
Test discovery fails using DRF APITestCase but not django's TestCase
Using Django Rest Framework's APITestCase class, Visual Studio Code does not discover my unittest tests. I've configured vscode to use unittest and given it the path to my django app. I have toggled between jedi and ms's language server for python. I can run the tests manually, using python manage.py test. If I switch to using Django's provided django.test.TestCase, vscode discovers the tests and creates the adornments. I have also tried rest_framework's two other test cases: APISimpleTestCase, APITransactionTestCase and neither worked. My test class is very simple, essentially the following: from django.test import TestCase # * cannot get vscode to discover tests with this from rest_framework.test import APITestCase service_path = "/api/v0.1/service" # class PathLookupTests(TestCase): class PathLookupTests(APISimpleTestCase): def test_responding(self): uri = "valid_uri" resp = self.client.get(f"{service_path}/?uri={uri}") self.assertEqual(resp.status_code, 200) In the Python Test Log I saw the following traceback once, but cannot repeat it: File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 1123, in setUpClass super().setUpClass() File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 197, in setUpClass cls._add_databases_failures() File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 218, in _add_databases_failures cls.databases = cls._validate_databases() File "/Users/bfalk/miniconda3/envs/web-server-eval/lib/python3.8/site-packages/django/test/testcases.py", line 204, in _validate_databases if alias not in connections: TypeError: argument of type 'ConnectionHandler' is not iterable -
How to allow users In Django to see specific data from same model
I am facing a problem while giving permission to admin users in Django that how to restrict users to see only user specific data from same model. I mean that if 2 user can add data to same model, then how to restrict them to access only that data. -
How to Make Multi Databases in Python Django
What I mean is how to insert a model into another model in Python Django So I am working on a simple project of an online school. we have classes, and in the classes we have subjects and in the subjects we got lessons so how to make a model in python django to add subjects to an individual class only. and add lessons to individual subject in a specific class, this is it, hope understand me well, thanks. -
Nginx and Gunicorn doesn't work (with Django 2.2.4)
I installed and configured Django 2.2.4 with MySQL, Nginx and Gunicorn, it works locally but at the time of seeing it on the web, the page is not visible, I already checked the terminal and there is no error, there is no error in the console of the browser, I used this documentation to configure Nginx and Gunicorn. https://platzi.com/tutoriales/1318-django/3302-instalar-un-proyecto-de-django-en-un-servidor-centos/ This is the image that my server runs the local server but when I deactivate "runserver" it is not published https://drive.google.com/file/d/1NgpapxTuU5VkHgvIqw8I76mg5-3mCGwb/view -
How to use django orm in not django-project?
I have a project with structure like that: . βββ app β βββ data β β βββ ... β β βββ orm β β βββ app_1 β β βββ app_2 β β βββ ... β β βββ orm β β βββ ... β β βββ settings.py β βββ ... βββ ... βββ main.py I want use django orm in my project but i want to have simple way to change Django ORM to any other ORM. Accordingly that i want isolate django project inside my main project. I have some class app.data...DataController which use Models in any cases. And code in main.py use DataController to get or load data from DB, other code works already with data but not with Models directly. To achieve this I wrote this code in app.data.__init__.py: import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.data.orm.orm.settings") import django from django.conf import settings django.setup() Also if i paste that code anywhere else, in main.py for example, that's does not working, django says ImproperlyConfigured: Requested setting INSTALLED_APPS. And then in settings.py i was change dotted pathes to apps like that 'app_1' -> 'app.data.orm.app_1'. But for now i can't use django-commands from manage.py not from project root directory nor from app/data/orm. First, project root β¦ -
Django prompt οΌA server error occurred. Please contact the administrator
I have tried everything I can find, and it has been 6 hours. I have nothing, I just created a django project, and the first time I run, I get an error. I've tried both, reinstall django, python 'encoding format, file encoding format. I am frustrated, please help me.enter image description here -
django admin: how to deal with broken foreign keys in unmanaged table?
I have unmanaged model which looks like this: class Foo(models.Model): parent = models.ForeignKey('Foo', on_delete=models.SET_DEFAULT, default=0) name = models.CharField(max_length=128) class Meta: managed = False db_table = 'foo' Previous developer decided to do a strange thing: add parent_id field which can be either ID of existing Foo row/instance or 0 (instead of just making field nullable). Foo with ID 0 doesn't exist. When I try to display this model in admin panel django doesn't complain: @admin.register(Foo) class FooAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'parent') What django does is just skipping foo's with parent_id == 0. Without parent in list_display all objects will be displayed. When I run something like Foo.objects.filter(parent_id=0) it returns 0 objects, but I know for sure that there are plenty of them in the database. Foo.objects.all() will return only objects with non-zero parent ids. So how should I deal with situation like this (aside from making database migration which might potentially break existing frontend which is not related to django but speaks to existing database)? Or at least how to make model manager return all objects and not just Foo instances with non-zero parent_id? First think that come in mind is to use another model field: parent_id = models.IntegerField(default=0) -
Django - update individual fields of a model
Im working on a django project and I have a user model and each user has a UserProfile. I want to implement a form so that a user can update his profile picture. This is what I have so far: views.py def update_image(request,username): response_data = {} if request.method == 'POST': image = request.POST.get('image') response_data['image'] = image UserProfile.objects.create( image = image ) return JsonResponse(response_data) context = { 'image':image } return render(request, 'userprofile.html', context) forms.py class ProfileUpdateForm(forms.Form): image = forms.ImageField(required=False,label='image') def clean(self): blocked_chars = set(punctuation) cleaned_data = super(ProfileUpdateForm, self).clean() image = cleaned_data.get('image') filename, file_extension = os.path.splitext(image) if not ".jpg" or '.png' in file_extension: raise forms.ValidationError(filename + 'is not an image') return image urls.py url(r'^(?P<username>[\w-]+)/update-image/$', update_image, name='update_image'), index.html <form id="profile_form" class="profile_form" method='POST' enctype="multipart/form-data" form_data="{{ request.user.profile.get_update_image_url }}"> {% csrf_token %} <div class="profile_form_group"> <div class="profile_table"> <div class="utable_row"> <div class="utable_th_1"> <span class="user_detail"> {{ form }}</span> </div> <div class="utable_th_2"> <span class="user_detail"> <input class='profile_img_btn' type="submit" value="Update Image"/> </span> </div> </div> </div> </div> </form> main.js var i_link = $('.profile_form').attr('form_data'); console.log(i_link) $(document).on('submit', '#profile_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: i_link, data:{ image :$('#id_image').val(), csrfmiddlewaretoken :$('input[name=csrfmiddlewaretoken]').val(), action : 'post' }, success:function(json,data,i_link){ console.log("HEY, THIS IS WORKING !" + data + i_link) document.getElementById("profile_form").reset(); }, error : function(xhr,errmsg,err) { console.log("HEY, THIS IS NOT WORKING !") β¦ -
connect() failed (111: Connection refused) while connecting to upstream || NGINX to Gunicorn
My nginx's default.conf file : server { listen 8000; location / { proxy_pass http://127.0.0.1:8001; } location /static/ { autoindex on; alias /root/gunicorn/webserver/static/; } } And, the port it is routing to : root@ip-X.X.X.X:~/gunicorn/webserver# docker run -it -p 8001:8001 guncorn_new [2020-02-24 16:24:35 +0000] [6] [INFO] Starting gunicorn 19.10.0 [2020-02-24 16:24:35 +0000] [6] [INFO] Listening at: http://0.0.0.0:8001 (6) [2020-02-24 16:24:35 +0000] [6] [INFO] Using worker: sync [2020-02-24 16:24:35 +0000] [9] [INFO] Booting worker with pid: 9 NOTE: 127.0.0.1:8001 (gunicorn) is accessible when manually opened via browser. But not via NGINX. AND all this works when I EXPLICITLY mention the public IP of my server instead of '127.0.0.1' in the default.conf file. # For DevOps nerds # FROM nginx EXPOSE 8000 EXPOSE 80 COPY ./default.conf /etc/nginx/conf.d/default.conf # ERROR MESSAGE # root@ip-172-31-90-249:~/gunicorn/nginx# docker run -it -p 80:80 nginx_new 2020/02/24 16:22:39 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 45.248.29.38, server: localhost, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "54.85.138.232" -
How to work with django SlugField and slugify?And How to use it properly?
I google about how to use slug and already watched some videos.But I am confused how does this work. Help me by Giving Some Example or Any Resources. It will be be very helpful for me. Thanks Good People. -
IntegrityError at /personal_detail/
I got this error as I was getting MultiValueKeyDictError I used POST.get but than I got this error IntegrityError at /personal_detail/ NOT NULL constraint failed: users_personal_detail.beneficiary_adhaar_name Request Method: POST Request URL: http://127.0.0.1:8000/personal_detail/ Django Version: 3.0.3 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: users_personal_detail.beneficiary_adhaar_name Exception Location: C:\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['C:\\pradhan-mantri-matru-vandana-yojana\\pmmvy', 'C:\\Python\\Python38\\python38.zip', 'C:\\Python\\Python38\\DLLs', 'C:\\Python\\Python38\\lib', 'C:\\Python\\Python38', 'C:\\Users\\diwas\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Python\\Python38\\lib\\site-packages'] My views.py looks like this,I used 'get' to avoid getting MultiValueKeyDictError def ApplyOnline(request): return render(request,'users/applyonline.html') @login_required def personal_detail(request): # ShowHideExample = request.POST.get('showHideExample',False) beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name') adhaarno=request.POST.get('adhaarno') # adhaarcopy =request.POST['adhaarcopy'] idcard=request.POST.get('idcard') adhaar_eid=request.POST.get('eid') beneficiary_id_name=request.POST.get('beneficiary_id_name') idno=request.POST.get('idno') # idcopy=request.POST['idcopy'] apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name,adhaarno=adhaarno, idcard=idcard,adhaar_eid=adhaar_eid,beneficiary_id_name=beneficiary_id_name,idno=idno) apply_online.save() return render(request,'users/applyonline.html') models.py (I tried using like idno=request.POST.get('idno',null=True) but it doesn't work) class Personal_Detail(models.Model): beneficiary_adhaar_name=models.CharField(max_length=30) adhaarno=models.IntegerField() adhaarcopy = models.ImageField(upload_to='adhaar/') idcard=models.TextField() adhaar_eid=models.IntegerField() beneficiary_id_name=models.CharField(max_length=30) idno=models.IntegerField() idcopy=models.ImageField(upload_to='identitycard/') def __str__(self): return self.beneficiary_adhaar_name + self.beneficiary_id_name I tried using nulll=False in my views like idcard=request.POST.get('idcard',null=True) but I again got error that get cannot associate with null or something like that. -
How ao apply custom filter to a django filters ModelChoicefilter
I'm using Django Filter to filter data in my Django project. Now I need to filter some specific ModelChoiceFilter based on the current logged in user. I've tried sending data using def _init_ to the form and then execute the filtering using self.fields['field_name'].queryset = my_qs, but it gives me unresolved error for self.filters. Finally, I've used the Filter.Method options from Django Filter, here is my code: views.py f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user),user=request.user.id) forms.py class RequestsFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super().__init__(*args, **kwargs) start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'})) end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'})) employee = django_filters.ModelChoiceFilter(field_name='employee', method="filter_employee", queryset=Employee.objects.filter()) class Meta: model = LeaveRequest fields = ['employee', 'type', 'date_time'] def filter_employee(self, queryset, name, value): qs = queryset.filter(user=self.user).filter(**{name: value}) if len(qs) >= 1: return qs[0] else: return None This no longer brings an error, but the employee field still shows all of the employees in the database, not filtering it based on the user. -
How can I implement a File_name field that excludes my file path and contains only the file name [Django models]
I am developing an app in Django. In my template I have a fileform that allows users to store files in a model, they are stored in my media_root/uploaded_files/ directory: class my_model (models.Model): file_obj = models.FileField(upload_to='uploaded_files/', blank=False, null=False) def __str__(self): return "%s" % (self.file_obj) But in my admin section, accessing the model my_model I get file names like: β’ uploaded_ files/file_1 β’ uploaded_ files/file_2 β’ uploaded_ file /file_3 While I want: β’ file_1 β’ file_2 β’ file_3 How can I implement a File_name field that excludes βuploaded_ filesβ and contains only the file name? -
Is there a way to enable selecting multiple files on a single file upload in Django Admin so that upon saving multiple records are created?
I have a case where users upload files and each file has certain attributes. Often times there could be 10 files that will need to be uploaded into the database with the same attributes. To save time, it would be nice to allow the user to select all ten files and have 10 records added in the database, one record per file. My models are similar to the example below: class ContentCategory(models.Model): name = models.CharField(max_length=100) class Document(models.Model): file_name = models.CharField(max_length=100, blank=True) note = models.TextField(null=True, Blank=True) content_category = models.ForeignKey(ContentCategory, on_delete=models.PROTECT) document = models.FileUpload(upload_to=f'{content_category}/') def save(self): self.file_name = os.path.basename(self.document.name) super(Document, self).save() My admin.py is simple, like the below code: class DocumentAdmin(admin.ModelAdmin): exclude = ('file_name',) admin.site.register(Document, DocumentAdmin) admin.site.register(ContentCategory) So here is an exact scenario that happens often. 10 photos will need to be uploaded and all of them get the same content category and note. Is there a way to setup the admin to allow someone to select the proper content category and write out the note and then select all 10 files to upload and have 10 records created in the document table upon save? One for each photo? -
Django IntegerField retrieves a 0 as a None value
Django has started retrieving all of my IntegerField with a value of zero as None instead of as a zero. This is happening across all of my models. I recently updated mysql-connector-python so I am not sure if that could be the problem. Does anyone know of a global setting or bug that would cause Django to start doing this across all of my models? example: class Brands(models.Model): brand_id = models.AutoField(primary_key=True) brand_name = models.CharField(unique=True, max_length=512) blacklisted = models.IntegerField() blacklisted_date = models.DateTimeField(blank=True, null=True) date_created = models.DateTimeField() class Meta: managed = False db_table = 'brands' The values for blacklisted are all being retrieved as None instead of 0. They are stored as a 0 in the database. Django version 2.2.1 MySQL InnoDB Thanks for any help you can provide. -
How do I mofify existing fields in django that have a many to many relationship?
I have a model with a many to many field (participant field in my Activity model, see below) that I want to edit using createview. However, I can only choose from the already existing entries, not create new ones. It is possible to do that in the admin site so there is a solution but I can't figure it out. I have tried to modify form_valid in views but with no succes. Any ideas how to add or modify a field that has a many to many relation? views.py: #response=super(CreateTour,self).form_valid() #self.object.project=self.form.cleaned_data['participant'] class CreateTour(CreateView): form_class=CreateTourForm template_name='artdb/createtour.html' def get_context_data(self,**kwargs): context=super(CreateTour,self).get_context_data(**kwargs) context['formset']=CreateFormset() return context def form_valid(self,form): self.object=form.save(commit=False) for p in form.cleaned.data['participant']: ap=Person() ap.group=self.object ap.person=ap ap.save() return super(self).form_valid(form) models.py: class Activity(models.Model): activity_name=models.CharField(max_length=200,default='no name') project=models.ForeignKey(Project,on_delete=models.CASCADE,default=1) participant=models.ManyToManyField(Person) min_stage_area=models.IntegerField(default='2') light_requirements=models.CharField(max_length=200,default='no requirements') sound_engineer=models.CharField(max_length=200,default='not needed') comment=models.ManyToManyField(Comment) def __str__(self): return self.activity_name class Meta: ordering = ('activity_name',) forms.py: class CreateTourForm(ModelForm): class Meta: model=Activity fields=('activity_name','project','participant') widgets={'participant':CheckboxSelectMultiple,} template: {% extends "artdb/index.html" %} {% block ct %} <form method="post">{% csrf_token %} <div class="input-group"> {% for fr in formset %} {{fr}} {% endfor %} <a> {{form}} </a> <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> </div> <hr></hr> <div class="row spacer"> <input type="submit" value="save"> </div> </form> {% endblock ct %} -
Django LDAPS configuration
I have a django server (in Centos) with an LDAP server and i want to configure it as LDAPs. The steps i've followed are (with a given .cer): Copy the cer into /etc/openldap/certs cacertdir_rehash /etc/openldap/certs update-ca-trust enable Copy the cert into /etc/pki/ca-trust/source/anchors/ update-ca-trust extract update-ca-trust check Then I changed the setting.py in my Django server: AUTH_LDAP_SERVER_URI = "ldap://xxx" to AUTH_LDAP_SERVER_URI = "ldaps://xxx:636" SERVER_DOWN({'info': "TLS error -8179:Peer's Certificate issuer is not recognized.", 'desc': "Can't contact LDAP server"} I'm pretty sure that the server is working (as it worked for normal LDAP). Can you help me? -
Unable to access request.session variable upon url callback in Django
I am trying to integrate Spotify Authorization flow (to gain access and refresh tokens) into my Django app. For this I have setup two Django endpoints - one for spotify login and another for spotify callback. The login endpoint redirects to the spotify authorization endpoint, which requires the user to login into their spotify account and grant permissions. This is followed by the Spotify API redirecting to the callback view in my Django app. Along with redirecting, the API sends a get variable, that is further utilised by the callback view to gain access and refresh tokens. I need to store these tokens for each user of my website and for that I need to gain access to the user id. However the request.session variable always comes in empty in the callback view. Suggestions for gaining access to the request.session variable? -
Store Json schema in django model
I have to validate my incoming json files through some schema files which will be sent before Json filesarrive, I need to store my schema files inside a model so I can validate my incoming json files. My problem is my schema file in not a standard type and it's format is like this: { namespace: βstringβ, schema: { field_1: type1, field_2: type2, β¦ } } How can I store incoming schema in this scenario and validate incoming json files with them? -
Django NoReverseMatch at /create/
I want to create a system. For this system I need to a patient create form. When I click the button, I can save the patient but there is a error page after I pushed it. Reverse for 'create' with keyword arguments '{'slug': 'James'}' not found. 1 pattern(s) tried: ['create/$'] (When I fill the form, I write James into title field) And even I write James, in mySql database, title column is like id. 1, 2, 3, ... etc not James... Where is my mistake? Thanks a lot. urls.py app_name = "patients" urlpatterns = [ path('patients/', views.PatientList.as_view(), name='patients_list'), url(r'^create/$', patient_create, name='create'), path('create/<slug:slug>/', views.PatientsDetail.as_view(), name='patients_detail'), ] models.py from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.text import slugify from ckeditor.fields import RichTextField class newPatients(models.Model): title = models.CharField(max_length=100) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) dept = models.TextField() address = models.TextField() phone = models.CharField(max_length=15) notes = RichTextField(verbose_name="notes") slug = models.SlugField(max_length=100, unique=True, editable=False) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_create_url(self): return reverse('patients:create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.title.replace('Δ±', 'i')) unique_slug = slug counter = 1 while newPatients.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def get_absolute_url(self): return reverse('patients:create', β¦ -
Django-Ajax passing multiple parameters
I am trying to get more details on clicking a button "type="button" class="apireq"" defined on each row and capture the result in javascript and show it in a window I am not able to get the clicked row data in jquery .It says variable value undefined .I wanted to POST multiple values . Is this the way to do it ? Do I need to modify urls.py template <tbody id="collist"></tbody> </tr> {% for index, row in s_results.iterrows %} <tr> <td> {{ row.colname }} </td> <td> {{ row.dbname }} </td> <td> {{ row.schemaname }} </td> <td> {{ row.tablenm }} </td> <td> {{ row.coltype }} </td> <td> {{ row.collength }} </td> <td> {{ row.colscale }} </td> <td> <input type="button" class="apireq" data-colname="{{row.colname}}" data-dbname="{{row.dbname}}" data-schemaname="{{row.schemaname}}" data-tablenm="{{row.tablenm}}" /> </td> <tr> {% endfor %} </tbody> js/app.js $('.apireq').click(function () { var jq_column_name = $("#collist tr").last().attr("data-colname"); alert(jq_column_name); var jq_dbname = $("#collist tr").last().attr("data-dbname"); var jq_schemaname = $("#collist tr").last().attr("data-schemaname"); var jq_tablenm = $("#collist tr").last().attr("data-tablenm"); $.ajax({ type: "POST", url: "http://localhost:8000/refresh1/", contentType: 'application/json; charset=utf-8', data: { column_name: jq_column_name, db_name: jq_dbname, schema_name: jq_schemaname, table_name: jq_tablenm }, success: function (data) { alert("success!!");}, error: alert("Failed!!") });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> urls.py path('refresh////', views.refresh1, name='refresh1'),