Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use views function in other function?
Same, how in ask. How can i use view function in my other function? Im trying do like button, but i dont have idea how can i got this. First Function def LikeView(request, pk): moje_posty = get_object_or_404(Posty, id=request.POST.get('post_id')) if moje_posty.likes.filter(id=request.user.id).exists(): moje_posty.likes.remove(request.user.id) else: moje_posty.likes.add(request.user.id) return HttpResponseRedirect(reverse('home:detail_post', args=[str(pk)])) Second Function def contact(request, pk): template_name = 'detail_post_view.html' post = get_object_or_404(Posty, pk=pk) comment = CommentPost.objects.all().filter(post=post.id).order_by('-date_posted')[:10] new_comment = True profil = Profil.objects.get(user=request.user) if request.method == "POST": comment_form = CommentModelForm(request.POST or None) if comment_form.is_valid(): instance = comment_form.save(commit=False) instance.user = profil new_comment = comment_form.save(commit=False) new_comment.post = post comment_form.save() comment_form = CommentModelForm() else: comment_form = CommentModelForm(request.POST or None) context = { 'post':post, 'new_comment':new_comment, 'comment_form':comment_form, 'comment':comment, } return render(request, template_name, context) How can i use this in my template? -
django query to get data
I am into a very confusing situation where I have one to many relation and I want to query data like I want all parent table data but want to get only data from child tables which fulfill condition of site_id = 100. class Policy(Base): """table containing details for Policies""" __tablename__ = "UmbrellaPolicy" id = Column(Integer, primary_key=True) policy_id = Column(Integer, nullable=False, index=True) user_defined_name = Column(String(255), nullable=True) and child is like this class Site(Base): __tablename__ = "Site" id = Column(Integer, primary_key=True) policy_id = Column(Integer, ForeignKey("Policy.id")) site_id = Column(String(32), nullable=False, index=True) policy = relationship("Policy", backref="sites") -
django heroku requirements.txt errors on push
I am deploying my djnago project/PWA using heroku. I generated requirements.txt with pip freeze > requirement.txt Then, I deleted all the @... paths because of the following error: Processing /C:/ci/argon2-cffi_1596828585465/work remote: ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '/C:/ci/argon2-cffi_1596828585465/work' but, even after removing the @, it is still reading from the same non existent path. This is the snippet of requirements.txt I now have: alabaster==0.7.12 anaconda-client==1.7.2 anaconda-navigator==2.0.4 anaconda-project==0.8.3 argh==0.26.2 argon2-cffi asn1crypto astroid astropy==4.0.2 async-generator==1.10 atomicwrites==1.4.0 -
Authinticating using request.POST that is stored in a SESSION doesn't work
I have implemented a login function this way in django and I want to preserve the POST request after the login. So I stored the request.POST in a SESSION variable, and tried to authenticate with it using the built-in function is_authenticated. But I get the following error: 'dict' object has no attribute 'user' Once I use the original request.POST, the error goes away,but so as the login info. That's why I kept the login POST in a SESSION in the first place. 1-the login parameters are processed in views.py: def main_v(request): template = loader.get_template('service_booking/index.html') template_not_logged = loader.get_template('index_not_logged.html') #get POST data from session if 'login_request' in request.session: login_session = request.session['login_request'] else: login_session = request #check if logged in or not by processing the SESSION variable 'login_session' if login_session.user.is_authenticated: print("authinticated") print("user is:"+str(request.user)) return HttpResponse(template.render({},login_session.POST)) else: print("not authinticated") print("user is:"+str(request.user)) # create a form instance and populate it with data from the request: form = login_form(request.POST) return HttpResponse(template_not_logged.render({'form':form},request)) 2-the session variable is composed in another function that processes the login form: def login_form_fun(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the … -
JavaScript File is not working in template django
I am trying to connect the javascript page to the HTML template. I tried many ways but It doesn't show anything. There are no errors but Js file is not responding. The index.html file is: {% extends "network/layout.html" %} {% load static %} {% block body %} <!-- <form action="" method=""> <input type="text" name="post" id="post-body"> <input type="submit" name="" id="postbtn" value="Post"> </form> --> <input type="submit" name="btn" id="btn" value="check"> {% endblock %} {% block script %} <script src="{% static 'network/post.js' %}" type="text/javascript"></script> {% endblock %} the post.js file is: document.addEventListener('DOMContentLoaded', function(){ document.querySelector('#btn').onclick = function(){ document.querySelector('#heading').innerHTML = 'hello'; }; }) alert("Hello, Welcome to Javatpoint"); the settings.py : # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' and urls.py file: from django.urls import path from .views import * from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path('posts', compose_post, name='post' ) ] Please help me with this. I will be very thankful to you. -
Django make migrations contanstly creates AlterField for many-to-many field
I have a very annoying situation with my model I renamed a Model used as ManyToMany table # The business models contains this field admins = models.ManyToManyField("users.User", through=BusinessMember) # this is the many to many model used in in Business class BusinessMember(models.Model): user = models.ForeignKey( "users.User", related_name="memberships", null=False, on_delete=models.CASCADE ) business = models.ForeignKey( "business.Business", related_name="members", null=False, on_delete=models.CASCADE ) class Meta: db_table = "myproject__business_member" This model once was called "BusinessUser" and I had to rename it. I created the following migrations to rename the Model # Rename and alter model table 0011_rename_business_user_model.py class Migration(migrations.Migration): dependencies = [ ("business", "0010_add_business_field"), ] operations = [ migrations.RenameModel("businessuser", "businessmember"), migrations.AlterModelTable( name="businessmember", table="myproject__business_member", ), ] # Another migration to update the sequence class Migration(migrations.Migration): dependencies = [ ("business", "0011_rename_business_user_model"), ] operations = [ migrations.RunSQL( "alter sequence myproject_business_user_id_seq rename to myproject__business_member_id_seq;" ), ] After this change, the makemigrations constantly create a migration with this AlterField migrations.AlterField( model_name='business', name='admins', field=models.ManyToManyField(through='business.BusinessMember', to=settings.AUTH_USER_MODEL), ), It doesn't matter how many times I migrated this AlterField, Django creates another migration every time. Do you have any idea what I did wrong? -
How to pass data to a template without passing it through the view?
I have a base.html file where on the sidebar it loops through all the spaces inside of my Spaces model and displays them as links. I am wondering instead of passing these spaces through each view is there a way to just have them in the base template? I tried looking it up an came across template tags but I don't think those are what I am looking for. Base.html <div class="sidenav"> <h2>Spaces:</h2> {% for space in spaces %} <a href="/{{space}}">{{space}}</a> {% endfor %} </div> Right now I am passing 'spaces' through my views but I don't want to have to do that in each view i create. Any help would be appreciated! -
How to resolve code duplication in View for model instances filtering
I trying to figure out how to resolve probably a very simple issue, but I would like to do it in an appropriate and Django consistent way. Let's assume that we have an example model: class ExmapleModel(Model): vote_up = models.IntegerField(default=0) vote_down = models.IntegerField(default=0) def get_voting_count(self): return self.vote_up - self.vote_down Ok and now I would like to create separate views on one template for ExmapleModel which will have for instance voting count higher than 500 and for all instances. Of course, I could create something like: class ModelListView(ListView): model = ExmapleModel template_name = 'ExmapleModel_list.html' and the second one: class ModelListView(ListView): model = ExmapleModel template_name = 'ExmapleModel_list.html' queryset = ExmapleModel.objects.filter(get_voting_count()>300) Assuming all the above, I would like to prevent repeating a lot of code for the above example, I have no idea how to user a get_voting_count() method for filtering and combining all of those things for the working package. If you have any ideas on how to combine it please help me. On other hand should I use this logic within Model? -
How can I use the same mock database both while testing normal django views and api views?
I have a following problem: I run tests using TestCase and create some data for my database. However, before rendering the template the view uses some API calls and receives information from the real database instead of the mock one. Is there a way to solve this problem? Or maybe I should test the view and the API view separately? Maybe I should create APITestCase? Any help will be appreciated. -
How to get "Historical" Queryset for the dataset using Django ORM?
I have CurrencyHistory model along with the database table which is populated on every Currency model update for the historical data. class CurrencyHistory(models.Model): id = models.AutoField(primary_key=True) change_rate_date = models.DateTimeField(_("Change Rate Date"), auto_now=False, auto_now_add=True, db_column='change_rate_date') code = models.ForeignKey("core.Currency", verbose_name=_("Code"), on_delete=models.CASCADE, related_name='history', db_column='code') to_usd_rate = models.DecimalField(_("To USD Rate"), max_digits=20, decimal_places=6, null=True, db_column='to_usd_rate') Database structure looks like id | change_rate_date | code | to_usd_rate 1 | 2021-01-01 | EUR | 0.123456 2 | 2021-01-01 | CAD | 0.987654 3 | 2021-01-02 | EUR | 0.123459 4 | 2021-01-02 | CAD | 0.987651 I need to fetch data using Djnago ORM to have a dictionary to display single row per date with the every currency as columns, like this Date EUR CAD 2021-01-01 0.123456 0.987654 2021-01-02 0.123459 0.987651 But I have no idea how to correctly do it using Django ORM to make it fast. I suppose for loop over the all unique database dates to get dict for each data will work in this case but it looks very slow solution that will generate thousands of requests. -
Django queryset filtering not providing expected behavior
I have an app taking inputs from a user on the front end. The functionality I'm trying to implement should display all titles on the front end that have reviews <=0, or display NULL values in the database. reviewsign_high = 'lte' if reviewinput_high == '0': review_kwargs = { 'amz_reviews__isnull': True, 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high) } titles = titles.filter(**review_kwargs) However, I don't get any results back here. If I remove one parameter, i.e. 'amz_reviews__isnull': True, I do get all titles with reviews less than or equal to 0. Vice versa, if I remove 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high), I get all titles with NULL reviews. But them together, displays 0 results. Any ideas on a solution here? Thanks! -
changing color of a particular string in entire html document with Django
Suppose you have a word "day" in 100 sentences in your document. You can change the color of that word in the following way: <span style="color: #ff0000"> day </span> The problem is that you need to do it 100 times. I am using Django and I want to do it inside template with for loop. So, my problem is now to change the color of a string inside some sentence that I don't know what it will be. I tried with something like: def colored(sentence, string, color): if string not in sentence: return sentence else: colored_string = f'<span style="color: {color}"> {string} </span>' colored_string.join(sentence.split(string)) I thought that that will give me colored variable string, but that wasn't the case. It just returned the string '....<span....' without any including the same stuff. It just like it didn't recognized html at all. What is the correct way of solving the same problem? -
What does request.POST.get method return in Django?
What does request.POST.get("a") return while "a" is the reference to following html label for = "a">ADDED ITEMS:</label> <input hidden type="number" name="a" id="a"> def myfunc(): if request.method == "POST": a = request.POST.get("a"); obj = TransferedItems(item_id = a); obj.save(); return HttpResponse("sent") else: return HttpResponse("form submission failed") I am new at Django and I am unable to find what does request.POST.get return. Please guide me on my question. -
Why my code Django into HTMl variables didnt work
''' Im trying to get a variable into a html document with python and django ''' def nombrarVariables(request): nombre="juan" doc_externo=open("SeleccionGrafica2.html") template=Template(doc_externo.read()) doc_externo.close() contexto=Context({"variable": nombre}) documento=template.render(contexto) return HttpResponse(documento) -
how to get the instance of a newly created user in django function based view
i'm writing the logic in django where a newly created user would automatically get the free membership when they hit the signup button and right now, i know what to do but i don't know how to implement maybe becuase i don't have much experince with django. i defined an instance variable to store all the newly created information but i'm just stock and it keeps showing red underlined word in vsCode, Any help would be greatly appreciated views.py def register(request): reviews = Review.objects.filter(status='published') info = Announcements.objects.all() categories = Category.objects.all() if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') obj = request.user get_membership = Membership.objects.get(membership_type='Free') # error is showing "instance" is not access using visual studio code instance = UserMembership.objects.create(user=obj, membership=get_membership) messages.success(request, f'Account Successfully created for {username}! You can Login In Now') return redirect('userauths:login') elif request.user.is_authenticated: return redirect('elements:home') else: form = UserRegisterForm() context = { 'reviews': reviews, 'form': form, 'info': info, 'categories': categories } return render(request, 'userauths/register.html', context) traceback Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Destiny\Desktop\DexxaPik\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in … -
Image stored in media is not been displayed
when click on "yo" image is shown but when displayed through img tag its not appearing on webpage <a href="{{status.adv.url }}">yo</a> <img src="{{status.adv.url}}" width="250" height="250" alt="advertise"/> -
Is there any way to edit django template?
In the last part of the code there exists a for loop which helps in constructing the boostrap crousel , but to make the website responsive i need to remove that forloop . So is there any way achive responsiveness? <div class="carousel-item active"> {% for i in products %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top mt-2" alt="..."> <div class="card-body"> <h5 id="productName{{i.id}}" class="card-title">{{i.product_name}}</h5> <p id="productPrice{{i.id}}" class="card-text">₹ {{i.price}}</p> <span id='button{{i.id}}'> <div id='product{{i.id}}' class="btn btn-primary cart">Add to cart</div> </span> <a href="/shop/productView/{{i.id}}" id="quickView{{i.id}}" class="btn btn-primary ml-3">Quick view</a> </div> </div> </div> {% if forloop.counter|divisibleby:4 and forloop.counter > 0 and not forloop.last %} </div> <div class="carousel-item"> {% endif %} {% endfor %} </div> </div> -
Django - deployment Heroku, how to solve error server (500)? Cloudinary error?
I have a question about my deployment app Django on Heroku. Whenever it is Debug=False in the setting.py file, it returns Error server 500, and when True then it is, ok? It is with the collecstatic parameter? find below the setting file: Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 3.2.8. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ import os from pathlib import Path import django_heroku import cloudinary.api import cloudinary_storage # 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/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXXXXXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['ecom-beta-XXXXX.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store.apps.StoreConfig', 'cloudinary', 'cloudinary_storage', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ecommerce.wsgi.application' # Database # … -
Adding data to form before it submits via Javascript in Django
I am working on an app in Django where the user puts in their address and submits it in a form. I need to get this form data, along with its corresponding lat/long, into the views and save it in a model. So, I have used Javascript to call a lat/long API before the form submits and then add that data to the form so all of the data (the address and the lat/long) gets submitted to the server. However, this newly inserted data by Javascript does not show up with the rest of the POST data when submitted. I am not sure why this is. Here is the JS code: const initiate_ride_form = document.querySelector("#initiate-ride-form"); if (initiate_ride_form != null) { document.querySelector("#start-ride-button").onclick = () => { // these are just predecided addresses to simplify the code and isolate this problem const origin = '20%20W%2034th%20St%2C%20New%20York%2C%20NY%2010001' const destination = '1600%20Pennsylvania%Avenue%20NW%2C%20Washington%2C%20DC%2020500'; fetch(`https://api.opencagedata.com/geocode/v1/json?q=${origin}&key=b45938af46624365b08b989268e79d5e`) // Put response into json form .then(response => response.json()) .then(data => { // get the lat and long and save them in variables console.log(data.results[0].geometry); const longitude_origin = data.results[0].geometry.lng; const latitude_origin = data.results[0].geometry.lat; // add the make the hidden input's value equal to the long var input_long_origin = document.querySelector("#from_long"); input_long_origin.value = longitude_origin; // … -
How do I make an upload pdf and make it render to my page in django?
Right now I just have it so that in the admin site when the admin writes out the form and clicks send it has a button that says view on the page and you click it, it brings you to a pdf. How do I make it so that the admin can just upload a pdf from the admin site and make it render for all the users? -
How to precache/load remote postgres DB in django/python for faster testing?
I am running django with a remote heroku hosted DB for testing. When developing locally/testing I am using the remote DB. Is there a way to precache/load the entire database locally so that I don't have to do network calls when running queries? Otherwise, I am using lru_cache in python for certain queries. Is there something I'm missing where I can just fetch the whole thing and cache it? -
two formsets in one view - django
i'm trying to implement two formset in one view , one of the formsets should be pop up modal form , class MobileCollection(models.Model): mobile = models.ForeignKey(ModelCategory,on_delete=models.PROTECT,related_name='model_category') qnt = models.IntegerField() price = models.DecimalField(decimal_places=3,max_digits=20) class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) serial_no = models.CharField(max_length=7,unique=True,blank=True,null=True) status = models.BooleanField(default=True) def __str__(self): return f'{self.mobile}-{self.imei}' in the page we adding new instance of MobileCollection , and each MobileCollection have its own set of imei , if qnt = 10 then we have to add 10 imei @login_required def create_collection(request): item_formset = mcollection(queryset=MobileCollection.objects.none()) imei_formset = imei_modelformset(queryset=Imei.objects.none(),prefix='imei') if request.POST: item_formset = mcollection(request.POST) imei_formset = imei_modelformset(request.POST,prefix='imei') if imei_formset.is_valid() and item_formset.is_valid() and request.user.is_superuser: for item in item_formset: item_obj = child.save(commit=False) item_obj.save() for imei in imei_formset: imei_obj = imei.save(commit=False) imei_obj.mobile = item_obj imei_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({ 'success':False,'error_child_msg':item_formset.errors,'error_imei_msg':imei_formset.errors}) context = { 'item_formset':item_formset, 'imei_formset':imei_formset } return render(request,'storage/collection.html',context) but it only saves the last item entry and doesnt save imei , only its instance(from the item) will be saved these are my formsets mcollection = modelformset_factory( MobileCollection,form=MobileCollectionForm,fields= ['mobile','qnt','price'],can_delete=True,extra=1) imei_modelformset = modelformset_factory(Imei,form=ImeiForm,fields= ['imei'],extra=1,can_delete=True) const addNewRow = document.getElementById('add-more') const totalNewForms = document.getElementById('id_form-TOTAL_FORMS') addNewRow.addEventListener('click',add_new_row); function add_new_row(e){ if(e){ e.preventDefault(); } const currentFormClass = document.getElementsByClassName('child_forms_row') const countForms = currentFormClass.length const formCopyTarget = document.getElementById('form-lists') const empty_form = … -
Django Project - 'urlpatterns' = (syntax error - cannot assign to literal)....Please advise?
Django Project - 'urlpatterns' = (syntax error - cannot assign to literal)....Please advise? -
The included URLconf 'web_project.urls' does not appear to have any patterns in it
My Customer Apps urls.py ''' from django import urls from django.urls import path from django.urls.resolvers import URLPattern from .import views URLPattern = [ path('', views.base ,name= 'customer-base'), path('Hall/', views.Hall ,name= 'customer-Hall'), path('Food_item/', views.Food_item ,name= 'customer-food'), path('About_us/', views.About_us ,name= 'customer-about'), ] ''' My web_project urls.py ''' from django.contrib import admin from django.urls import path, include from django.urls.resolvers import URLPattern URLPattern = [ path('admin/', admin.site.urls), path('base/', include('customer.url')), ] ''' errors that are showing ''' Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\urls\resolvers.py", line 600, in url_patterns iter(patterns) TypeError: 'module' object is not iterable The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\Nawaf Bhatti\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\Nawaf Bhatti\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Nawaf Bhatti\Desktop\New\env\lib\site-packages\django\utils\functional.py", line 48, … -
How to using two parameters in delete method of class GenericViewSet in Django
I'm newbie Django How can use 2 params on my url with delete method on django 3 My url config: API_VERSION = os.getenv('API_VERSION') API_ROOT = "grpz/" router = routers.DefaultRouter(trailing_slash=False) router.register(r'^groups/(?P<group_id>.)/users/(?P<user_id>.)', group_views.DeleteGroupViewSet) schema_view = get_schema_view( title='next_blog', renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer]) urlpatterns = [ path('admin', admin.site.urls), path('api_auth', include( 'rest_framework.urls', namespace='rest_framework')), path('docs', schema_view, name='docs'), path(API_ROOT, include(router.urls)), ] My class viewsets: class DeleteGroupViewSet(viewsets.GenericViewSet): queryset = Groups.objects.all() serializer_class = GroupSerializer permission_classes = (AllowAny,) def destroy(self, request, group_id, user_id): try: # user_id = self.kwargs['user_id'] # group_id = self.kwargs['group_id'] user = Users.objects.filter(user_id=user_id).first() if user is None: return Response({ 'msg': 'User is not exist', }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: user_owner_role_in_group = GroupHasUsers.objects.filter( group_id=group_id, user_id=user_id, role__name='owner' ) if user_owner_role_in_group.count() == 0: return Response({ 'msg': 'User is not a owner role' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: Groups.objects.filter(id=group_id).delete() return Response({'msg': 'success'}, status=status.HTTP_200_OK) except Exception as e: return Response({ 'msg': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) Thanks all !