Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.0.8 Field.disable UpdateView
For example I have a EntryUpdateForm that inherits from UpdateView that updates some data on a model. Now I'd like to disable certain fields. From the Django documentiation I'm not sure where exatcly to put the Field.disable attribute to disable a certain field on a form. forms.py class EntryUpdateForm(UpdateView): class Meta: model = Entry fields = ["material", "shape", "diameter", "taken_from", "moved_to", "quantity"] views.py class EntryUpdateView(LoginRequiredMixin, EntryUpdateForm): model = Entry fields = ["material", "shape", "diameter", "taken_from", "moved_to", "quantity"] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) I'm not even sure if it's possible to do this if I'm inheriting from the UpdateView, at least easly. -
Django: How to efficiently filter model property methods?
I've been looking for a way to efficiently filter Django model objects using the YourModel.objects.filter() method with property values. Django is unable to filter through property methods in this way. It's still possible with list comprehension: streams = [object for object in YourModel.objects.all() if object.property_method == 'value'] I've been told that this method isn't efficient because you still iterate through each object in the SQL table instead of the apparently more efficient SQL way. Really I'd like to know what the best way to do this would be. Here's my example models: # someapp/models.py from django.db import models class Platform(models.Model): name = models.CharField(max_length=50, null=True) def __str__(self): return self.name class Account(models.Model): platform = models.ForeignKey(Platform, on_delete=models.PROTECT) name = models.CharField(verbose_name="Account Name", max_length=100, null=True) profile_pic = models.ImageField(upload_to='profile_pictures', null=True, blank=True) def __str__(self): return self.name class Stream(models.Model): host = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Host") def __str__(self): return self.host.name @property def platform(self): return self.host.platform I'm thinking that it might just be best to make platform an attribute, but that kind of takes away the automatically adding part of it without external scripts. What's the most efficient way to filter Objects (in this case "Stream" objects) by platform and automatically populate? -
How to get response back from Django API to Calling HTML Page i am posting an image to Api?
How i can call an django Api from another django Project (or from any other project) and get the response back after some processing on the same calling page (the page from whcih i called the Api) i am calling the api from form action ....but api shows response in new blank page Here is API CODE: (//skipping some dode to avoide confusion) def IdealWeight(request): #defining a list of data to send back to html list_of_data=[] list_of_data.append(name) list_of_data.append(fatherName) list_of_data.append(registration) print(list_of_data) # outPut_Data = ast.literal_eval(list_of_data) # return render(request,'LibraryForm.html',{'data1':outPut_Data}) return JsonResponse(list_of_data,safe=False) i want list_of_data on the calling page in some variable. Here is my HTML Code from which i am calling the API: <form action="http://127.0.0.1:8000/idealweight/?image/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" class="form-control-file" name="image" onchange="readURL(this);" required> <input type="submit" class=" btn btn-primary" title="Process" value="Process" id="processButton"> </div> {{ data1 }} </form> From html page, I am sending a picture to Api (API build in Django) and from that i want to send an array or list of data extracted from image and want to show that on same html page....................from which i called the api how i can do that? hope i am clear what i want? -
pip freeze command aint working in my virtualenv instead it is showing this
(chinu) abitribe@yashmacbook chinu % pip freeze Traceback (most recent call last): File "/Users/abitribe/Desktop/chinu/bin/pip", line 8, in sys.exit(main()) File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/cli/main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/commands/init.py", line 104, in create_command module = importlib.import_module(module_path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/init.py", line 37, in import_module import(name) File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/commands/freeze.py", line 12, in from pip._internal.operations.freeze import freeze File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/operations/freeze.py", line 16, in from pip._internal.req.constructors import ( File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/req/init.py", line 12, in from .req_install import InstallRequirement File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/req/req_install.py", line 30, in from pip._internal.operations.install.wheel import install_wheel File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_internal/operations/install/wheel.py", line 25, in from pip._vendor.distlib.scripts import ScriptMaker File "/Users/abitribe/Desktop/chinu/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py", line 14, in from .compat import sysconfig, detect_encoding, ZipFile ImportError: No module named compat -
How can I implement service layer in Django?
I see in this article 1 and also in this video 2 that is very helpful to build your REST application in Django using a service layer because put your business logic in Model Layer or in View Layer isn't the best choice. Can you share with me some simple models of services in Django ? -
How to order the answers objects by their votes?
Here i want to order the question's answers by their votes. The higher voted answer will be at the top but if it has accepted answer then it will stay at top like in stackoverflow. How can i do it here ? views class DetailQuestionView(LoginRequiredMixin, View): template_name = 'post_detail.html' def get(self, request, **kwargs): question = get_object_or_404(Question, pk=kwargs['pk']) """checking if the current user has voted on the question or not""" q_voted = question.question_votes.filter(user=request.user, question=question).exists() """getting the list of answers which are voted by the current user""" answers = question.answers.all().order_by('votes') ## how ?? a_voted_list = [answer for answer in answers if answer.answer_votes.filter(user=request.user, answer=answer)] context = { 'question': question, 'voted': q_voted, 'a_voted_list': a_voted_list, 'answers': answers } models class Answer(CommonInfo): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') ans = models.TextField() user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='user_answers') is_accepted = models.BooleanField(default=False) class AnswerVote(CommonInfo): answer = models.ForeignKey(Answer, on_delete=models.CASCADE, related_name='answer_votes') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_votes_ans') -
Create django project with PyCharm
I am trying to create the Django project but it poped up a dialog with these messages. Can anyone help me why it happened? -
is there a way to create database from django manage command?
is there a way to create database from django manage command ? i want create a multitenant Application and need to generate dynamic database configuration for django manage command. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, **'another_generated_from_manage_command'**:{ 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } -
Problem of django-taggit with persian language
I am working with django and also I want to use django-taggit for tags but the problem is that for persian language(farsi language) when I use django-taggit I cannot use persian words because it has problems to use persian words as slug. What can I do? Does it has a solution or I have to create a Tagging system by myself for persian language? -
I'm Working on the RSS Feed in the django but it gives me an Error
So guys as you read earlier i'm working on the RSS Fedd in the django. i've done all the code but when i'm enter the url for any feed it gives me and error related that saying your code giving the None instead of HttpResponse and i don't know how to solve this please Help me. any help would be appricated. MY HTML CODE IS for BASE HTML== <!DOCTYPE html> <head> <title>Django RSS Reader</title> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> </head> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="/">Home</a> </ul> </nav> <body> {% block content %} {% endblock %} </body> </html> MY HTML CODE FOR READER.HTML PAGE {% extends 'reader/base.html' %} {% block content %} <br/> <form class="form-inline"> <div class="form-group mx-sm-3 mb-2"> <label for="inputPassword2" class="sr-only">Password</label> <input type="text" class="form-control" placeholder="paste link" name="url"> </div> <button type="submit" class="btn btn-primary mb-2">Search</button> </form> {% if feed %} <h2>{{ feed.feed.title }}</h2> {% if feed.entries %} {% for entry in feed.entries %} <div class="card"> <div class="card-header"> Feed </div> <div class="card-body"> <h5 class="card-title">Headline: {{ entry.title }}</h5> <p class="card-text">Description: {{ entry.description }}</p> <a href="{{ entry.link }}" class="btn btn-primary">Visit Link</a> </div> </div> <p>{{ entry.published }}</p> {% endfor %} {% endif %} {% … -
Pytest-Django Client User Login
I was wondering if someone can help figure out why it seems my user is not being logged in. import pytest from mixer.backend.django import mixer @pytest.fixture def strong_pass(): return "Str#410-P@55" @pytest.fixture def create_test_user(db, strong_pass): return mixer.blend('auth.User', username="JohnnyTest", password=strong_pass) @pytest.fixture def logged_in_client(client, create_test_user, strong_pass): test_user = create_test_user if test_user is not None: client.login(username=test_user.username, password=strong_pass) return client, test_user It makes the user fine and can reference him in other tests, but client doesn't seem to like the login. I have tried to replace the values in client.login to the exact strings and it still doesn't work. I have also tried force_login but still not working Any help would be appreciated -
Error "Expected table or queryset, not str " for form
I am building a private website for inventory management using python django, and i was creating a form to add items in my Item Model, till now I have redone my form code 2-3 times but am always getting stuck with same error "Expected table or queryset, not str" and have run out of ideas. here is my code, views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import Item, Tender from django.urls import reverse from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm, AddItemForm from .tables import ItemTable def add_item(request): if request.method == 'POST': form = AddItemForm(request.POST) if form.is_valid(): Item = form.save(commit = False) Item.item_updated = timezone.now() Item.save() return redirect("main:item_list") else: form = AddItemForm() return render(request, "main/item_list.html", {'form': form}) models.py: from django.db import models from datetime import datetime from django.contrib.auth.models import User class Item(models.Model): item_no = models.CharField(max_length=200, primary_key = True ) item_name = models.CharField(max_length = 200) item_quantity = models.CharField(max_length = 200, default = 0) item_description = models.TextField(blank = True) item_updated = models.DateTimeField("Item updated", default=datetime.now()) item_price = models.CharField(max_length = 100, default = 0) def __str__(self): return self.item_name forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from … -
Carousel with Bootstrap and Django
I am trying to implement a simple Carousel with Bootstrap in a Django project. Somehow the loop works but only the active is shown, I cant go to the next and prev image. The carousel-items are greyd out <!--Carousel--> <div class='row'> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% if labelimages %} {% for image in labelimages %} <div class="carousel-{% if forloop.first %}active{% else%}item{% endif %}"> <img class="d-block w-100" src="{{ image.url }}" alt="Third slide"> </div> {% endfor %} {% endif %} <div class="carousel-item"> <img class="d-block w-100" src="{{ image.url }}" alt="Third slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> -
Check constraint on secondary model with primary model data in Django
Question is about check constraint in Django. For example I have 2 models: class model_1(models.Model): date_range = DateRangeField() class model_2(models.Model): primary_model = ForeignKey( model_1, on_delete=models.CASCADE, related_name='secondary_model', ) date_range = DateRangeField() And I would like to create database check constraint in order to maintain following condition: – date_range of model_2 should be contained_by ('<@') date_range of model_1 Example: Correct (contained) (2012-01-01, 2014-01-01) contained by ('<@') (2010-01-01, 2016-01-01) Incorrect(not contained) (2012-01-01, 2014-01-01) contained by ('<@') (2013-01-01, 2016-01-01) Is it possible to create such check constraint? Thanks. -
Extended user profile model not saving to database
I've created a profile model and created the forms and views to use the extended user model feature, the only problem is the data doesnt save to the database and I cant see the newly create user in the admin site, below are the related files: models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) age = models.IntegerField(null=True) email = models.EmailField(max_length=20) dp = models.ImageField(upload_to='images/', default='default.jpg') country = models.CharField(max_length=20, null=True) joined = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['joined'] @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() views.py def signup_view(request): form = SignUpForm(request.POST) if form.is_valid(): user = form.save() user.refresh_from_db() user.profile.first_name = form.cleaned_data.get('first_name') user.profile.last_name = form.cleaned_data.get('last_name') user.profile.email = form.cleaned_data.get('email') user.profile.age = form.cleaned_data.get('age') user.profile.dp = form.cleaned_data.get('dp') user.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'milk/signup.html', {'form': form}) templates {% extends 'milk/base.html' %} {% block title %} {% endblock %} {% block content %} <h2>Sign up Form</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p … -
How can I Check username is available or not in DJango registration redux form using Ajax or JavaScript
How can I Check username is available or not without clicking the submit button in DJango registration redux form using Ajax or JavaScript And how I can recommend some username related to his username which one he wanted to use as username in the first attempt -
static() helper function django
urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Dears, where can I learn more about how this static() function process the two arguments passed? -
How do I use Wagtail App Pages to create dynamic pages from django model?
I have a django model of data for several locations that I need to generate pages from in wagtail. Like a blog, I need a listing page and detail pages. I followed this documentation: https://wagtail-app-pages.readthedocs.io/en/latest/index.html models.py from django.db import models from wagtail.core.models import Page from wagtail_app_pages.models import AppPageMixin from . import misc_options class Feature(models.Model): feature = models.CharField(max_length=50) description = models.CharField(max_length=300) class Meta: ordering = ['feature'] verbose_name = "Feature" verbose_name_plural = "Features" def __str__(self): return self.feature class Location(models.Model): template = 'locations/locations_list.html' name = models.CharField(max_length=30, null=True, blank=False) address = models.CharField(max_length=60, null=True, blank=False) city = models.CharField(max_length=25) state = models.CharField( max_length=2, choices=misc_options.STATES, null=True, blank=False) zipcode = models.CharField(max_length=5, null=True, blank=False) lat = models.CharField(max_length=50, null=True, blank=False) lon = models.CharField(max_length=50, null=True, blank=False) phone = models.CharField(max_length=10, null=True, blank=False) email = models.CharField(max_length=40, null=True, blank=False) places_id = models.CharField(max_length=100, null=True, blank=True) facebook_url = models.CharField(max_length=100, null=True, blank=True) google_url = models.CharField(max_length=100, null=True, blank=True) entity = models.CharField(max_length=10, null=True, blank=True) truck_url = models.CharField(max_length=100, null=True, blank=True) trailer_url = models.CharField(max_length=100, null=True, blank=True) supplies_url = models.CharField(max_length=100, null=True, blank=True) features = models.ManyToManyField(Feature) class Meta: # noqa ordering = ['name'] verbose_name = "Location" verbose_name_plural = "Locations" def __str__(self): return self.name class LocationPage(AppPageMixin, Page): template = 'locations/locations_list.html' url_config = 'location.urls' class Meta: # noqa verbose_name = "Locations List" verbose_name_plural = "Locations … -
Page not found (404) Django - generic.DetailView
Developing a project where have course, lesson and episode model. In episode model have videos. But the problem is when I rendering a template using generic.TemplateView the template is work but when I use the generic.DetailView then the error says "Page not found (404)". Can not understand the error. urls.py from django.urls import path from .views import ( CourseDetailsView, LessonEpisodeVideoView, ) urlpatterns = [ path('course_detail/<slug:slug>/', CourseDetailsView.as_view(), name='course-detail'), path('course/detail/video/<slug:slug>/', LessonEpisodeVideoView.as_view(), name='episode-video'), ] views.py when TemplateView class LessonEpisodeVideoView(TemplateView, LoginRequiredMixin): model = Courses template_name = 'courses/course_details.html' Working good. views.py when DetailView class LessonEpisodeVideoView(DetailView, LoginRequiredMixin): model = Courses template_name = 'courses/course_details.html' But changing TemplaeView to DetailView, got an error!! In HTML Hyperlink Tag: <a class="flex" href="{{ ep_context.get_absolute_episode_url }}">{{ ep_context.title }}</a> -
Login using REST APIs
I'm using a Django Rest Framework backend with a React frontend. I'm using Django Authentication for the logins and then posting the login details to the REST API in this format - { "id": 11, "employeeId": 0, "username": "admin1@________.in", "password": "pbkdf2_sha256$180000$W1yLUJ4XqRb0$YrvVoT3+QFcHp5Eh7PBq2LJS26xlztrb9W5k/IK41gY=", "first_name": "____", "last_name": "____", "user_type": "Admin", "created_at": "2020-06-28T20:59:39.721240", "previous_login": "2020-07-03T13:31:59.403874" }, { "id": 12, "employeeId": 1, "username": "admin2@________.in", "password": "pbkdf2_sha256$180000$ze6arinX0kyM$YdPn3tzT4lJf1EfHpBNfKqId6zxO76vf0chVhRUA2cU=", "first_name": "____", "last_name": "____", "user_type": "Admin", "created_at": "2020-06-28T21:36:30.537960", "previous_login": "2020-07-01T19:07:42.992369" }, I can't think of a way to distinguish which user had logged in from this and use it in React. I tried multiple methods - I tried to use the previous_login which updates when they login and compare that with timezone.now(), the issue with that came when another user logged in at the same time on a different computer and both the users showed up as logged in on the same homescreen. I then tried to store the time when they logged in and the time that the homescreen loaded in the React state which won't be changed. However, this also proved to be ineffective when I clicked on some buttons which take you to other parts of my website and come back to the homescreen. I tried … -
How to make protection from repeated POST request processing in Django?
I'm almost done coding comment section in my app, but I realize, after user post comment and refresh the page, comment duplicates, but it's not what I want. views.py def post_detail(request, pk): template_name = 'books/post-detail.html' book = get_object_or_404(Book, pk=pk) comments = book.comments.filter(active=True) new_comment = None # Comment posted if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): # Create Comment object but don't save to database yet new_comment = comment_form.save(commit=False) # Assign the current post to the comment new_comment.comment = book new_comment.username = request.user # Save the comment to the database new_comment.save() else: comment_form = CommentForm() context = {'book': book, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form} return render(request, template_name, context) -
Django - Save multiple versions of an Image
My application needs to save multiple versions of an uploaded Image. One high quality image and another one just for thumbnails use (low quality). Currently this is working most of the time but sometimes the save method simply fails and all of my Thumbnail images are getting deleted, especially then if I use the button at my form raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) app | ValueError: The 'postcover_tn' attribute has no file associated with it. -> See full trace here: https://pastebin.com/hgieMGet models.py class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField() content = models.TextField(blank=False) postcover = models.ImageField( verbose_name="Post Cover", blank=True, null=True, upload_to=image_uploads, ) postcover_tn = models.ImageField( verbose_name="Post Cover Thumbnail", blank=True, null=True, upload_to=image_uploads, ) published_date = models.DateTimeField(auto_now_add=True, null=True) def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) if self.postcover: if not (self.postcover_tn and os.path.exists(self.postcover_tn.path)): image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 500 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = image.resize((wsize, baseheight)) imageTemproaryResized.save(outputIoStream, format='PNG') outputIoStream.seek(0) self.postcover = InMemoryUploadedFile(outputIoStream, 'ImageField', "%s.png" % self.postcover.name.split('.')[0], 'image/png', sys.getsizeof(outputIoStream), None) image = Image.open(self.postcover) outputIoStream = BytesIO() baseheight = 175 hpercent = baseheight / image.size[1] wsize = int(image.size[0] * hpercent) imageTemproaryResized = … -
Implement simple-jwt-django-rest framework token authentication without password
My app does not required password as i want to login with phone and otp. I am trying to implement custom simple jwt token authentication which takes only phone number and not password. I am new to Django and I did check some links in stackoverflow and tried implementing the below way:- class CustomSerializer(TokenObtainPairSerializer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields[self.username_field] = serializers.CharField() del self.fields['password'] def validate(self,attr): print(attr) data = super().validate(attr) token = self.get_token(self.user) print (token) try: request = self.context["request"] print(request) except KeyError: pass request_data = json.loads(request.body) print(request_data) So here when validate method is executed,to goes to validate tokenobtainpairserializer init method which in turn calls init method of its parent class which is validating the password. So even if i am deleting passowrd field in my custom serializer, it still give me key-error of password. I tried to pass the keyerror but again it gets fail at request.body. I am stuck on this and not understanding how to implement simple jwt without password. -
Django passing a value from a template to another
I am new in Django and I want to use "datepicker" in my project. I do not know how can I apply the selected date. Scenario is taking date in one template and showing in another template for confirmation by user. Which way is better: 1- passing value from one template to another directly? 2- passing value from one template to another via views? If there is any link or example, I thank you. -
How to get request params in Django rest framework on ListCreateAPIView
I am creating a private message app with Django Rest Framework and Swagger for document the API. I am newbie on this framework and I not sure if ListCreateAPIView is the correct way to do that. I need the following endpoints: List all messages given the sender and the receiver. Post messages given the sender and the receiver. Delete messages given the sender and the receiver. My question is how to get the sender ID and the receiver ID from URL? Here is my code and any change on every part including Serializer and Model is welcome. Thanks in advance. class Message(models.Model): sender = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey( UserProfile, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) createdAt = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default=False) def __str__(self): return self.message class Meta: ordering = ('createdAt',) class MessageSerializer(serializers.ModelSerializer): """For Serializing Message""" sender = serializers.SlugRelatedField( many=False, slug_field='username', queryset=UserProfile.objects.all()) receiver = serializers.SlugRelatedField( many=False, slug_field='username', queryset=UserProfile.objects.all()) class Meta: model = Message fields = ['sender', 'receiver', 'message', 'createdAt'] class MessageViewSet(ListCreateAPIView): serializer_class = MessageSerializer queryset = Message.objects.all() def list(self, request, *args, **kwargs): queryset = Message.objects.all() serializer = MessageSerializer(queryset) print(self.request.data) print(kwargs) return Response(serializer.data) router = DefaultRouter() router.register('messages', MessageViewSet.as_view(), basename='messages') urlpatterns = [ path('', include(router.urls)), ]