Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete multiple records from different classes in django?
It seems that whenever I delete records I get server error (500), I'm knew in web development so I don't know what's causing the problem please help... these are my classes in models.py where I would like to delete records from: class Bscs1_1(models.Model): idNumber = models.CharField(max_length=15) CC100 = models.FloatField() CC101 = models.FloatField() resultCS11 = models.IntegerField() courseCS1 = models.TextField() class Cs(models.Model): cs_count = models.TextField() class Retention_cs1(models.Model): retention_count = models.TextField() And this is how I add records from views.py: def resultCS1_1(request): CC100 = request.POST['CC100'] CC101 = request.POST['CC101'] prediction = model1.predict([[CC100,CC101]]) studentID = request.POST['studentID'] student1 = Bscs1_1() student1.idNumber = studentID student1.resultCS11 = prediction student1.CC100=CC100 student1.CC101=CC101 student1.save() courseCS1 = Cs(cs_count='BSCS1') courseCS1.save() retention = Retention_cs1() if prediction == 0: retention.retention_count = 'NEGATIVE' else: retention.retention_count = 'POSITIVE' retention.save() return render(request, "rCS1_1.html" , {'student1': student1} ) This is how I delete records from all those classes all in one click of a button: def deleteCS12(request, student_id): stud = Bscs1_1.objects.get(pk=student_id) stud.delete() csCount = Cs.objects.get(pk=student_id) csCount.delete() retention = Retention_cs1.objects.get(pk=student_id) retention.delete() return redirect('tableCS12') -
How can I use Q objects on Two Dynamic Search Forms in Django
I am working on a Django project where I want to search profile records for those that are resident in a particular country and state. In this project I would be collecting data of people from different countries and their respective states, so I want a situation where I can have two Search Forms for Country and State. The form should be able to allow me select list of countries in the Profile Model while the state form should be able to allow me type and search for a state in the selected country. The result should be a list of persons in the selected Country and searched state.Please understand that I decided to go with Q objects because I learn that it makes queries efficient. Here are my model code: class Profile(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) surname = models.CharField(max_length=10, null=True) othernames = models.CharField(max_length=30, null=True) gender = models.CharField(max_length=6, choices=GENDER, blank=True, null=True) nation = models.CharField(max_length=10, choices=NATION, blank=True, null=True) state = models.CharField(max_length=20, null=True) address = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=11, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') Here is my search form code: class Applicant_Search_Form(forms.ModelForm): class Meta: model = Profile fields = ['nation', 'state'] Here is my views code: def … -
DRF how to update, create OneToOneField in serializers?
I have two models, with OnetoOne field. How can I update/create them with help of serializers? class Page(models.Model): info = models.TextField(null=True, blank=True) document = models.OneToOneField( Document, primary_key=True, related_name='page', on_delete=models.CASCADE) class Document(models.Model) description = models.TextField(null=True, blank=True) note = models.TextField(null=True, blank=True) My serializer class PageSerializer(ModelSerializer): document = DocumentSerializer() class Meta: model = Page fields = ('document', 'info') def update: def create: -
Question about a code in a Django Girl's tutorial
I'm through a Django Girls' tutorial. There is this code (that I think is mistyped): <a href="<div data-gb-custom-block data-tag="url" data-0='post_draft_list'></div> " class="top-menu"><span class="glyphicon glyphicon-edit"></span></a> Regardless of the errors, I'm trying to figure out what this part does: <div data-gb-custom-block data-tag="url" data-0='post_draft_list'></div> I searched in the internet, but I didn't find an explanation for it. What are 'data-gb-custom-block', data-tag, and 'data-0'? Neither Django's documentation nor Mozilla's mention these codes, that I believe is something belonging to HTML. -
How to groupby one column of django table based on another column
I have a table like below: id | type | code ------------------------------------- 0. 5 2 1 6 6 2 8 16 3 4 11 4 5 4 5 2 2 6 4 1 7 10 6 8 9 2 All I need like output is a list of groupby on codes like here: { '2': [5,2,9], '6': [6, 10], '16': [8], '11':[4], ...} I did this query but it's not doing the right query: type_codes = [{ppd['code']:ppd['type_id']} for ppd in \ MyClass.objects \ .values('code', 'type_id') .order_by() ] Any help will be appericiated -
how to show success message without refreshing the page in django
I have a template called basket whenever I want to update the product quantity it works fine but the success message doesn't show until I refresh the page views.py: def basket_update(request): basket = Basket(request) if request.POST.get('action') == 'post': book_id = int(request.POST.get('bookid')) book_qty = int(request.POST.get('bookqty')) basket.update(book=book_id, qty=book_qty) messages.success(request,"Basket Has Been Updated") basketqty = basket.__len__() baskettotal = basket.get_total_price() response = JsonResponse({'qty': basketqty, 'subtotal': baskettotal}) return response -
Django profile picture does not upload
This question was asked I don't know how much but it doesn't give my answers The app I was gonna make is a little blog webapp from a tutorial (for some training in Django, it's the first time I use it so...) There is my code: # models from django.db import models from django.contrib.auth.models import User from PIL import Image # Create your views here class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) Well, that's not all: @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm( request.POST, instance=request.user ) p_form = ProfileUpdateForm( request.POST, request.FILES, instance=request.user.profile ) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'title': 'Profile', 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html', context) At this time, I changed all my settings and I did some html code: {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username … -
The 'for' loop only one product's attribute in django
I want to calculate the the difference between total product quantity and shopcart product quantity. So I made calculations in my views and applied to templates. The problem is the for loop which I think should loop through all products only loops to the recently added product and give the result to all the products. What did I do wrong? Here is the code: Template {% for rs in products %} <div> <a href="{% url 'addtoshopcart' rs.id %}" class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Add to Cart</a> </div> <p><strong>Availability:</strong> {% if tot > 0 %} In Stock : {{tot}} Remaining {% else %} Out of Stock {% endif %}</p> {% endfor %} Views def category_products(request,id,slug): current_user = request.user #category = Category.objects.all() setting = Setting.objects.get(pk=1) catdata = Category.objects.get(pk=id) products = Product.objects.filter(category_id=id) context={'products': products, #'category':category, 'setting':setting, 'catdata':catdata } for rs in products: if rs.variant == 'None': checkinproduct = ShopCart.objects.filter(product_id=id, user_id=current_user.id) # Check product in shopcart if checkinproduct: control = 1 # The product is in the cart else: control = 0 # The product is not in the cart""" if control == 1: tot = rs.amount - ShopCart.objects.get(product_id=id, user_id=current_user.id).quantity else: tot = rs.amount context.update({'tot': tot}) else: pass return render(request,'category_products.html',context) -
Django / How to evaluate a django variable inside a bracket expression?
In my html file I need to define a variable for a js file. <script> var gltf_home = "{% static '/3d/ {{ scene.GltfFileToLoad }} ' %}"; </script> which gives as an output : /static/3d/%7B%7B%20scene.GltfFileToLoad%20%7D%7D instead of /static/3d/00-world.glb And this alternative var gltf_home = "{% static '/3d/' {{ scene.GltfFileToLoad }} %}"; gives /static/3d/ What would be the correct way to do it ? -
Djongo migrate models cons
Its's nice to see mongodb is connected with django but doesn't support completely. I explain why so because when you install any third party packages to your project it could written for Django models not Djongo which will fall you in Database error while migrating you apps. djongo.database.DatabaseError Do we have any solution for this case? -
Django: After updating a template, the changes are not reflected upon refreshing the page in the browser
I am testing a class based view in my Django application. I am currently in development, so I want to see changes in the browser as soon as I make any change in a template. The urls.py of the main app is below: urlpatterns = [ path('myapp/', include('myapp.urls')), ] urls.py of myapp: from django.urls import path, include from . import views urlpatterns = [ path('all/', views.AllView.as_view(), name="myapp-all"), ] The views.py file in myapp looks like below: from django.views import View from django.template import loader from django.http import HttpResponse # Create your views here. class AllView(View): template = loader.get_template('myapp/all.html') def get(self, request, *args, **kwargs): return HttpResponse(self.template.render(request=request)) The all.html template looks like below: {% extends 'base.html' %} {% block title %} Example Table {% endblock %} {% block content %} <div class="d-flex justify-content-center"> <div class="col-8"> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> </div> {% endblock %} The above template is stored in the below directory: base_directory -> myapp -> templates -> myapp -> all.html The settings.py file … -
How do I filter models from the Django admin sidebar while keeping them on their children's change page form?
I have a setup that looks like this: Because 'Charities' and 'Interventions' aren't meant to be edited except from the Evaluations and Max Impact Fund Grants page, I don't want to show up in the navbar menu. I've been scraping through the bowels of Django looking for a way to do this, and the least hacky way I can find is overwriting the django.contrib.admin.AdminSite.get_app_list function, such that after it's assembled the app_list array, I modify in place the element containing the models to delete the offending two. The two problems with this are 1) it's incredibly hacky and 2) it doesn't actually work - I end up with an empty navbar with the message that I don't have permission to modify any objects (I confirmed that the app_list post-modification had the rest of the elements). I feel like there's probably some trivial approach like 'define the app_navbar_models variable to have an exclude list on one of your admin objects', but I have failed to find such an approach either on StackOverflow or indicated in the Django code. Did I miss something? -
Ho to create serializer for model having foreign keys to access that foreign keys tables data also?
I want to rewrite the following API in a more efficient way using the serializer. In the following API, the user and group are foreign keys. I want to return all matching data of group and user using Serializer. How to design a serializer for this situation. @api_view(['GET']) def get_post(request, group_id, post_type, post_limit): if request.method == 'GET': print('group id = ') print(group_id) # data = GroupPostsModel.objects.filter( # group_id=group_id) & GroupPostsModel.objects.filter(post_type=post_type).order_by('-time_stamp') try: data = GroupPostsModel.objects.filter( group_id=group_id, post_type=post_type).order_by('-time_stamp')[post_limit:post_limit+3] # data = data[0:3] model.objects.filter(book = 'bible') post_arr_obj = [] for post in data: comments_count = GroupPostCommentsModel.objects.filter( post_id=post.id).count() print('post id = '+str(post.id)) post_dict = { 'post_id': str(post.id), 'post_text': str(post.post_text), 'post_type': str(post.post_type), 'image': str(post.image), 'document': str(post.document), 'likes': str(post.likes), 'group_id': str(post.group.id), 'user_id': str(post.user.id), 'time_stamp': str(post.time_stamp), 'profile_pic': str(post.user.profile_pic), 'first_name': str(post.user.first_name), 'last_name': str(post.user.last_name), 'gender': str(post.user.gender), 'comments_count': str(comments_count) } post_arr_obj.append(post_dict) except Exception as e: print('get_post exception : '+str(e)) resp = { 'resp': post_arr_obj } # group_post_serializer = GroupPostsSerializer(data, many=True) return Response(resp) else: return Response({'msg': 'Only GET request allowed..!'}) Relationship One user can join/create many groups One group can have mane posts One user can post many posts UserModel class UserModel(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) gender = models.CharField(max_length=6) college_name = models.CharField(max_length=50) user_id = models.CharField(max_length=30,unique = True) user_password = … -
Django admin and normal user seperation
Everytime i logout of the normal user system it also logs me out of admin page. the normal user system is created using the AbstractUserModel provided by django and admin created using createsuperuser command. How do i prevent that from happening. Currently using authentication system provided by django (accounts/login, accounts/logout etc) -
Am trying to launch in Cpanel, but am getting a Module not found error
I'm new to Cpanel and am trying to launch my python Django project, I think I've set up everything correctly but am getting this error: File "/opt/alt/python38/lib64/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named '<my_module_name>' [UID:2291][2142962] Child process with pid: 2149437 was killed by signal: 15, core dump: 0 Any help offered would be much appreciated, thanks in advance -
Docker compose 'Address not available'
When I try to run docker-compose django postgres I get this error: could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 8000? My Dockerfile: FROM python:3.8.3-alpine WORKDIR /bewise ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk --no-cache --update-cache add postgresql-libs postgresql-dev libffi-dev openldap-dev unixodbc-dev git RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . My docker-compose.yml: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - . :/bewise/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=123123 - POSTGRES_DB=db_01 volumes: postgres_data: Settings.py: DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } .env.dev: DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=db_01 SQL_USER=user SQL_PASSWORD=123123 SQL_HOST=db SQL_PORT=5432 -
Using forloop.counter to iterate over list in django template
I have a list of objects named chargers_list and on my view I estimate when will the charging be done. List of estimates is the same size and is named eta. I iterate over chargers {% for charger in charger_list %} to display some information about every charger. Inside that loop I want to print estimated time. Simple ETA: {{eta.0|date:'Y-m-d H:i'}} works if I provide the index. But how can I utilize forloop.counter (that's the only way I thought of doing this)? When I simply ETA: {{eta.forloop.counter|date:'Y-m-d H:i'}} it throws an error: Exception Type: TemplateSyntaxError Exception Value: Could not parse some characters: eta|[forloop.counter]||date:'Y-m-d H:i' -
I display a table with ajax in real time and I check some lines which I return in my views
I have this problem in summary: when i fill my input automatically i display an array using ajax , and on the same table I shock a few lines and when I send back to my views through a button I have nothing that is displayed either at the console or the terminal. Js & Ajax enter code here $(document).on("click","#final",function(){ const list_entrepot = getSelectedVals1(); const list_fournisseurs = getSelectedVals(); selection = {list_fournisseurs,list_entrepot}; $.ajax({ async: false, type : "GET", url : 'fournisseur_ajax', data :{ 'csrfmiddlewaretoken': csrf, 'selection':selection, }, success : (res) =>{ console.log(res.data) } }); }); function getSelectedVals(){ var tmp =[]; $("input[name='fournisseur_tab']").each(function() { if ($(this).prop('checked')) { checked = ($(this).val()); tmp.push(checked); } }); var filters = tmp.join(','); console.log(filters) return filters; } -
Django form with dropdown list using Database returns empty fields
I'm discovering Django and I'm trying to develop a simple application. I have three tables in my database : One big table to report all the information to users and 2 tables to create drop down list on my form (but no usage of foreign keys on purpose). I need to have these two tables because statuses and areas need to be editable at all time and need to be written in the same way each time in the main table Action. Here is my model.py : class Status(models.Model): id_status = models.AutoField(db_column='ID_STATUS', primary_key=True) status = models.CharField(db_column='STATUS', max_length=50) def __str__(self): return self.status class Meta: managed = False db_table = 'T_EAVP_STATUS' class Area(models.Model): id_area = models.AutoField(db_column='ID_AREA', primary_key=True) area_name = models.CharField(db_column='AREA_NAME', max_length=50) def __str__(self): return self.area_name class Meta: managed = False db_table = 'T_EAVP_AREA' class Action(models.Model): id = models.AutoField(db_column='ID', primary_key=True) title = models.CharField(db_column='TITLE', max_length=200) due_date = models.DateTimeField(db_column='DUE_DATE') status = models.CharField(db_column='STATUS', max_length=50) date_insert = models.DateTimeField(db_column='DATE_INSERT', auto_now_add=True) emitting_area = models.CharField(db_column='EMITTING_AREA', max_length=50) receiving_area = models.CharField(db_column='RECEIVING_AREA', max_length=50) owner = models.CharField(db_column='OWNER', max_length=200) def __str__(self): return self.title class Meta: managed = False db_table = 'T_EAVP_ACTION' Here is my forms.py : class ActionForm(forms.ModelForm): status = forms.ModelChoiceField(queryset=Status.objects.all()) receiving_area = forms.ModelChoiceField(queryset=Area.objects.all()) emitting_area = forms.ModelChoiceField(queryset=Area.objects.all()) class Meta: model = Action fields = ['title', … -
in Django : Why nothing happens when I try to Create new note with the html form in the notes.html page
I just start my first app with Django by following a video on YouTube.. the app is a students dashboard has 8 tools and features help the student to make note, search for help, save books, etc. So when I follow the steps I get stuck , in the creation of a new note but note from the admin side but from the actual notes template that has a crispy form and a create button. the program supposed to write a title and description(the content of the note) then press the create button. but nothing happened everytime I tried to click (create) #This is the view.py page in the dashboard app : from django.shortcuts import render from . forms import * from django.contrib import messages # Create your views here. def home(request): return render(request, 'dashboard/home.html') def notes(request): if request.method == "POST": form = NotesForm(request.POST) if form.is_valid(): notes = Notes(user=request.user,title=request.POST['title'],description=request.POST['description']) notes.save() messages.success(request,f"Notes Added from {request.user.username} Successfully") else: form = NotesForm() notes = Notes.objects.filter(user=request.user) context = {'notes':notes,'form':form} return render(request,'dashboard/notes.html',context) and this is the notes.html page in the dashboard app > template folder > dashboard folder : {% extends 'dashboard/base.html' %} <!-- Load the static files here --> {% load static %} {% … -
FieldError at /teacher/8/. Cannot resolve keyword 'teacher' into field. Choices are: classroom, faculty, faculty_id, id, name
I reach the error in my django project when I was trying to display my view. The problem seems like related to the Course model but i honestly dont know where to begin with it. My Teacher model: class Teacher(models.Model): GENDER_MALE = 0 GENDER_FEMALE = 1 GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')] fname = models.TextField(max_length=20) lname = models.TextField(max_length=20) gender = models.IntegerField(choices=GENDER_CHOICES) phone = models.IntegerField(default=None, blank=True, null=True) email = models.TextField(max_length=30, default=None, blank=True, null=True) faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE ) def __str__(self): return self.lname + ' ' + self.fname My Course model: class Course(models.Model): name = models.TextField(max_length=50) faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE ) def __str__(self): return f'{self.name}' My view: def teacher(request, teacher_id): teacher = get_object_or_404(Teacher, pk=teacher_id) faculties = Faculty.objects.filter(teacher=teacher) course = Course.objects.filter(teacher=teacher) classrooms = Classroom.objects.filter(teacher=teacher) students = Student.objects.filter(teacher=teacher) # students = [] # for cls in classrooms: # students.extend(Student.objects.filter(classroom=cls)) return render(request, 'polls/teacher.html', {'teacher': teacher,'faculties': faculties, 'courses':course,'classrooms':classrooms, 'students':students}) When i run the website, it point out in my view the code to be stoped at course = Course.objects.filter(teacher=teacher) My template: {% extends "polls/base.html" %} {% block body %} <h2>{{ teacher.fname }} {{ teacher.lname }}</h2> <h3>Faculty</h3> {% if faculties %} {% for faculty in faculties %} <p><a href="{% url 'faculty' faculty.id %}">{{ faculty.name }}</a></p> {% endfor … -
drf_yasg.generators: path component of api base URL http://localhost:8080/ is ignored; use FORCE_SCRIPT_NAME instead
I am using swagger (drf_yasg.generators) with Django and I get the following error message Error message is drf_yasg.generators: path component of api base URL http://localhost:8080/ is ignored; use FORCE_SCRIPT_NAME instead Here is the swagger class SchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, request=None, public=False): schema = super(SchemaGenerator, self).get_schema(request, public) schema.basePath = os.path.join(schema.basePath, "") return schema if env.bool("DJANGO_DEBUG"): schema_view = get_schema_view( openapi.Info( title="API", default_version="v1", description="API endpoints", ), url="http://localhost:8080/", public=True, permission_classes=(permissions.AllowAny,), urlconf="config.urls", generator_class=SchemaGenerator, ) Here is the URL urlpatterns = [ path(settings.ADMIN_URL, admin.site.urls), path("api/", schema_view.with_ui("swagger", cache_timeout=0), name="swagger"), path("algo1/", include("core_functions.algo1.urls")), ] Can someone please help with the error? -
Django form_valid method
In my form's view I wonder what if I don't add product_form.save method in the code below and what if I add that: def form_valid(self, form): product_form = form.save(commit=False) product_form.user = self.request.user product_form.save() # what if I delete this? return super().form_valid(form) -
Django / Create HTMl file from a form
In my Models.py class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) I have submitted the form in Views.py (simplified version) def add_scenes(request): form = sceneForm(request.POST, request.FILES) if form.is_valid(): return HttpResponseRedirect('add_scenes?submitted=True') return render(request,'scenes3d/add_scenes.html', {'form':form, 'submitted':submitted}) What I would like is : after the form is submitted, a new html is created which would be defined in urls.py with the slug name of my form. path('<str:slug>',views.newpage, name="newpage"), Is it the right way to achieve that ? -
Stuck in urls.py while migrating a website from Python 2 to Python 3
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) While running manage.py makemigrations, got this error and was stuck in this error for a day . This is the error I received File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 112, in format_suffix_patterns return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 59, in apply_suffix_patterns regex = urlpattern.pattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern AttributeError: 'tuple' object has no attribute 'pattern' This is my urls.py ( Note: it is shorted because of more than 400 lines) urls.py urlpatterns = [('CyberHealth.views', re_path(r'^$', views.index, name='index'), #==== Role === re_path(r'^getorinsertroleAPI/$', views.getorinsertroleAPI, name='getorinsertroleAPI'), re_path(r'^updateordeleteroleAPI/(?P<pk>[0-9]+)/$', views.updateordeleteroleAPI, name='updateordeleteroleAPI'), #==== Register === re_path(r'^registerUser/$', views.registerUser, name='registerUser'), re_path(r'^registerFBUser/$', views.registerFBUser, name='registerFBUser'), re_path(r'^admin/registerCoach/$', views.registerCoach, name='registerCoach'), #==== Login === re_path(r'^login/$', views.loginMethod, name='loginMethod'), re_path(r'^getUserId/$', views.getUserId, name='getUserId'), ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) views.py @csrf_exempt def getHealthyLivingListByUser(request, format=None): if request.method == 'POST': try: request_params=json.loads(request.body) limit=request_params.get('limit') offset=request_params.get('offset') limit=offset+limit tasks = tbl_healthyliving.objects.filter(status=1).order_by('-syndicateid') totalrecords=len(tasks) tasks=tasks[offset:limit] serializer = tbl_healthylivingSerializer(tasks, many=True) return JsonResponse({'Response':'Success','Response_status':1,'totalrecords':totalrecords,'healthyliving':serializer.data}) except Exception as e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':e.message})) else: return HttpResponse(status=405,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Method not allowed'})) Kindly help me to solve this issue as soon as possible