Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to let Kombu consumer return or stream queued message
I am using Kombu and RabbitMq to queue the JPEG image data and stream or return the dequeued message back so it shows the video streaming on the webpage. Kombu consumer detects the message sent from the producer declared in detection.py file, but it does not save or return any message back so basically nothing is showing on the web. I read Kombu documentation but still I have trouble understanding the problem of my code. Any help would be greatly appreciated.. color_detection.py: The following code declares Kombu producer and publish the message to the exchange called video-exchange. from kombu import Connection from kombu import Exchange from kombu import Producer from kombu import Queue import numpy as np import cv2 import sys # Default RabbitMQ server URI rabbit_url = 'amqp://guest:guest@localhost:5672//' # Kombu Connection conn = Connection(rabbit_url) channel = conn.channel() # Kombu Exchange # - set delivery_mode to transient to prevent disk writes for faster delivery exchange = Exchange("video-exchange", type="direct", delivery_mode=1) # Kombu Producer producer = Producer(exchange=exchange, channel=channel, routing_key="video") # Kombu Queue queue = Queue(name="video-queue", exchange=exchange, routing_key="video") queue.maybe_bind(conn) queue.declare() ''' ML object detection algo(haarcascade)used to identify objects. the XML file consists of trained Haar Cascade models. ''' face_cascade = cv2.CascadeClassifier( 'accounts/personal_color/self_detection/haarcascade_frontalface_default.xml') # … -
Is there a way to display all user last_login and date_joined in django
I want to display all users information on admin dashboard with their last_login and join date I filter user date to display on template data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10] Profile model user = models.OneToOneField(User,default="1", on_delete=models.CASCADE, related_name="profile") image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' I want to do like -
I am gettitng post method not allowed
from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def contact(request): if request.method == 'GET': contact = ContactMe.objects.all() serializer = ContactMeSerializer(contact, many=True) return JsonResponse(serializer.data, safe=True) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ContactMeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.data, safe=False) I am getting post method not allowed, i don't know why i keep getting post method not allowed. The source code is below. Thanks from django.urls import path from .views import ListingView, SearchView, ListingsView, contact urlpatterns = [ path('contact/', contact) ] -
showing date from db in html date in django
How can i show date from db in django html template with input type date. As You can see if we use input type 'date'. we can see the below widget showing in html. But if i want to it to show date from DB in below picture. Is there anyway i can do? [![enter image description here][1]][1] Showing like this, so user can see the current date from DB and change if needed. forms.py class ProfileUpdateForm(ModelForm): #birthdate = forms.DateField( # input_formats=['%dd-%mm-%yyyy'], # widget=forms.DateInput(format='%dd-%mm-%yyyy', attrs={'type': "date"}) # ) class Meta: model = User fields = [ 'email', 'full_name', 'address', 'city', 'state', 'postcode', 'phone_number', 'birthdate', ] widgets = { 'full_name': Textarea(attrs={'cols': 35, 'rows': 1}), 'address': Textarea(attrs={'cols': 80, 'rows': 3}), 'city': Textarea(attrs={'cols': 35, 'rows': 1}), 'birthdate': forms.DateInput(format='%d %b %Y', attrs={'type':'date'}), } -
Add template variable into URL and satisfy reverse match
I found a way to inject variables into the URL per Django Template: Add Variable Into URL As Parameter, but my reverse match is not working. Do I need to use re-path and use regular expressions? Current url.py path('student/item/drilldown/<str:type>/<int:num>/',views.StudentBehaviorListView.as_view(),name='student_item_list_drilldown'), Original w/hard-coding: <a href="{%url 'registration:student_item_list_drilldown' type='grade' num=6%}"> With variable injection: <a href="{%url 'registration:student_item_list_drilldown'%}?type=grade&num={{i.grade}}">{{i.grade}}th Grade</a> Error message: NoReverseMatch at /registration/dashboard/ Reverse for 'student_item_list_drilldown' with no arguments not found. 1 pattern(s) tried: ['registration/student/item/drilldown/(?P<type>[^/]+)/(?P<num>[0-9]+)/\\Z'] -
Django Form "'ForwardManyToOneDescriptor' object has no attribute 'all'"
Hey so I'm having quite some problems. In effect trying to add a form to a home-page with options for a user to select based on a DB object. Then once submitted the page will refresh, and the form can be used again. Forms.py rom django import forms from django.forms import ChoiceField, ModelForm, RadioSelect from .models import command_node class command_form(ModelForm): class Meta: model = command_node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=command_node.host_id, widget=forms.Select( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, attrs={ 'class': 'form-control' }, choices=[ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ]) Models.py from tkinter import CASCADE from turtle import update from django.db import models class beacon(models.Model): host_id = models.BigAutoField('Id', primary_key=True) hostname = models.CharField('Hostname', max_length=200) internalIp = models.CharField('Internal-IP', max_length=200) externalIp = models.CharField('External-IP', max_length=200) current_user = models.CharField('Current_User', max_length=200) os = models.CharField('OS', max_length=200) admin = models.CharField('Admin', max_length=200) def __str__(self): return self.hostname class command_node(models.Model): host_id = models.ForeignKey(beacon, on_delete=models.CASCADE) current_commands = models.CharField('current_command', max_length=50, null=True) previous_commands = models.CharField('previous_commands', max_length=2000, null=True) def __str__(self): return str(self.host_id) views.py from django.shortcuts import render from django.http import HttpResponse from .models import … -
How to compare model fields using Django-filter package
I am trying to compare two model fields ma8, ma21 using Django-filter but I am not sure where to start. I think I should use F objects like in this answer: How to create a Django queryset filter comparing two date fields in the same model Below is my filters.py file from .models import TheModel from .tables import The TableTable import django_filters class MyFilter(django_filters.FilterSet): ma8__lt = django_filters.NumberFilter(field_name='ma8', lookup_expr='lt') ma8__gt = django_filters.NumberFilter(field_name='ma8', lookup_expr='gt') ma21__lt = django_filters.NumberFilter(field_name='ma21', lookup_expr='lt') ma21__gt = django_filters.NumberFilter(field_name='ma21', lookup_expr='gt') activeYN = django_filters.BooleanFilter(field_name='activeYN') # Here I want to be able to compare two model fields ma8, ma21 ex. ma8 > ma21 class Meta: model = TableData table_class = TableTable fields = ['ma8','ma21','activeYN'] -
Provide initial data for Django models from txt file
I have a .txt file with 3 columns (longitude, latitude, distance) and 40 million rows. These are the first lines of the file. -179.98 89.98 712.935 -179.94 89.98 712.934 -179.9 89.98 712.933 -179.86 89.98 712.932 -179.82 89.98 712.932 -179.78 89.98 712.931 -179.74 89.98 712.93 -179.7 89.98 712.929 -179.66 89.98 712.928 -179.62 89.98 712.927 Is there a way to provide these 40 million rows as initial data to this Django model? from django.db import models class Location(models.Model): longitude = models.FloatField() latitude = models.FloatField() distance = models.FloatField() -
How to annotate a QuerySet with the result of another QuerySet that uses a field of the first?
I'm currently working on the django backend of an app that allows users to place camera markers, each containing multiple cameras. The models I'm working with: class CameraMarkers(models.Model): # Field name made lowercase. marker_id = models.AutoField(db_column='Marker_ID', primary_key=True) # Field name made lowercase. city = models.CharField(db_column='City', max_length=25) # Field name made lowercase. num_of_cams = models.IntegerField(db_column='Num_of_Cams') # Field name made lowercase. zipcode = models.CharField( db_column='Zipcode', max_length=6, blank=True, null=True) # Field name made lowercase. street = models.CharField( db_column='Street', max_length=50, blank=True, null=True) # Field name made lowercase. house_num = models.CharField( db_column='House_num', max_length=10, blank=True, null=True) # Field name made lowercase. company = models.CharField( db_column='Company', max_length=12, blank=True, null=True) # Field name made lowercase. contact_name = models.CharField( db_column='Contact_name', max_length=50, blank=True, null=True) # Field name made lowercase. email_address = models.CharField( db_column='Email_address', max_length=50, blank=True, null=True) # Field name made lowercase. phone_num = models.CharField( db_column='Phone_num', max_length=15, blank=True, null=True) # Field name made lowercase. date_of_visit = models.CharField( db_column='Date_of_visit', max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'Camera Markers' class Cameras(models.Model): # Field name made lowercase. camera_id = models.AutoField(db_column='Camera_ID', primary_key=True) # Field name made lowercase. status = models.CharField(db_column='Status', max_length=20) # Field name made lowercase. view = models.TextField(db_column='View', blank=True, null=True) # Field name made lowercase. marker = models.ForeignKey( CameraMarkers, models.DO_NOTHING, db_column='Marker_ID') … -
Noreversematch: "url-name" not found a valid function or pattern name
I built a simple app to register and login users. Whenever a user registers, redirect to login, when login is successful, redirect to another page. But I get this error, reverse for "url-name" not found. "Url-name" is not a valid view function or pattern name. From the browser traceback it highlighted this code for me 47. return redirect ("videos") Local vars Below is the code. from django.urls import path from .views import Display_all,Registration_view,Login_view,logout_view,index_view urlpatterns = [ path('videos/', Display_all, name ="video"), path('register/',Registration_view, name ='registration'), path('login/', Login_view, name = "login"), path('logout/', logout_view, name = "logout") The views from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect, render from django.views import View from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .forms import RegistrationForm from django.contrib.auth import authenticate,login, logout from .models import Video def Display_all(request): all_videos = Video.objects.all() context = {"all_videos":all_videos} return render(request, 'videos/displayall.html', context) def Registration_view(request): form = RegistrationForm(request.POST or None) if form.is_valid(): form.save() return redirect("login") else: form = RegistrationForm() context = {"form":form} return render(request, 'profiles/registration.html', context) def Login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect ("videos") return render(request, 'profiles/login.html',{}) The simple login template <!DOCTYPE html> <html lang="en"> … -
ERROR: Invalid requirement: 'asgiref 3.5.2'
I am new to heroku and I wanted to deploy a simple app, when i push to heroku it is given me the error below. I check online unfortunately I dont find the right answer to it. ERROR GIVEN Enumerating objects: 73, done. Counting objects: 100% (73/73), done. Delta compression using up to 4 threads Compressing objects: 100% (71/71), done. Writing objects: 100% (73/73), 24.58 KiB | 719.00 KiB/s, done. Total 73 (delta 11), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.10.4 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.10.4 remote: -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ERROR: Invalid requirement: 'asgiref 3.5.2' (from line 1 of /tmp/build_44a6c2b3/requirements.txt) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to olakaymytodo. remote: To https://git.heroku.com/olakaymytodo.git ! [remote rejected] main -> main (pre-receive … -
how to Serialize multiple objects in Django
I have 2 models for admin and member positions and I would like to get both of the models in one API call to fetch the data on my front end. I tried to do many things so can some one help me :( class ClinetAdminPosition(models.Model): name = models.CharField(max_length=128, null=True) company = models.ForeignKey( to="Company", on_delete=models.CASCADE, related_name="admin_positions", null=True ) modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True) created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False) def __str__(self): return f"{self.name}" class ClinetMangerPosition(models.Model): name = models.CharField(max_length=128, null=True) company = models.ForeignKey( to="Company", on_delete=models.CASCADE, related_name="manger_positions", null=True ) modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True) created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False) def __str__(self): return f"{self.name}" I want to get both models' data from 1 API request to be like this: [ { "admin_positions": [ { "name": "test", "company": 1 }, { "name": "test2", "company": 1 }, { "name": "test3", "company": 1 } ], "manger_position": [ { "name": "test", "company": 1 }, { "name": "test2", "company": 1 }, { "name": "test3", "company": 1 } ] } ] -
Django CSRF not working on SSL(HTTPS), but working on local(linux), tried all things
Following is the Error i get : 403 : CSRF verification failed. Request aborted. When Debug = True : Reason given for failure: Origin checking failed - https://example.com does not match any trusted origins. Basic Checks : site is having valid working ssl browser is accepting cookie for this site In settings.py "CSRF_COOKIE_SECURE = True" is set In settings.py "django.middleware.csrf.CsrfViewMiddleware" is above other View Middleware I have tried many things, nothing works. It works perfectly on development environment -
How do I destructure an API with python Django and django-rest-framework?
I have a successfully compiled and run a django rest consuming cocktaildb api. On local server when I run http://127.0.0.1:8000/api/ I get { "ingredients": "http://127.0.0.1:8000/api/ingredients/", "drinks": "http://127.0.0.1:8000/api/drinks/", "feeling-lucky": "http://127.0.0.1:8000/api/feeling-lucky/" } but when I go to one of the links mentioned in the json result above, for example, http://127.0.0.1:8000/api/ingredients/ I get an empty [] with a status 200OK! I am learning and I would appreciate any tips on where I should focus on. Thanks in advance. -
filter Boto3 s3 file filter does not find file
I am trying to check if a file exists in boto3 with django before adding it to the django model session = boto3.Session( aws_access_key_id=env("AWS_ACCESS_KEY_ID"), aws_secret_access_key=env("AWS_SECRET_ACCESS_KEY"), ) s3 = session.resource( "s3", region_name=env("AWS_S3_REGION_NAME"), endpoint_url=env("AWS_S3_ENDPOINT_URL") ) bucket = s3.Bucket(env("AWS_STORAGE_BUCKET_NAME")) Then when I try to search the file: objs = list(bucket.objects.filter(Prefix="media/" + name)) It shows that it could not find the file with according to the name passed. Although when I do bucket.objects.all(), I find the file existing under media/NAME_HERE -
When I use Bootstrap to build a web apps by python but it didn't show me the correct page
enter image description here enter image description herecom/KF5ap.png -
template rendering works fine but when I use template inheritance it displays error
I tried the using {% include 'navbar.html'%} on room.html template both of them work fine and display the template but when I add {% include 'navbar.html'%} in room.html try to render it displays this error I adjust have also include the templates in the setting what seems to be the problem. The urls file in first app is from django.urls import path from . import views urlpatterns =[ path('',views.home), path('room/',views.room), path('navbar/',views.navbar), and the views file is like this from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'firstapp/home.html') def room(request): return render(request,'firstapp/room.html') def navbar(request): return render(request,'firstapp/navbar.html') def main(request): return render(request,'main.html') images of error displayed in Django and setting file [1]: https://i.stack.imgur.com/MH8fL.png error displayed in Django [2]: https://i.stack.imgur.com/Wh8Ot.png error displayed in Django [3]: https://i.stack.imgur.com/phUt0.png settings file -
Media Files and Static files not Displaying and working in Django
when deployed server then static files not working and media files not diplaying. 404 error here is the urls.py from django.views.static import serve import django from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path ('' , include('home.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and settings.py STATIC_URL = 'static/' STATIC_ROOT = '/usr/local/lsws/Example/html/demo/static' """STATICFILES_DIRS=( BASE_DIR / "static", )""" # Default primary key field type # https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = 'media/' MEDIA_ROOT = '/usr/local/lsws/Example/html/demo/static/media' CKEDITOR_UPLOAD_PATH = 'uploads' -
Strange Unterminated String literal error
I'm making a simple todo app with Django but the error Unterminated String literal is creating a lot of problems. I know there is no unterminated string literal but the error keeps arriving? What might be the cause? Line 11 is causing the trouble. -
Get 1,2,3,4,5 star average individually except from the main average
Suppose i have rated a user with 1 star 3 times, 2star 1times, 4star 4 times, 5star 10times.now from here anyone can find out overall average rating but how can i get the percentage of 1star,2star ,3star,4star and 5star from total rating #show it on a django way rating = Rating.objects.filter(activity__creator=u) one_star_count = rating.filter(star='1').count() two_star_count = rating.filter(star='2').count() three_star_count = rating.filter(star='3').count() four_star_count = rating.filter(star='4').count() five_star_count = rating.filter(star='5').count() total_stars_count = one_star_count + two_star_count+ \ three_star_count + four_star_count+ five_star_count -
unsuppoted operand type(s) for *: 'NoneType' and 'NoneType'
Helo everyone, am trying to compute unit price and the quantity from this table as follows class Marketers(models.Model): category =models.ForeignKey(Category, on_delete=models.CASCADE, null=True) name =models.CharField(max_length=50, null=True, blank =True) grade =models.CharField(max_length=50, null=True, blank =True) quatity_received = models.IntegerField(default=0, null=True, blank =True) unit_price =models.IntegerField(default=0, null=True, blank =True) customer = models.CharField(max_length=50, null=True, blank =True) date_received = models.DateTimeField(auto_now_add=True) date_sold = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.quatity_received * self.unit_price return total this is how i call it in my template <td class="align-middle text-center"> <span class="text-secondary text-xs font-weight-bold">{{ list.get_total }}</span> <p class="text-xs text-secondary mb-0">Overall Price </p> </td> this is the erro am receiving TypeError: unsupported operand type(s) for *: 'NoneType' and 'NoneType' please i need help. Thanks -
API request doesn't return results
I am trying to run an API request equivalent to following: curl -X POST "https://api.mouser.com/api/v1.0/search/partnumber?apiKey=*****" -H "accept: application/json" -H "Content-Type: application/json" -d "{ \"SearchByPartRequest\": { \"mouserPartNumber\": \"RR1220P-512-D\", }}" with this function: MOUSER_API_BASE_URL = 'https://api.mouser.com/api/v1.0' MOUSER_PART_API_KEY = os.environ.get('MOUSER_PART_API_KEY') def get_mouser_part_price(request, pk): part = Part.objects.get(id=pk) headers = { 'accept': 'application/json', 'Content-Type': 'application/json' } data = { 'SearchByPartRequest': { 'mouserPartNumber': part.part_number, } } url = MOUSER_API_BASE_URL + '/search/partnumber/?apiKey=' + MOUSER_PART_API_KEY response = requests.post(url, data=data, headers=headers) part_data = response.json() print(part_data) But for some reason I am getting zero results from the function, while curl returns a result. Where is the error? -
Image haven't showed (Django admin area)
Image not showing after adding to admin area. When I click on the image in the admin panel everything works correctly, but only until I reload the project. Also, after adding the picture (in the folder media/images) doubles. models.py class Offer(models.Model): name = models.CharField("ФИО", max_length=60, blank=True, null=True) nickname = models.ForeignKey(User,on_delete=models.SET_NULL, null=True) header_image = models.ImageField("Фотография", null=True, blank=True, upload_to="images/") price = models.IntegerField("Цена занятия") subject = models.CharField("Предметы", max_length=60) venue = models.ForeignKey(Venue, blank=True, null=True, on_delete=models.CASCADE) rating = models.IntegerField("Рейтинг преподавателя", blank=True) data = models.DateField("Сколько преподает", max_length=50, blank=True) description = models.TextField("Описание",blank=True) def __str__(self): return self.name urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') admin.py @admin.register(Offer) class OfferAdmin(admin.ModelAdmin): list_display = ("name", "header_image", 'price', 'subject', "nickname") ordering = ('name',) search_fields = ('name', 'subject', ) html <li><img src="{{ offers.header_image.url }}"></li> -
How Can I Integrate Flutterwave Paymwnt Gate Way with Django
I am working on a Django Project where I want to collect payment in Dollars from Applicants on the portal, and I don't know how to go about it. Though I have been following an online tutorial that shows how to do it but the result I am having is different with the recent error which says 'module' object is not callable. Remember that I have tested my configured environment and also imported it into my views on top of the page. Profile 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=255, 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=16, null=True) image = models.ImageField(default='avatar.jpg', upload_to ='profile_images') def __str__(self): return f'{self.applicant.username}-Profile' Education/Referee Model code: class Education(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null = True) qualification = models.CharField(max_length=60, choices=INSTITUTE, default=None, null=True) instition = models.CharField(max_length=40, null=True) reasons = models.CharField(max_length=100, null=True) matnumber = models.CharField(max_length=255, null=True) reference = models.CharField(max_length=100, null=True) refphone = models.CharField(max_length=100, null=True) last_updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return f'{self.applicant}-Education' Submitted Model code: class Submitted(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) … -
How to make custom serializer from model in django rest framework?
I want to make a custom serializer from a model. I want output like this: { 'name': { 'value': 'field value from model', 'type': 'String', # 'what the model field type like: String' }, 'number': { 'value': 'field value from model', 'type': 'Number', # 'what the model field type like: Number' }, 'type': { 'value': 'field value from model', 'type': 'Choice', # 'what the model field type like: Choice' 'options': ['Paved', 'UnPaved'] }, 'category': { 'value': 'field value from model', 'type': 'Choice', # 'what the model field type like: Choice' 'options': ['primary', 'secondary'] }, 'width': { 'value': 'field value from model', 'type': 'Number', # 'what the model field type like: Number' } } Here is my model: class Road(models.Model): name = models.CharField(max_length=250, null=True) number = models.CharField(max_length=200, null=True) type = models.CharField(max_length=100, null=True) category = models.CharField(max_length=200, null=True) width = models.FloatField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Here is the serializer code: class RoadSerializer(serializers.ModelSerializer): class Meta: model = Road exclude = ['created', 'updated'] Here is the view: @api_view(['GET']) def get_road(request, pk=None): queryset = Road.objects.all() road= get_object_or_404(queryset, pk=pk) serializer = RoadSerializer(road) return Response(serializer.data) put URL like this path(r'view/list/<pk>', views.get_road, name='road') How can I achieve that output? Which type of serializer is best to get …