Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to mock the bound context of a celery task?
How do I mock the bound context, or celery task id? Given a celery task like: @app.task(queue="abc", bind=True) def some_task(self, some_number: int): print(self.id) # how to mock this attribute access? Simple test case: from django.test.testcases import TestCase class SomeTest(TestCase): def test_some_task(self): some_task.delay(123) I tried: @patch("celery.app.base.Celery.task", return_value=lambda x: x) I also tried: class MockResult(dict): def __getattr__(self, x): return self[x] ... def test_some_task(self): cls = MockResult({"id": "asdf"}) bound_some_task = some_task.__get__(cls, MockResult) bound_some_task(123) Related: Python: Bind an Unbound Method? https://docs.python.org/2/howto/descriptor.html -
list is not updating when item is removed
I'm writing a service for my front-end to consume an update service which has the following payload shape.However, when i add some skills eg:["Custom, "Plumbing"] on my skill_sub_category everything works perfect, but when I'm trying to remove a skill on the skill_sub_category the list is not getting updated.This is how my payload to update a custom_item looks like { "custom_items": [ { "item_name": "item_custom", "item_type": 1 , "measurement": "3m²" , "skill_sub_category": ["Custom", "Plumbing","Carpet"], "price" : "80", "client": "OTHER", "year":"2019", "items_source" : 0, "id": 582 }]} My implementation looks like this. def update_items(self, request, params={}, *args, **kwargs): """ :param request: :param params: :param args: :param kwargs: :return: """ logger.debug("Entering the gate of the update items function") logger.debug("** Params are being used ** :%s" % params) # print(params) logger.debug("** Params to be updated ** :%s" % params) for custom in params['custom_items']: item_name = custom['item_name'] item_type = str(custom['item_type']) item_type = ItemType.objects.get(pk=item_type) measurement = sanitize_data(custom['measurement']) # measurement = custom['measurement'].replace("", u"²") category = custom['skill_sub_category'] # year = custom['year'] # Frontenders do not want us to send through the year. which makes since client = str(custom['client']) client = Client.objects.get(name=client) # year = PriceList.objects.get(year=year) #so we commented that fee = custom['price'] items_source = custom['items_source'] get_sp = self.staff … -
Django with python-magic (libmagic) to verify uploaded files
I'm trying to save the mime type of an uploaded file in django. I don't need to reject certain types of files, I just need to keep track of the mime type of uploaded files. I'm doing this: class Foo(models.Model): document = models.FileField(upload_to="foo", null=False) file_type = models.CharField(max_length=14) def save(self, *args, **kwargs): print(self.document.read()) #confirms that the file exists, and this prints a load of bytes, so it's a bytes object filetype = magic.from_file(self.document.read()) self.file_type = filetype return super().save(*args, **kwargs) The problem is that filetype = magic.from_file(self.document.read()) throws the error: "ValueError: embedded null byte". The file is definitely not corrupt (in this case, it's a png, so I'm expecting image/png). from_file definitely seems to want a bytes object, and self.document.read() definitely produces bytes, so I'm not sure what the problem is... -
How to show the form to answer an issue if the user has not yet replied
I'm creating a quiz and would like a form to be shown only if the user has not yet responded. I'd like to know how I do it. {% if questao.resposta_set.all %} {% for resposta in questao.resposta_set.all %} {% if user == resposta.usuario|slice:":1" %} {{ resposta.resposta }} {% endif %} {% endfor %} {% else %} <form method="POST" class="post-form"> {% csrf_token %}{{respostaform.resposta}} <button type="submit" class="save btn btn-primary">Responder questão</button> </form> {% endif %} -
How would I approach implementing a "friend request" in React?
My goal is to implement some sort of friend/partner relationship between users. My backend is done in django, and my user model has a ManyToManyField to represent "friends". In terms of backend logic I believe to create such a relationship I would do something like user1.friends.add(user2) user1.save() which would set user2 as user1's friend and user1 as user2's friend. However, for the front end, how would I approach this? I plan to just have a view with a list of friend requests, and the option to accept/decline. Would my accept button be a PUT request to mysite/api/users? And if so, how would I prevent someone from spoofing a call and "forcing" people to be friends with them? (I think this falls under authenticating api calls or something) -
Parsing image from RSS feeds in django
I'm making a webpage to crawl rss feed contents in django. I'm unable to get image from rss feed using feedparser. Input rss feed is : http://feeds.bbci.co.uk/news/rss.xml I'm able to crawl publish date, title, description and link. How to crawl image and show it on webpage?? I have given my code below: Views.py from django.shortcuts import render from django.http import HttpResponse import feedparser def index(request): if request.GET.get("url"): url = request.GET["url"] feed = feedparser.parse(url) else: feed = None return render(request, 'rss/reader.html', { 'feed' : feed, }) reader.html {% if feed %} <h2>{{ feed.feed.title }}</h2> {% if feed.items %} {% for item in feed.items %} <div> <p>{{ item.published }}</p> <p>Headline: {{ item.title }}</p> <p>Link: <a href="{{ item.link }}">{{ item.title }}</a></p> <p>Description: {{ item.description }}</p> </div> {% endfor %} {% endif %} {% else %} <p>Add RSS feed</p> {% endif %} {% endblock %} -
How to fix UnicodeDecodeError in Python (Django Rest Framework template)?
I'm running a Django web app and creating a REST Api using Django Rest Framework. I've created a basic list/update view however when I go to the url, I get 'A server error occurred. Please contact the administrator.' and in the console: UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9735: ordinal not in range(128). I suspect this has something to do with a template, presumable DRF's as it says position 9735. This error isn't global as a form on a different part of my site is working perfectly. I'm not even sure what files to show but, models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): type = models.CharField(max_length = 30, null = True, default = "") class NewsPost(models.Model): title = models.CharField(max_length = 30, null = True, default = "") content = models.TextField(max_length = 1000, null = True, default = "") def __unicode__(self): return u'Title is %s' % self.title class Emergency(models.Model): title = models.CharField(max_length = 30, null = True, default = "") content = models.TextField(max_length=1000, null=True, default="") class EventUpdate(models.Model): type = models.CharField(max_length = 30, null = True, default = "") status = models.CharField(max_length = 300, null = … -
Pygal chart don't render properly in Django
I'm converting my flask app to django (I want to lern it by the way) and I got stuck on rendering pygal charts. On Django i see something like this: Chart problem I already search many sites including that ones that was proposed to me when i created this post and nothing helps :/ views.py # graphs charts = [] for item in firmy: gauge = pygal.SolidGauge(half_pie=True,width=500, height=500, inner_radius=0.70, show_legend=False) gauge.add(item['ID'], [{'value': item['low'], 'max_value': item['hi']}]) chart = gauge.render() charts.append(chart.decode('utf-8')) # tryied without decode too context = { 'test1': 'Site for cft/monitoring', 'firmy': firmy, 'sheet_names': sheet_names_to_choose, 'charts': charts, } return render(request, 'cft/monitoring.html', context) template {% for chart in charts %} <div id="chart" style="display: inline-block;"> <embed type="image/svg+xml" src={{ chart|safe }}/> </div> {% endfor %} I want to get rid of those errors and properly render charts. -
Can't connect to remote debug server with pydevd-pycharm
I have a Django project that I deploy with docker. I want to debug the project with Python Remote Debug. This I how I configured it according to the https://www.jetbrains.com/help/pycharm/remote-debugging-with-product.html Afterwards I launched the debugger and it said: Use the following code to connect to the debugger: import pydevd_pycharm pydevd_pycharm.settrace('0.0.0.0', port=3000, stdoutToServer=True, stderrToServer=True) Waiting for process connection... Afterwards I coppied the code to __main__ in manage.py Next I launched by docker with docker-compose up -d proj command After a while I saw logs from my container that says that: Could not connect to localhost: 3000 NoneType: None Traceback (most recent call last): File "/usr/local/lib/python3.6/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/usr/local/lib/python3.6/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 93, in sentry_patched_wsgi_handler environ, start_response File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/wsgi.py", line 69, in __call__ rv = self.app(environ, start_response) File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 92, in <lambda> return SentryWsgiMiddleware(lambda *a, **kw: old_app(self, *a, **kw))( File "/usr/local/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 157, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/site-packages/sentry_sdk/integrations/django/__init__.py", line 112, in sentry_patched_get_response return old_get_response(self, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in get_response response = self._middleware_chain(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/utils/deprecation.py", line 140, in __call__ response = self.get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line … -
Enabling CSS Modules in react with django as backend (SPA without create-react-app)
I am creating SPA that uses django as backend containing react app as the frontend. Having the backend and frontend separated I would use create-react-app for the frontend and then use 'eject' script to get access to webpack files that would have to be edited to enable css modules, however given I have not used create-react-app, I have no idea how to approach this subject. This is what I currently have: webpack.config.js module.exports = { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } } ] } }; I am trying to know how to appropriately configure webpack files in order to enable css modules. -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7fdd43044d90>
I'm doing a simple To-Do List in python 3.6.7 with django 2.0.7 in a virtualenv in Ubuntu,this error appeared when I created a folder called static with a css folder with styles(static/css/styles.css) I changed settings.py and added this: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] More later I created a link in my base.html to the styles: <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> And this is my console output: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4061a4bd90> Traceback (most recent call last): File "/home/mario/Dev/ToDo/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/mario/Dev/ToDo/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "/home/mario/Dev/ToDo/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/home/mario/Dev/ToDo/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/home/mario/Dev/ToDo/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/home/mario/Dev/ToDo/lib/python3.6/site-packages/django/core/checks/urls.py", line 101, in check_url_settings if value and not value.endswith('/'): AttributeError: 'tuple' object has no attribute 'endswith' -
How to POST data from HTML page to django REST API using python
I have one selection in HTML page. When I select something from that selection it should pass it to API and display as JSON. view.html <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("#mySelect").change(function(){ selected = $("#mySelect option:selected").text() $.ajax({ type: 'POST', dataType: 'json', contentType: 'application/json; charset=utf-8', url: 'http://127.0.0.1:8000/customer/view/', data: { 'fruit': selected }, success: function(result) { document.write(result) } }); }); }); </script> </head> <body> <form> <br> Select your favorite fruit: <select id="mySelect"> <option value="apple" selected >Select fruit</option> <option value="apple">Apple</option> <option value="orange">Orange</option> <option value="pineapple">Pineapple</option> <option value="banana">Banana</option> </select> </form> </body> </html> Django code: Inside views.py def view(request): if request.method == 'POST': data = request.body return HttpResponse(json.dumps(data)) When I open view.html page I get below error django server: -
Characters appear at the end of url (Django project)
In my Django website when clicking an image to go to other url, at the end of the url some random numbers appear, example "?x=27&y=18" Any way to remove these characters ? An example http://127.0.0.1:8000/Login/?x=11&y=25 When I try accessing the link wihout those characters it still works Code looks something like that url(r'^$', views.index, name='index'), url(r'^Login/$', views.login, name='login'), <input type="image" formaction="{% url 'desporto:login' %}" src="{% static 'desporto/login.png' %}"/> -
Is there any good reason to catch exceptions in unittest transactions?
The unittest module is extremely good to detect problems in code. I understand the idea of isolating and testing parts of code with assertions: self.assertEqual(web_page_view.func, web_page_url) But besides these assertions you also might have some logic before it, in the same test method, that could have problems. I am wondering if manual exception handling is something to take in account ever inside methods of a TestCase subclass. Because if I wrap a block in a try-catch, if something fails, the test returns OK and does not fail: def simulate_requests(self): """ Simulate requests to a url """ try: response = self.client.get('/adress/of/page/') self.assertEqual(response.status_code, 200) except Exception as e: print("error: ", e) Should exception handling be always avoided in such tests? -
Can I enable PointField in django without admin on windows?
I'm using my desktop PC (Windows 10) as my development environment. I need to add geographic coordinates to one of my tables. PostgreSQL has type point, and it seems that Django equivalent model is PointField I tried: from django.contrib.gis.db.models import PointField ... class ... location = PointField(blank=True) and I get the following error message: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal202", "gdal201", "gdal20", "gdal111", "gdal110", "gdal19"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. It seems I need to install gdal library. So I tried pip install gdal --user, and I got the following error message: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ and, MSVC++ needs admin rights to install, which I don't have. I downloaded osgeo4w-setup-x86_64.exe, but I need admin rights to install it. I tried pip install geos --user, which seems to run without errors, but it doesn't have any effect to my django app. I tried using django.contrib.postgres.fields.ArrayField, but it doesn't work with postgreSQL's point type Any suggestions, what can I do? -
Django: Can I check if a model instance matches a filter without filtering all model instances
I have an instance of a model. I have a queryset. Can I check if the instance matches a filter without filtering all model objects? Situation: I have a model Alpha, when this model is created I need to check if it matches a user defined filter which is stored in model Bravo. There will be many Alpha models and many Bravo models (filters). class Alpha(models.Model): test = models.CharField() class Bravo(models.Model): test = models.CharField() def get_qs(self): # These could be longish and complex, defined by users return Q(test=self.test) | Q(test=f"{self.test}a") # There will be many of these but I only want to check this instance a = Alpha(test="testa") # There will be many of these, I need to check if queries from get_qs match "a" b = Bravo(test="test") # Lots of Bravo, all need to be checked, unavoidable for bravo in Bravo.objects.all(): # Lots of Alpha, don't want to check them all # Just check "a" matches bravo.get_qs filter if a in Alpha.objects.filter(bravo.get_qs()): # Do something with "a" depending on which "b" pass My assumption is if a in Alpha.objects.filter(bravo.get_qs()) Will filter all Alpha objects. I don't want this because I don't need to check any other instances apart from … -
How do I create this queryset?
I have the following three models: class Category(models.Model): name = models.CharField(max_length=120) class Experiment(models.Model): name = models.CharField(max_length=50, unique=True) categories = models.ManyToManyField(Category) class Ad(models.Model): experiment = models.ForeignKey(Experiment, related_name='ads', on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.PROTECT, blank=True, null=True) I want to create a queryset which returns all ads where ad.category is in ad.experiment.categories. Some example data to talk through: Category: ['Cat1', 'Cat2', 'Cat3', Cat4', 'Cat5'] Experiment: [['Exp1',['Cat2','Cat3]],['Exp2',['Cat5','Cat1']]] Ad: [['Exp1','Cat4'],['Exp1','Cat2']] The queryset I'm hoping to create would only return the second ad because the ad's category is in the ad's experiment's category. Any help would be appreciated! -
How to execute independent tasks sequentially using Celery?
I have to schedule some tasks which seem very complex to run in parallel. They do not depend on the result of each other and the function expects 3 arguments. I already tried using chain, map and starmap methods. With chain I get this error: [2019-04-23 15:28:00,991: ERROR/PoolWorker-3] Task proj.apps.tasks.generate[112a7426-5ac3-4cd6-8416-5591c3c018a3] raised unexpected: TypeError('get expected at least 1 arguments, got 0',) Traceback (most recent call last): File ".../local/lib/python2.7/site-packages/celery/app/trace.py", line 367, in trace_task R = retval = fun(*args, **kwargs) File ".../local/lib/python2.7/site-packages/celery/app/trace.py", line 622, in __protected_call__ return self.run(*args, **kwargs) File ".../tasks.py", line 966, in generate return res.get() TypeError: get expected at least 1 arguments, got 0 Using map I cannot pass all the arguments and with starmap all the tasks are started simultaneously. [2019-04-23 15:48:00,991: INFO/MainProcess] Received task: generate[..] [2019-04-23 15:48:00,991: INFO/MainProcess] Received task: generate[..] [2019-04-23 15:48:00,991: INFO/MainProcess] Received task: generate[..] An example of the task: @shared_task def generate(field1, field2, field3=None): if field3 is not None: return field1 + field2 + field3 return field1 + field2 -
Reduce number of queries made to render list of items with same in-line editable field
While rendering a table of items, if the value for field X is not defined, it is rendered as a select element. Django makes a query for each select element and these can add up and cause delays in large tables. What is the best way to reduce the number of queries? views.py from rest_framework import renderers from rest_framework.response import Response class ItemViewSet(viewsets.ModelViewSet): queryset = models.Item.objects.select_related("bought_by") serializer_class= serializers.ItemSerializer filterset_fields = ("bought_by") renderer_classes = [renderers.JSONRenderer, renderers.BrowsableAPIRenderer, renderers.TemplateHTMLRenderer] def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if request.accepted_renderer.format == "html": items = self.get_serializer(queryset, many=True) return Response( { "items": items, "serializer": self.get_serializer(), "style": {"template_pack": "rest_framework/inline/"}, }, template_name="myapp/items_list.html", ) else: page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) items_list.html {% load static %} {% load rest_framework %} {% if items_info %} {% csrf_token %} <table id="Items_Table" class="table"> <thead> <tr> <th scope="col">Name</th> <th scope="col">Active</th> <th scope="col">Bought By</th> </tr> </thead> <tbody> {% for item in items %} <tr scope="row"> <td>{{ item.name }}</td> <td>{{ item.active }}</td> <td> <form action="{% url "myapp:item-detail" pair.item.pk %}" method="PATCH"> {% render_field serializer.bought_by style=style %} </form> </td> </tr> {% endfor %} </tbody> </table> {% else %} <p class="text-center">No items to show.</p> … -
Python/Django universal method in template without passing from view
I am starting to think this may not be possible as I cannot really conceptualize how it should be done, but I figured I'd ask before I edit hundreds of views to include a method call in my Django Project. I have a large project that has hundreds of views already. I am creating a tasks feature where users are able to complete specific tasks associated with the specific project application they are using. I have multiple interfaces: admin, management, onsite, etc... and each interface has their own navigation with a tasks link. What I want is to be able to change the color of this link if a user is in an interface where a task has yet to be completed. This is easy to check in each view and then I could universally render the correct color for the link based on a variable passed into the view, but that is extremely tedious with hundreds of views. I suppose I could add a filter in each interface to simplify this a bit, but is that the most simple solution? Here is an example of the method I want to be called in each interface's navigation: from objects_client.task_models.task_models import … -
cannot be able to produce proper tree structured output using self referencing using django rest framework
I have below Comment model and i want to implement the comment-reply functionality and in turn send the response as JSON using django rest framework. But in the reponse im getting the records even for 'parent not equal to None' in parent node. I want all the records whose having parent value should be displayed as only children. models.py: ''' class Comment(models.Model): name = models.TextField('comment') expression = models.ForeignKey('Expression', on_delete=models.CASCADE, related_name='expression') datecreated = models.DateTimeField('date created', auto_now_add=True) dateupdated = models.DateTimeField('date updated', auto_now=True) parent = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True, related_name='replied_to') class META: verbose_name_plural = "comments" ordering = ['-datecreated'] def __str__(self): return '{}'.format(self.name) ''' views.py: ''' class CommentViewSet(viewsets.ModelViewSet): comments = Comment.objects.all() queryset = comments serializer_class = CommentSerializer @list_route() def roots(self, request, *args, **kwargs): slug = kwargs.get('slug') expression = Expression.objects.get(author=request.user, slug=slug) queryset = expression.expression.filter(parent=None) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) ''' serializers.py: ''' class RecursiveSerializer(serializers.Serializer): def to_representation(self, value): serializer = self.parent.parent.__class__(value, context=self.context) # data = serializer.data.filter(parent!=0) return serializer.data class CommentSerializer(serializers.ModelSerializer): ''' Ref: http://voorloopnul.com/blog/representing-hierarchical-data-with-django-rest-framework/ ''' expression = serializers.CharField(required=False, read_only=True) replied_to = RecursiveSerializer(many=True, read_only=True) class Meta: model = Comment read_only_fields = ('id','datecreated', 'dateupdated',) fields = ('id','name','expression','datecreated','dateupdated','parent','replied_to') ''' Actual Result: ''' [ { "id": 1, "name": "new comment1", "expression": "My new expression1", "datecreated": "2019-04-07T17:52:52.784429+05:30", "dateupdated": "2019-04-07T17:52:52.784429+05:30", "parent": null, … -
How to debug django (logic) code using django shell in Visual Studio Code
I'm developing a django app including custom logic code using Visual Studio Code and I would like to debug my code while interactie via the django shell. Is this possible and if so, what debugging settings are required? -
How to fix MultiValueDictKeyError in rest api while authenticating user through facebook
While testing the facebook-authentication I am having the following problem Exception Type: MultiValueDictKeyError at /api/social/convert-token Exception Value: 'user_type' Request information: USER: AnonymousUser I am filtering the user in the following file def create_user_by_type(backend, user, request, response, *args, **kwargs): if backend.name == 'facebook': avatar = 'https://graph.facebook.com/%s/picture?type=large' % response['id'] if request['user_type'] == "driver" and not Driver.objects.filter(user_id=user.id): Driver.objects.create(user_id=user.id, avatar=avatar) elif not Customer.objects.filter(user_id=user.id): Customer.objects.create(user_id=user.id, avatar=avatar) When I am checking the Users table in admin page its creating the user but it is not creating the token. I am using Django==2.1.7 django-rest-framework-social-oauth2==1.1.0 -
What file is causing this Heroku error related to my template html file?
I'm having a bit of trouble deciphering the below error log that's appearing when loading my heroku-hosted django site. It appears to be triggered by the logic in my home.html template, but there's nothing in that file named uploader_post. Error log (can also be found by going to the site itself): home.html: <!-- templates/home.html --> <h1>Django Image Uploading</h1> <ul> {% for post in object_list %} <h2>{{ post.title }}</h2> <img src="{{ post.cover.url}}" alt="{{ post.title }}"> {% endfor %} </ul> -
Expected view StudentInforMigrateViewSet to be called with a URL keyword argument named "pk"
I am trying to copy one data from one model to another. i want to mapped all the student ang change their is_migrate status to True. Even thought the code looks ok. i am getting this error Expected view StudentInforMigrateViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. class StudentInforMigrateViewSet(viewsets.ModelViewSet): queryset = StudentInfo.objects.all() serializer_class = StudentInfoMigrateSerializer @action(detail=False,methods=['put','get']) def migrate(self,request): student_info=self.get_object() StudentInfo.objects.Migrate() student_info.is_migrate =True return Response(status=status.HTTP_200_OK)