Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
define quantity for each selected item in the same time
i have tried a lot to get an answer for my problem i'm working on a restaurant order management system , and apart of the system is a point of sale at the same time(for cashier) , when a customer visit to the restaurant , the cashier be able to fill a receipt,for example (3 pizza with 2 sandwich) models.py class Product(models.Model): name = models.CharField(max_length=50) price = models.PositiveIntegerField(default=1) def __str__(self): return self.name class Order(models.Model): id = models.AutoField(primary_key = True) products = models.ManyToManyField(Product ,through='ProductOrder') @property def total(self): return self.productorder_set.aggregate( price_sum=Sum(F('quantity') * F('product__price'), output_field=IntegerField()) )['price_sum'] class ProductOrder(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE , null=True,blank=True) ordering = models.ForeignKey(Order, on_delete=models.CASCADE , blank=True) quantity = models.IntegerField(default=1) #to make a new instance from order,but doesnt make! def create_order(sender, instance, **kwargs): instance.ordering.save() pre_save.connect(create_order,sender=ProductOrder) views.py class ProductOrderCreate(CreateView): form_class = ProductOrdering model = ProductOrder template_name = 'create_product_order.html' success_url = '/orders/' def form_valid(self,form): form.instance.ordering = Order.objects.order_by('-pk')[0] return super(ProductOrderCreate,self).form_valid(form) if the signal(pre_save) worked fine and after select a product,creating another field automatically(not formset) it will solve the problem i asked alot everywhere but still but still not solved , please someone help me out i much appreciate -
Why my javascript/ajax script is not executing?
I have: {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), success: function(json) { console.log(json); } }); }); }); } </script> {% endblock content %} I get the json response from the server side fine but don't know why I can not show it in console or why is this still redirecting me. I mean why my script is not executing. This is in my header of base.html that is inerithed from. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> What is happening? -
How to get Sum with group by in Django query
I am trying to get Sum of my quantity with the group by product_id but it returns multiple records. I am working on Django and trying to get sum with group by so. I try with annotate and values. productinventory_ds = ( ProductInventory.objects.filter(product_id=product_id) .values("product_id") .annotate( instock_quantity_s=Sum("instock_quantity"), delivered_quantity_s=Sum("delivered_quantity"), ) ) But instead of giving one product id and sum of all the quantity. this query returns multiple results with the same product id. -
How to Handle Case When Item Does Not Exist
I have a simple for loop which iterates through all objects in a local database. For each object, I reference a presalesEngineer and pass that ID to an API call to retrieve a JSON response. However, there are records in the database for which there is no value for presalesEngineer. When this is the case, the empty string throws a HttpError when a bad URL is passed to the API call. How can I handle when presalesEngineer does not exist, so the API is not passed an empty value? views.py objects = Opportunity.objects.all() for object in objects: if object.presalesEngineer: presales_engineers = [cwObj.get_member_by_id(object.presalesEngineer) for object in objects] else: presales_engineers = 'None' -
Django: CI/CD, BitBucket Pipelines and VPS
Is it possible to have CD set up for BitBucket repo, so that once the code is commited/merged into dev branch, tests are run in BitBucket(or other) cloud, and if tests pass, git pull is triggered on VPS as well as python manage.py commands? -
Django Forms - Is 'readonly' safe to use?
I created a form in Django. In this form, there is a field that must not be edited by the user, because the default value of the form must be sent to my database as it is. I come up with the following solution, but after making some research, i've come to find that using readOnly is generally not a good idea. Can someone clarify me on this? Should i go with another solution? tst = forms.CharField( initial='//value to be sent to the db without being touched', widget=forms.TextInput(attrs={'readonly':'readonly'})) -
PostgreSQL database design for Django real estate website
I'm working on a real estate website, and am struggling to define a design for my DB. Database needs to store Properties, attributes, property category/subcategory, and have them be linked all together. I could easily solve said problem by hard-coding property categories/subcategories in code, but would like to have it be more dynamic. Now, I want to have categories table having ID and category title, then subcategories table having ID, title and ID of a category it belongs to, so a rather basic manytoone relationship. I also need a more dynamic approach to attributes, so that I have one table, with ID, title and subcategory_id, where I'll limit attributes so that they can only be used for properties in certain subcategories. With this said, I'm having an issue figuring out how would I form a table for properties, so that it stores all the properties and its attribute/value pairs. NOTE: I'm doing this in Django. -
Service unavailable django rest framework api
I am trying to build a Django Restframework API. The endgame of this API is to calcualte indicators againt a Vectorwise database and return them to the user. The user gives a date and a store number and the response of the API would be the gross sales for that particular date, the comparable date of the previous year and the progression of sales between the two dates. The store number is of type DECIMAL in the database and the date is of type ANSIDATE. I calculate the comparable date from one table and then use the value of the date and date_comparable to calculate the sales for the entered store number from another table. The code for my views is as follows: class WebIndicators(APIView): """ Use to calculate indicators relevant to gross sales indicators for comparable dates """ serializer_class = DateInputSerializer @swagger_auto_schema(query_serializer=serializer_class, operation_id="Retrieve gross sales web indicators.", responses={200: WdcOutputSerializer, 204: "No Content", 400: "Bad Request"} ) @cache_response(key_func=calculate_cache_key_get) def get(self, request, *args, **kwargs): input_serializer = self.serializer_class(data=request.query_params) input_serializer.is_valid(raise_exception=True) sql = "select dat_refprev from dtm.dim_time where dat_ref = '" + input_serializer.data['date'] + "'" store = input_serializer.data['store'] try: df = select_vector(sql, DB_CONNECTOR) except Exception: raise ServiceUnavailable() if df is None: raise ServiceUnavailable() if … -
How to change slug if same string is stored in it?
I am working with slug on my model. Although, the entries for slug are not unique. When I try to go to a url containing slug, it says get() returned more than one object and I understand that it is because the entries are not unique. How am I supposed to change the slug a bit, if identical entries occur? model class Cabin(models.Model): centre_name = models.ForeignKey(Centre, on_delete=models.CASCADE ) code = models.CharField(max_length=8, unique=True, default=unique_rand) total_seats = models.IntegerField(blank='False') category=models.CharField(max_length=100, default=False) booked_date=models.DateField(blank='False') released_date=models.DateField(blank='False') price=models.IntegerField(blank=False, default=None) slug = models.SlugField(unique=False,default=None,blank=True) objects = UserManager() def save(self, *args, **kwargs): self.slug = slugify(self.category) super(Client, self).save(*args, **kwargs) -
How to test class method which use class object
I want to mock only part of class methods and assert result with call_args_list but I'm struggling with mock in this case. I tried many different approaches but still I'havent figured how I can write this unittest.od. I'm aware that my current solution at this moment this test doesn't check anything except PASSED status. from unittest import mock from unittest.mock import call from django.db import models, transaction class MyModel(models.Model): @classmethod def my_method(cls, arg1, arg2): with transaction.atomic(): my_model, _ = cls.objects.get_or_create(arg1=arg1, defaults={'arg1': arg1, 'arg2': arg2}) my_model.save() def test_my_method(): MyModel = mock.MagicMock() MyModel.objects.return_value.get_or_create.return_value = MyModel(arg1='arg1', arg2='arg2') MyModel.my_method('arg1', 'arg2') assert MyModel.call_args_list == [call(arg1='arg1', arg2='arg2')] I'll be very glad if someone could tell how I can test this function it correctly. -
Why to not delete your Django project and clone it back from Github again?
I have been working on a Django project for a few days. I made the most recent commit to Github just a couple of days ago. Up until this point, everything in my project was working great. After that, I made a few unnecessary changes to my project and nothing was running fine. So, I moved the entire project to some other folder on my computer and cloned it again from my Github repository. I thought everything would run fine but I couldn't be more wrong. Now, whatever changes I would make to the models.py file wouldn't show in the database at all. Why did this happen? How did I solve the problem? I deleted the Github cloned version and brought my old project back to the same directory on my computer. I deleted the database completely and re created it and then used these commands-"python manage.py makemigrations" and "python manage.py migrate". -
Behave-django - UNIQUE constraint failed when trying to load users in fixtures
I'm trying to behave with django, thanks to the behave-django integration. That's pretty great, and I'm using Selenium too, tu run my test cases. But I can't figure how fixtures really works. It failed when I have many scenarios. I've created a fixtures files with everything I need, including two users, with the django dumpdata command line. I load it on the behave environment file. Here is my environment.py file from behave import register_type from selenium import webdriver from django.core.management import call_command register_type(String=lambda text: str(text)) register_type(Int=lambda text: int(text)) register_type(List=lambda text: [w.strip() for w in text.split(',')]) def before_all(context): context.fixtures = ['data/fixtures.json'] context.browser = webdriver.Chrome() def after_all(context): context.browser.quit() def django_ready(context): context.django = True For the first Scenario, everything works fine, but when it try to run the second scenario, it fail with a UNIQUE constraint failed : python manage.py behave --lang=fr Creating test database for alias 'default'... Feature: Workflow management # features/workflow.feature:1 @fast Scenario: Do something # features/workflow.feature:4 Given an authenticated user # features/steps/users.py:4 0.620s And the object "1" # features/steps/context.py:4 0.000s And the page "settings" is displayed # features/steps/navigation.py:8 3.070s Then the trash icon is displayed # features/steps/workflow.py:4 0.036s When he click on the trash icon # features/steps/workflow.py:14 0.052s And he … -
Djago files are appear if i write in browser
i have a problem if i write sitename.com/manage.py in browser manage.py will be download. I'm trying to setup on plesk panel not only specific files but also every files such templates/xx.html it will appear {{code}} code. My guide is; https://www.plesk.com/blog/guides/django-hosting-latest-plesk-onyx/. where am I making a mistake -
Filebased caching in Django is not working
I have a django app up and running. The app connects to an s3 bucket and creates an imprint of the objects in s3 onto a psql db. Using some forms i am able to download relevant objects to a single folder called queried_data. I want to cache this folder to retain contents for a certain time etc. etc. This is my settings.py file. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/home/clyde/Downloads/new/automatic_annotator_tool/queried_data', 'TIMEOUT': '30', 'OPTIONS': { 'MAX_ENTRIES': 5 } } } CACHE_MIDDLEWARE_ALIAS = 'default' CACHE_MIDDLEWARE_SECONDS = 60 CACHE_MIDDLEWARE_KEY_PREFIX = 'uvlearn' MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ..... ] I expect the cached folder to: a. sync with the db after certain time b. purge all data if it is stale. Any help would be appreciated.... TIA -
Problem in displaying objects from ForiegnKey in Django
I am having two models Patient and Ipd, Patient can have multiple Ipd. I am trying to get Patient Info in IpdForm but don't know where I am getting wrong I have already tried "qs = Ipd.objects.get(patient__id=patient_id)" , "qs = Ipd.objects.filter(patient__id=patient_id)" but nothing worked models.py : class Patient(models.Model): name = models.CharField(max_length=200); phone = models.CharField(max_length=20); address = models.TextField(); Patient_id = models.AutoField(primary_key=True); Gender= models.CharField(choices=GENDER,max_length=10) consultant = models.CharField(choices=CONSULTANT,max_length=20) def __str__(self): return self.name class Ipd(models.Model): reason_admission = models.CharField(max_length=200, blank=False) presenting_complaints = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=False) date_of_admission = models.DateField(("Date"), default=datetime.date.today) patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=False,default = " ") def __str__(self): return self.patient.name forms.py : class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name','phone','address','Patient_id','consultant','Gender'] class IpdForm(ModelForm): class Meta: model = Ipd fields = ['patient','reason_admission','presenting_complaints', 'rooms','date_of_admission'] views.py: @login_required def ipd (request,patient_id): formtwo = IpdForm() qs = Ipd.objects.filter(patient__Patient_id=patient_id) if request.method=="POST": formtwo = IpdForm(request.POST) if formtwo.is_valid() : instance = formtwo.save(commit=False) instance.save else: return HttpResponse(formtwo.errors) else: formtwo = IpdForm() return render(request, 'newipd.html', {'a':qs,'form2':formtwo}) urls.py : url(r'^order/ipd/(?P<patient_id>\d+)/$', my_order.ipd, name='ipd'), html : <div class="card-panel"> <span class="blue-text text-darken-2">Name : {{ab.name}}</span> <br> <span class="blue-text text-darken-2">Phone : {{ a.phone }}</span><br> <span class="blue-text text-darken-2">Address : {{ a.address }}</span><br> <span class="blue-text text-darken-2">Gender : {{ a.Gender }}</span><br> </div> -
How To Clear self.add_error in Django if user clicks on browser back button?
I have a FORMVIEW where a user selects a value from a dropdown, and if they select the value, and click submit, it performs an HTTPResponseRedirect to a URL and all is well. If they forget to enter a value and click submit, they get an error message telling them to choose a value. I do a clean on the form to figure this out. This all works just fine. The issue is if the user gets an error message, then adds a value and then displays the desired output. If they then click the back button on the browser window after viewing the output, the error message is still displayed. I have been able to work around this by including a NeverCacheMixin to the form, but when the user clicks on the back button, they get an ugly Confirm Form Resubmission page. The user is just looking up a value, so maybe there is a better way to approach this? There are no updates or deletes involved, it's strictly a lookup on one page that does an HttpResponseRedirect to another. Here is my FORMVIEW... class AuthorLookupView(LoginRequiredMixin,FormView): form_class = AuthorLookup template_name = 'author_lookup.html' def form_valid(self, form): authorbyname = form.cleaned_data['dropdown'] return … -
Django Import Export export pk instead of name after using ForeignKeyWidget?
I am using django-import-export for exporting and importing data in csv. I have used example according to given doc of django-import-export. I have used: Python - version 3.7 django -version 2.2 django-import-export - 1.2.0 https://django-import-export.readthedocs.io/en/latest/api_widgets.html#widgets Django import-export display manytomany as a name instead of ids when exporting to csv models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book Name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True, on_delete=models.CASCADE) author_email = models.EmailField('Author Email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.BooleanField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) categories = models.ManyToManyField(Category, blank=True) def __str__(self): return self.name resources.py from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from .models import Person, Book, Author class PersonResource(resources.ModelResource): class Meta: model = Person class BookResource(resources.ModelResource): author = fields.Field( column_name='author', attribute='author', widget=ForeignKeyWidget(Author, 'name')) class Meta: model = Book fields = ('author__name', ) admin.py from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Book, Author, Category @admin.register(Book) class BookAdmin(ImportExportModelAdmin): pass @admin.register(Author) class AuthorAdmin(ImportExportModelAdmin): pass @admin.register(Category) class CategoryAdmin(ImportExportModelAdmin): pass I expect that while exporting data of books in csv, I will get name of author in author column but got pk. And … -
django-tables2 not displaying column titles
I'm generating a leaderboard using django-tables2 based on this model (in users/models.py): class CustomUser(AbstractUser): points = models.DecimalField( max_digits=20, decimal_places=2, default=Decimal('1000.00'), verbose_name='User points') In tables.py, I select username and points, and order by the latter: class UserTable(tables.Table): class Meta: model = CustomUser fields = ('username','points') order_by = '-points' template_name = 'django_tables2/bootstrap.html' In views.py, I have def leaderboard_list(request): table = UserTable(CustomUser.objects.all()) RequestConfig(request).configure(table) return render(request, 'leaderboard.html', { 'table': table }) Finally, this gets rendered in the leaderboard.html template with {% load render_table from django_tables2 %} and {% render_table table %}. The table renders fine, but without any column headers. I added the verbose_name to the points field of the CustomUser model in light of this suggestion, under the assumption that this should show by default (as per this), but to no avail. What am I doing wrong here? -
Processing JSON with AJAX from a search
I have: {% extends 'base.html' %} {% block content %} <form method="GET" action="{% url 'libros:buscar' %}" id="buscador-libros"> <div> <input type="text" , name="titulo" /> <input type="submit" value="Buscar" /> </div> </form> <script type="text/javascript"> $(document).ready(function() { $("#buscador-libros").submit(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr("action"), type: $(this).attr("method"), data: $(this).serialize(), success: function(json) { console.log(json); } }); }); }); } </script> {% endblock content %} I get the json response from the server side fine but don't know why I can not show it in console or why is this still redirecting me. What am I doing wrong? Edit: I add jquery in 'base.html' -
Python Django autocomplete light the results could not be loaded
I am trying to add autocomplete light to my project, but I am not able to. If I want to find anything in the form it says: The results could not be loaded, TypeError: 'bool' object is not callable. I am using Python version 3.7 and django-autocomplete-light version 3.3.5 The project is web app to track orders which are assigned to the users. to the mysite/settings.py I added: INSTALLED_APPS = [ 'dal', 'dal_select2', 'crispy_forms', 'myapp', to the mysite/myapp/urls.py I added: path('autocomplete/', login_required(views.OrderAutocomplete.as_view()), name="autocomplete"), to the base.html: <head> {% load staticfiles %} ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script> and to the new_order.HTML: <form method="POST"> {% csrf_token %} {{ form|crispy }} {{ form.media }} <input type="submit"> </form> To the mysite/myapp/views.py I added: class ObjednavkaAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated(): return Objednavka.objects.none() qs = Order.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs and to the mysite/myapp/forms.py I added: class OrderForm(forms.ModelForm): user_auto = forms.ModelChoiceField(queryset=Order.objects.all(), widget = autocomplete.ModelSelect2(url='autocomplete')) class Meta: model = Order fields = ["user_auto"] mysite/myapp/models.py: from dal import autocomplete class Order(models.Model): ... user = models.ForeignKey(MyUser, on_delete=models.CASCADE) class MyUser(models.Model): eid = models.CharField(max_length=7) I am sorry for posting so much code. If I try … -
what is wrong with the update function?
i have an update function that is written in django views and that must edit or update the data in the database based on the selected ID and display the data in the form in update page once the user finish the update and click edit it must take him to the list page where it shows the updated data. views.py def update(request,pk): #deny anonymouse user to enter the create page if not request.user.is_authenticated: return redirect("login") else: # dbEntry = suspect.objects.filter(pk =pk) dbEntry = suspect.objects.get(pk =pk) print( "db entry : ",dbEntry) if request.method == 'POST': fname = request.POST['FName'] dbEntry = suspect.objects.filter(pk = pk).update(suspect_name = fName) #INSERT INTO TABLE VALUES ....... dbEntry.save() #to save into DB return render(request,'blog/update.html', {"dbEntry":dbEntry}) update.html {% extends "base.html" %} {% load static %} {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/linesAnimation.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/input-lineBorderBlue.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/dropDown.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/home.css' %}"> <link rel="stylesheet" type="text/css" href="{% static '/css/meta-Input.css' %}"> <meta name= "viewport" content="width=device-width, initial-scale=1.0"> <script type="text/javascript" src="{% static '/js/jquery-3.1.1.min.js'%}"></script> <title>Welcome</title> </head> <body> <div class="lines"> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div> <div class="line"></div><div class="line"></div><div class="line"></div> </div> <form method = "POST" enctype="multipart/form-data"> {% csrf_token … -
How to link guest and user checkout together?
I'm very new to Django and I'm confused with the checkout. I have the "accounts" app for user to enter their profile and I want to link it with the checkout but also include guest checkout. Right now I'm good to the guest-checkout but I cant link the user info from "accounts" app to the checkout. The error says " IntegrityError at /usercheckout/ NOT NULL constraint failed: accounts_profile.user_id " accounts/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=255, default='') last_name = models.CharField(max_length=255, default='') email = models.EmailField(default='none@email.com') birth_date = models.DateField(default='1999-12-31') address = models.TextField(default='') mobile = models.CharField(max_length=255, default='') def __str__(self): return self.user.username def __str__(self): return 'Order {}'.format(self.id) def create_profile(sender, **kwargs): if kwargs['created']: profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) orders/models.py class Order(models.Model): first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) email = models.EmailField() address = models.CharField(max_length=150) postal_code = models.CharField(max_length=30) city = models.CharField(max_length=100) mobile = models.IntegerField(default=0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created', ) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) orderu = models.OneToOneField(Profile, on_delete=models.CASCADE) product = models.ForeignKey(Product_info, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * … -
How to change the url password_reset link in django?
I have a users app and I have links in urlpatterns but the problem is whenever I click on the Forgot Password link, instead of going to password_reset which I have set it leads me userspassword_reset/ url. userspassword_reset/ is a password reset page in admin page but I want it to be in custom page. path('users', include('django.contrib.auth.urls')), path('password_reset/',auth_views.PasswordResetView. as_view(template_name='users/password_reset.html') path('password_reset_done/', password_reset_done, name='password_reset_done') It should send me to this page {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {%csrf_token%} <fieldset class="form-group"> <legend class="border-bottom mb-4" style="font-size: 50px"> Reset Password</legend><br> {{form|crispy}} </fieldset><br> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Send Confirmation Link</button> </div> </form> </div> <br> {% endblock %} -
Server Error (500) when change database user password
i changed database user password and I got this error "Server Error (500)" what should i do ? [debug=False] in production -
How to pass detail url inside the list in DRF
Here i am trying to do CRUD operations with the django-rest framework and the following code works fine also but the one thing i want to change is i want to give the detail url inside the list..How can i do it ? urls.py path('create/',CategoryCreateAPIView.as_view(),name='category-create'), path('list/',CategoryListAPIView.as_view(),name='category-list'), path('detail/<int:pk>/',CategoryDetailAPIView.as_view(),name='category-detail') views.py class CategoryCreateAPIView(generics.CreateAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] class CategoryListAPIView(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] class CategoryDetailAPIView(generics.RetrieveUpdateDestroyAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer permission_classes = [IsAdminUser] with the list url it displays the data like this.which is fine. HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 3, "next": null, "previous": null, "results": [ { "id": 1, "name": "category1", "description": "description", }, { "id": 2, "name": "category2", "description": "description", ...................... But when i have to go for the details of id 2 then i have to enter /category/detail/1/ and then i can view the deatils of that id.Is there any solution so that i can pass my detail url inside the every id in the list? The result i want is : HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 3, "next": null, "previous": null, "results": …