Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangochannelsrestframework problem with elastickbeanstalk and @model_observer
I have a consumers in which there is tracking of model changes using @model_observer. I subscribe to the event via @action and track its changes, everything works perfectly locally, the model has changed, I immediately received a change. But as soon as I try to put it on aws elastic beanstalk, I can subscribe/unsubscribe, but I don't get changes about events, although I see that the session is not broken. I thought that the problem was in queues or sessions, but I checked this together with technical support, they told me that everything was working correctly and the connection was made correctly. Maybe you know at least in which direction I should look and dig? Just in case, I summarize: everything works correctly locally, when uploading to the server, only subscribe to the event / unsubscribe from the event works, but for some reason the changes do not work my consumer.py with @model_observer my django.conf my Procfile: web: gunicorn --bind :8000 --workers 3 --threads 2 settings.wsgi:application websocket: daphne -b 0.0.0.0 -p 5000 settings.asgi:application I watched redis, I watched DB, cleaned up sessions -
client.post is not passing the FK
Hope someone can help me out here, I am trying to test a post method on an API, but the post method is not working as expected. When I pass the payload to the post method, the points and de code fields are loaded but the shopper and card fields, which are both Foreing Keys, are not loaded and a null value is passed, as they are required fields I ended up getting an error. I did check, and the values for self.shopper.pk and self.card.pk are correct. MYCARDS_URL = reverse('mycards:mycards-list') def test_create_mycards(self): """Test creating a mycards""" payload = { 'shopper': self.shopper.pk, 'card': self.card.pk, 'points': 0, 'code': "code", } res = APIClient().post(MYCARDS_URL, payload) I did check to see if was something related to my serializer, but it is all good as you can see: class MycardsSerializer(serializers.ModelSerializer): """Serializer for cards.""" class Meta: model = MyCards fields = ['id', 'shopper', 'card', 'updated', 'created'] read_only_fields = ['id', 'created'] class MycardsDetailSerializer(MycardsSerializer): """Serializer for card detail view.""" class Meta(MycardsSerializer.Meta): fields = MycardsSerializer.Meta.fields + [ 'points', 'code'] Here is also my viewset which seems to be ok: class MycardsViewSet(viewsets.ModelViewSet): """View for manage card APIs.""" serializer_class = serializers.MycardsDetailSerializer queryset = MyCards.objects.all() authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def … -
Django - can't delete rows when migrating backwards
I have a problem. I implemented a migration to create another option on my model (add the preview textchoice) and implemented a RunPython method to create rows on a table that matches my requirements. This works. The part that doesn't work is the reverse code. I simply query and filter the instances that I want to delete and try to delete them. In doing so, I get this weird error: Unapplying applications.0012_alter_mediatype_name...Traceback (most recent call last): File "/usr/local/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/usr/local/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/__main__.py", line 39, in <module> cli.main() File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 430, in main run() File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher/../../debugpy/../debugpy/server/cli.py", line 284, in run_file runpy.run_path(target, run_name="__main__") File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 321, in run_path return _run_module_code(code, init_globals, run_name, File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 135, in _run_module_code _run_code(code, mod_globals, init_globals, File "/root/.vscode-server/extensions/ms-python.python-2022.20.2/pythonFiles/lib/python/debugpy/_vendored/pydevd/_pydevd_bundle/pydevd_runpy.py", line 124, in _run_code exec(code, run_globals) File "/code/ews/manage.py", line 22, in <module> main() File "/code/ews/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 98, in wrapped res = handle_func(*args, **kwargs) File … -
Django media files 404 not found
I am creating my application where I need to upload an image, I created an input tag in html, but through this tag the files are not transmitted in the right way, but through the admin panel the images are loaded as neededenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description here I tried almost all the options that I found -
Error 403 when I try to access an uploaded image in Django with Nginx
When I upload some images together with a total size of about 10MB, I get a 'PermissionError: [Errno 1] Operation not permitted' error when I try to see them. How can I set my media folder to securely accept uploads and downloads from my users? I have a server configured with Django, Nginx and Gunicorn, so I tried to increase the client_max_body_size value in Nginx configuration file but no results. -
Django: Reverse for 'thread' with arguments '(1,)' not found. 1 pattern(s) tried: ['(?P<forum_id>[0-9]+)/(?P<thread_id>[0-9]+)/\\Z']
`I have tried to use two primary key at urls.py path but when I am using that and in template I cannot access that second primary key. Like: forum/1/2 2 cannot be accessed. it show error.` **urls.py **path('<int:forum_id>/<int:thread_id>/', views.thread, name='thread'), views.py `def forum(request,forum_id): forums = get_object_or_404(ForumModel, id=forum_id) threads = ThreadModel.objects.filter(forum=forums) context={'forums':forums,'threads':threads} return render(request,'forumdetail.html',context) def thread(request, thread_id): thread = get_object_or_404(ThreadModel, id=thread_id) posts = PostModel.objects.filter(thread=thread) context={'thread':thread,'posts':posts} return render(request,'threaddetail.html',context) ` template \ {% for thready in threads %} {{ thready.title }} {% endfor %} `` -
How to pass context object from a template to a view in django?
In search results page,a list of experts with their name and some other details are displayed.The name and the details are accessed from a context object "expert" that has been passed to search results page.Beside each search result I also generated a "save" button .When the user clicks on the save button,I need to save the individual expert data to a database.How do I send this "expert" context object from the search results page to a view so that I can then save it to the database? Here is the search result page: Here is part of the code of the for the search results: You can see I tried to create a hidden form with a button to send the context object to a view but it's not working.How do I create the button so that when the user clicks "save" button the url sends the context "expert" to a view? I tried to create a hidden form with a button to send the context object to a view but it's not working -
How can i pass a json param in get method (drf)?
class getAlarmlogsFilterByDistincts(APIView): permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): column_name = request.data['column_name'] #just an idea, dont works distincts_list = request.data['distincts_list'] #just an idea, dont works column_values = [Alarmlog.objects.filter(**{column_name: x}) for x in distincts_list ] serialized_response = AlarmlogSerializer(column_values) return Response(serialized_response.data, status=status.HTTP_200_OK) My view is more or less like this. I need to receive a string in column_name and a list in distincts_list (maybe in json format). What i tried: class AlarmlogsFilterByDistinctsSerializer(serializers.Serializer): distincts_list = serializers.ListField() column_name = serializers.CharField() class getAlarmlogsFilterByDistincts(CreateAPIView): permission_classes = (IsAuthenticated,) serializer_class = AlarmlogsFilterByDistinctsSerializer def post(self, request, *args, **kwargs): column_values = columnFilter(request.data['column_name'], request.data['distincts_list']) response_serialized = serializers.serialize('json', column_values) print(response_serialized) return Response(response_serialized, status=status.HTTP_200_OK) i've tried to use post method, but my response come out as a string: "[{\"model\": \"alarms.alarmlog\", \"pk\": 26, \"fields\": {\"created_at\": \"2023-01-12T17:06:19.016Z\", \"updated_at\": \"2023-01-12T17:06:19.016Z\", \"name\": \"string43\", \"description\": \"string\", \"severity\": \"low\", \"type\": \"string\", \"period\": \"string\", \"value\": \"string\", \"reference\": \"string\", \"source\": 2147483647, \"third_party_id\": \"string\", \"device\": \"string\", \"extra_content\": {}, \"occurred_at\": \"2023-01-12T16:29:39.055Z\", \"equipment\": 7}}, {\"model\": \"alarms.alarmlog\", \"pk\": 27,... ps. sorry my english -
Celery, RabbitMQ removes worker from consumers list while it is performing tasks
I have started my celery worker, which uses RabbitMQ as broker, like this: celery -A my_app worker -l info -P gevent -c 100 --prefetch-multiplier=1 -Q my_app Then I have task which looks quite like this: @shared_task(queue='my_app', default_retry_delay=10, max_retries=1, time_limit=8 * 60) def example_task(): # getting queryset with some filtering my_models = MyModel.objects.filter(...) for my_model in my_models.iterator(): my_model.execute_something() Sometimes this task can be fininshed less than a minute and sometimes, during highload, it requires more than 5 minutes to finish. The main problem is that RabbitMQ constantly removes my worker from consumers list. It looks really random. Because of that I need to restart worker again. Workers also starts throwing these errors: SSLEOFError: EOF occurred in violation of protocol (_ssl.c:2396) Sometimes these errors: consumer: Cannot connect to amqps://my_app:**@example.com:5671/prod: SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)'). Couldn't ack 2057, reason:"RecoverableConnectionError(None, 'connection already closed', None, '')" I have tried to add --without-heartbeat but it does nothing. How to solve this problems? Sometimes my tasks takes more than 30 minutes to finish, and I can't constantly monitor if workers were kicked out from rabbitmq. -
How to redirect to another view with arguments and 'cannot unpack non-iterable Listing object' django
Essentially what I am trying to do is allow a user to delete their own comments and simply refresh the page with all the data with that page loaded in from my 'view' view. However, I'm not sure about the best way to go about this as my view function has multiple variables in its context that I cannot access from my 'delete_comment' view. Also I keep running into an error when I try to access a given listing through a foreign key relationship and I get the error 'cannot unpack non-iterable Listing object' even though there is a listing associated with each comment. Here is everything associated with what I am trying to accomplish. views.py def view(request, listing_title): listing = Listing.objects.get(title=listing_title) # If someone is logged in user = request.user if user.id != None: try: watchlist = PersonalWatchList.objects.get(user=request.user) watchlist_listings = watchlist.listings.all() except: watchlist = None watchlist_listings = None return render(request, "auctions/listing.html", { "listing": listing, "watchlist": watchlist, "watchlist_listings": watchlist_listings, "comments": Comment.objects.filter(item=listing).order_by('-date_created') }) else: return render(request, "auctions/listing.html", { "listing": listing, "comments": Comment.objects.filter(item=listing).order_by('-date_created') }) def delete_comment(request, comment_id): comment_details = Comment.objects.get(id=comment_id) # item is None? Supposed to be of type 'Listing' auction = comment_details.item listing = Listing.objects.get(auction) listing_title = listing.title Comment.objects.get(id=comment_id).delete() # Need … -
Django DB delete filtered Objects
I'm trying to delete a user's all related messages. All messages sent by all users are located in a Message Model. So, to delete a specific user's messages only, I have to filter this Message.Model and sort it by user. def clear(request): user_msg = request.user relative_message = Message.objects.filter(user=user_msg) Message.objects.filter(id=relative_message).delete() My code is not working and gives me a Value Error: The QuerySet value for an exact lookup must be limited to one result using slicing. -
In django, admin.py file, while providing link to other page, the reverse function from django.urls module, is not working. showing models not found
enter image description here #this is my code enter image description here #this is my problem I'm facing. despite everything's ok in models.py file. -
Reverse Proxy for Django App 404 Not Found
I am following this guide to try show this url www.mycompany.com/testblog instead of www.mycompany.com:8000/testblog These are my current config files setup <VirtualHost *:80> ServerAdmin webmaster@localhost ServerName website.com ServerAlias www.website.com DocumentRoot /var/www/website.com Redirect permanent / https://website.com/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> ` <VirtualHost *:443> ServerAdmin webmaster@localhost ServerName website.com ServerAlias www.website.com DocumentRoot /var/www/website.com SSLEngine on SSLCertificateFile /etc/ssl/certs/website.com.cer SSLCertificateKeyFile /etc/ssl/private/website.com.key SSLCertificateChainFile /var/www/website.com/SSLCert/SSLIntermediateCertificate.cer ProxyPreserveHost On ProxyPass /testblog https://website.com:8000/testblog ProxyPassReverse /testblog https://website.com:8000/testblog </VirtualHost> However, when I run my server and try to access the URL www.mycompany.com/testblog I get a 404 Not Found error -
Download pdf file Django
views.py The download function using an API to convert a page to pdf using the URL. The pdf is saved in the project folder but i want it to be downloaded using HttpResponse and if possible not saved in the folder but a variable instance in code pdf=file.write(response.content). def downloadpdf(request, feedback_id): apiKey = '*****************' resume = Personal_Details.objects.get(feedback_id=feedback_id) response = requests.post( 'https://api.restpdf.io/v1/pdf', headers = { 'X-API-KEY' : apiKey, 'content-type': 'application/json' }, json = { "output": "data", "url": "https://github.com/chryzcode" } ) if response.status_code == 200: with open(f'{resume.resume_name}.pdf', 'wb') as file: file.write(response.content) return redirect('Resume', feedback_id=feedback_id) else: print("There was an error converting the PDF") -
Which is better Python vs PHP
As a newbie which is better for speed and back end development between PHP and Python As a newbie which is better for speed and back end development between PHP and Python -
Django-Oscar - Address Book not working on shipping-address
I'm having this problem that I mentioned in the title and I've been trying to fix it all morning, I've done some tests to find out where the error is coming from, I found out where it came from, but when I get to the file, I don't see any errors... As you can see, the user is logged in, but he cannot find an address for this user, since I have already registered one. See the code: {% extends "oscar/checkout/checkout.html" %} {% load i18n %} {% block title %} {% trans "Shipping address" %} | {{ block.super }} {% endblock %} {% block checkout_nav %} {% include 'oscar/checkout/nav.html' with step=1 %} {% endblock %} {% block checkout_title %}{% trans "Shipping address" %}{% endblock %} {% block order_contents %}{% endblock %} {% block shipping_address %} <div class="col-sm-12"> <div class="sub-header"> <h2>{% trans "Where should we ship to?" %}</h2> </div> {% if user.is_authenticated %} <p>User logged in</p> {% if addresses %} <p>Addresses: {{ addresses }}</p> <h3>{% trans "An address from your address book?" %}</h3> <div class="choose-block"> <div class="row"> {% for address in addresses %} {% block select_address_form %} <div class="col-sm-6 d-flex"> <div class="card card-body bg-light"> <address> {% block select_address_fields %} {% for … -
How to make the inventory decrease by 1 book when I borrow from the library, and increase by 1 when I return the book?
In the Book model, I made 2 methods to call them in the Borrowing field, but I haven't figured out how exactly to do it. And it is especially not clear how to connect the logic of returning the book. In the Borrowing model, there is only the actual_return_date field, when it is filled in, 1 should be added to the inventory, I think so. I tried to change the create method but it didn't work. model Book: from django.db import models class Book(models.Model): COVER_CHOICES = [("HARD", "Hard cover"), ("SOFT", "Soft cover")] title = models.CharField(max_length=255) authors = models.CharField(max_length=256) cover = models.CharField(max_length=15, choices=COVER_CHOICES) inventory = models.PositiveIntegerField() daily_fee = models.DecimalField(max_digits=7, decimal_places=2) class Meta: ordering = ["title"] def __str__(self): return ( f"'{self.title}' by {self.authors}, " f"cover: {self.cover}, " f"daily fee: {self.daily_fee}, " f"inventory: {self.inventory}" ) def reduce_inventory_book(self): self.inventory -= 1 self.save() def increase_inventory_book(self): self.inventory += 1 self.save() book/view.py from rest_framework import viewsets from book.models import Book from book.serializers import BookSerializer class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.all() serializer_class = BookSerializer book/serializers.py from rest_framework import serializers from book.models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ("id", "title", "authors", "cover", "inventory", "daily_fee") model Borrowing: from django.conf import settings from django.contrib.auth.models import AbstractUser from … -
Django: how to exclude certain results based on the values of other rows in the table?
I have a Django model called ProductPrice with a custom QuerySet as a manager: class ProductPriceQuerySet(models.QuerySet): def available(self, user): Group = apps.get_model("memberships", "Group") q = Q(title="Non-Member") if user.is_authenticated and user.member: q = q | Q(membership__members__user=user) return self.annotate( available=Case( When( membership_group__in=Group.objects.filter(q), then=True, ), default=False, ) ).order_by("stock", "-price") class ProductPrice(models.Model): stock = models.ForeignKey( StockManagement, on_delete=models.CASCADE, related_name="prices" ) membership_group = models.ForeignKey( "memberships.Group", null=False, blank=False, on_delete=models.PROTECT ) price = models.FloatField() objects = ProductPriceQuerySet.as_manager() This works for displaying available prices on the front end. But what I want to do is exclude the higher non-member price if the user is able to buy the item at a lower price point. What would be the best way to do this? I was thinking of another annotation like: display=Case( When( membership_group__in=Group.objects.filter(q) & ProductPrice.objects.filter( price__lt=F("price"), ), then=True, ), default=False, ) But this gives the error Cannot combine queries on two different base models. Is there an option to do this with SubQuery? Or would that be too expensive? -
Django complex filter through ManyToManyField and ForeignKey
I have a number of database tabels that are connected via manytomany and foreign key fields. from django.db import models class User(models.Model): name = models.CharField(max_length=20) class Bookings(models.Model): user = user = models.ForeignKey( User, blank=True, null=True, on_delete=models.SET_NULL) class Event(models.Model): bookings = models.ManyToManyField( Booking, related_name="event_bookings", blank=True) class ScheduleManager(models.Manager): def for_user(self, user): """ Returns a Schedule queryset for a given user object. Usage: user= User.objects.first() Schedule.objects.for_user(user) """ qs = self.get_queryset() #need to extend this to return Schedule qs return qs class Schedule(models.Model): event = models.ForeignKey( Event, on_delete=models.CASCADE ) objects = ScheduleManager() I would like to query the database to output a Schedule queryset for a given User object by calling Schedule.objects.for_user(User). I have been playing with a combination of prefetch_related and select_related to no prevail. I can get hold of the correct qs by using a bunch of chained queries and loops but its not the most elegant and I'm am hitting the db far too many times. Any help will be appreciated. -
OperationalError at /admin/store/product/
http://127.0.0.1:8000/admin/store/product/ it shows the error on that http://127.0.0.1:8000/admin/store/product/add/ links works perfect but whenever I try to add product it shows same error -
lookup was already seen with a different queryset. Django
I have a Quotes model referenced by the Comment model, which has a liked field (likes of the Comment model). I am trying to optimize the query so that there is no n+1 error, but this exception occurs. The problem is that I need to pull the user out of Comment and like, but it doesn't come out. How to do it? Table 'user' - it's ForeignKey Table 'liked' - it's ManyToManyField Views.py def get(self, request, *args, **kwargs): post = Quotes.objects.prefetch_related( Prefetch( 'quotes_comment', queryset=Comment.objects.select_related('user')) ).prefetch_related( Prefetch( 'quotes_comment', queryset=Comment.objects.select_related('liked') ) ) -
How to make filtering with SerializerMethodField()?
I'm creating table that show objects of a model and I have a SerializerMethodField that shows a value from a different table with same transaction ID. The problem is I'm using the serializers for the filtering table and chargeback is not working in there. How Can I make it filterable? Simplifying the code, a have this model: class PSerializer(serializers.ModelSerializer): ... chargeback = serializers.SerializerMethodField() def get_value(self, obj): ctransaction = CTransaction.objects.raw('SELECT * ' 'FROM ctransaction ' 'WHERE TRIM(mid)=TRIM(%s) ' 'AND TRIM(unique_id)=TRIM(%s) ' 'AND TRIM(num)=TRIM(%s) ' 'AND rc_code IN (%s, %s, %s)', [obj.mid, obj.unique_id, obj.num, '1', '1', '1']) if len(cs_transaction) > 0: return 'Yes' return 'No' -
Django Api-Key with unit test
I am trying to implement unit tests to an existing project, the existing project uses Api-Key's to access and authenticate against the Api endpoints. if I do the following via postman or command line: curl --location --request GET 'http://127.0.0.1:8000/api/user_db' \ --header 'Authorization: Api-Key REDACTED' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "test@testing.local" }' This will call the following view function and return the user details with the corresponding oid (json response) without error. from django.shortcuts import render from rest_framework_api_key.permissions import HasAPIKey from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from user_api.classes.UserController import ( GetBusinessUser, CreateBusinessUser, UpdateBusinessUser, DeleteBusinesssUser ) from celery.utils.log import get_task_logger import environ logger = get_task_logger(__name__) env = environ.Env() class ProcessUserRequest(APIView): permission_classes = [HasAPIKey |IsAuthenticated ] def get(self, request): logger.info("Get Business User Request Received") result = GetBusinessUser(request) return Response(result["result"], content_type='application/json charset=utf-8', status=result["statuscode"] This additionally calls the following shortened function: def GetBusinessUser(request) -> Dict[str, Union[str, int]]: logger.info(f"Processing Get Username Request: {request.data}") valid_serializer = ValidateGetBusinessUserFormSerializer(data=request.data) valid_serializer.is_valid(raise_exception=True) username = valid_serializer.validated_data['username'] return BusinessUser.objects.filter(username=username).first() As I wish to make unit test cases to ensure I can validate prior to deployment, I have implemented the following in the modules tests.py file: from rest_framework.test import APITestCase, APIClient from rest_framework_api_key.models import … -
500 internal server error while accessing hx-requests in Django project
I am working on a Django project to create a dynamic form using HTMX using a YouTube video.. As I am clicking "Add" button to add a form, no form gets added.. and as I inspect the browser console, I get the following error: GET http://127.0.0.1:8000/businesscase/htmx/project-form/ 500 (Internal Server Error) lr @ htmx.org@1.8.5:1 (anonymous) @ htmx.org@1.8.5:1 i @ htmx.org@1.8.5:1 Response Status Error Code 500 from /businesscase/htmx/project-form/ St @ htmx.org@1.8.5:1 ee @ htmx.org@1.8.5:1 Q @ htmx.org@1.8.5:1 fr @ htmx.org@1.8.5:1 o.onload @ htmx.org@1.8.5:1 load (async) lr @ htmx.org@1.8.5:1 (anonymous) @ htmx.org@1.8.5:1 i @ htmx.org@1.8.5:1 I tried to search a lot in Google to get rid of this error, but unfortunately all I received was to refresh browser, clear cache etc which I did but the problem persists.. I'd really appreciate of any quick solution here.. many thanks.. -
We have created django app , I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code
We have created django app , I am making test script for my api but I have getting AssertionError: 401 != 201 , I am giving sample code error :- Traceback (most recent call last): File "C:\Abhishek\Git\taskManagement\tests.py", line 108, in test_auth_user_can_create_project self.assertEqual(response.status_code, status.HTTP_201_CREATED) AssertionError: 401 != 201 views.py class Projects(APIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] """ To create the project """ def post(self, request): request.data['created_by'] = request.user.id request.data['username'] = request.user.username serializer = ProjectSerializer(data=request.data) if not serializer.is_valid(): print(serializer.errors) return Response({ 'success': False, 'errors': serializer.errors, 'message': _("something is wrong") }) serializer.save() return Response({ 'success': True, 'Project': serializer.data, 'message': _("Project create successfully") }) tests.py def test_auth_user_can_create_project(self): client = APIClient() data = { "project_name": "Test project testscript", "project_description": "test project desc", } response = self.client.post('/api/project/', data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED)