Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
redirect to another page for script execution in django
I got a problem, I'm making a web for SqlServer Agent Jobs execution, and I got to type of Jobs, with parameters or without parameters (I added this attribute in my table with a boolean), so if my job got no paremeters executes normally, but if my job got parameters it redirects to another page where I can type the value of the parameters and then execute the job. I got my code byt it returns error "didn't return an Http.Response", can someone please tell me what I'm doing wrong? I'll leave some code below views.py #Job execution def ejecutar(request, job_name): print("Ejecutando el job") cursor = connection.cursor() job = Jobs.objects.get(job_name=job_name) if job.flag_params == 0: cursor.execute("EXEC msdb.dbo.sp_start_job '" + job.job_name + "'") return HttpResponse("""<html><script>alert("Job ejecutado");window.location.replace('/home');</script></html>""") else: #redirects to parameters.html redirect('parameters.html', job_name=job.job_name) if request.method == 'POST': #get job parameters parametros = Parametros.objects.filter(job_id=job.id) for parametro in parametros: #Update parameters in my table cursor.execute("UPDATE Jobs_parametros SET parameter_value='" + request.POST['parameter'] + "' WHERE parameter_name='" + parametro.parameter_name + "' AND job_id='" + str(job.id) + "'") cursor.execute("EXEC msdb.dbo.sp_start_job '" + job.job_name + "'") return HttpResponse("""<html><script>alert("Job ejecutado");window.location.replace('/home');</script></html>""") #Get Job List per User def insertar(request): #get user id who logged in user = Usuarios.objects.get(username=request.session['username']) #get jobs asigned to the … -
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" : "testuser@localhost" }' Everything works great, however when trying to add the Api-Key to the header in Unit tests I receive the following : 'detail': ErrorDetail(string='Authentication credentials were not provided.', code='not_authenticated')} AssertionError: 403 != 200 from rest_framework.test import APITestCase from rest_framework import status from django.urls import reverse import environ env = environ.Env() class GetUserTestCase(APITestCase): def test_get_user_account(self): getdata = { "username" : "testuser@localhost" } response = self.client.get(reverse('users_db'), data=getdata, **{ "HTTP_AUTHORIZATION": f"Api-Key {env('API_KEY')}" }) print(response.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data["username"],response.data["enc_password"],response.data["oid"]) Also tried with the following items: headers = { 'Authorization': f'Api-Key {env("API_KEY")}', 'Content-Type': 'application/json' } response = self.client.get(reverse('users_db'), data=getdata, headers=headers) AND self.client.credentials(HTTP_AUTHORIZATION=f"Api-Key {env('API_KEY')}") No joy so far, anyone else had this problem and find a way forward? -
How do I link different users to view the page differently?
hi if anyone is familiar with django, i'm working on how different group of users will be able to view different buttons, but i cant seem to make that work; my elif doesn't work, when i'm logged in to employee i'm able to view the buttons but when im logged in the inventory manager i can only view undefined user employee view inventory manager view below are my codes views.py def menu(request): user = request.user is_employee = request.user.groups.filter(name='employee').exists() is_inventorymanager = user.groups.filter(name='inventorymanager').exists() is_financialdirector = user.groups.filter(name='financialdirector').exists() is_vendor = user.groups.filter(name='vendor').exists() return render(request, 'app/menu.html', { 'is_employee': is_employee, 'is_inventorymanager': is_inventorymanager, 'is_financialdirector': is_financialdirector, 'is_vendor': is_vendor }) menu.html (interface) {% extends "app/layout.html" %} {% block content %} <div> <br /> {% if is_employee %} <h2>Employee Menu</h2> {% elif is_inventorymanager %} <h2>Inventory Manager Menu</h2> {% elif is_financialdirector %} <h2>Financial Director Menu</h2> {% elif is_vendor %} <h2>Vendor Menu</h2> {% else %} <h2>Undefined</h2> {% endif %} <br /> <table> {% if is_employee %} <tr><td> <form class="margintop" action='createpurchaseorder' method='GET'> <button type="submit" class="btn btn-info"> EMP | Create Purchase Order</button><br /> </form> </td></tr> <tr><td> <form class="margintop" action='createdeliveryorder' method='GET'> <button type="submit" class="btn btn-info"> VEN | Create Delivery Order</button><br /> </form> </td></tr> <tr><td> <form class="margintop" action='listview_po' method='GET'> <button type="submit" class="btn btn-info">EMP FM VEND | View … -
Django email backend and smtp configuration
I'm trying to use my Zoho account within my django project, in order to receive emails via contact forms. I also followed this guide: https://www.zoho.com/mail/help/zoho-smtp.html In the 'settings.py' file I wrote: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtppro.zoho.eu' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = '<domain name email>' EMAIL_HOST_PASSWORD = '<password>' and in views.py: def home(request): allTemplates = AllTemplates.objects.all() if request.method == 'POST': form = forms.ContactForm(request.POST) if form.is_valid(): body = { 'name': form.cleaned_data['name'], 'surname': form.cleaned_data['surname'], 'from_email': form.cleaned_data['from_email'], 'message': form.cleaned_data['message'], } mail_body = "\n".join(body.values()) try: send_mail("Generic contact", mail_body, '<domain name email>', ['<domain name email>'], fail_silently=False) except BadHeaderError: return HttpResponse('Ops, qualcosa è andato storto') form = forms.ContactForm context = {'form': form, 'allTemplates': allTemplates, 'allTemplates_length': len(allTemplates)} return render(request, 'home.html', context) N.B. in 'send_email' I entered my email address twice to test I also tried to use ssl EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtppro.zoho.eu' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = '<domain name email>' EMAIL_HOST_PASSWORD = '<password>' but nothing, I don't receive any email. Is there anyone who has already gone through it or who can direct me towards some document or guide to study? Thank you very much in advance. -
Got AttributeError when attempting to get a value for field `name` on serializer `BusinessSerializer`
I am getting this error. when trying to save a record using rest AttributeError at /business/ Got AttributeError when attempting to get a value for field name on serializer BusinessSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'name'. why is trying to find name field on user object when business object already has that field views.py class BusinessViewSet(viewsets.ModelViewSet): serializer_class = BusinessSerializer queryset = Business.objects.all() def create(self,request): serializer = BusinessSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) businessRecord = serializer.save() return Response({ "business": BusinessSerializer(businessRecord, context=self.get_serializer_context()).data, }) models.py class Business(models.Model): businessOwner = models.OneToOneField(User,blank=True,null=True,on_delete=models.CASCADE) # first name, last name, username, email, password etc. present in this model name = models.TextField() mobileNumber = PhoneField(help_text='Mobile Number') businessLocation = models.PointField() created = models.DateTimeField(auto_now_add=True) businessType = models.CharField(max_length = 30,choices = BUSINESS_TYPE_CHOICES,default = 'Business') address = models.TextField() businessCategory = models.ManyToManyField(Category, related_name='Bcategory', blank=True) hashTags = models.ManyToManyField(HashTag, related_name='Bhashtag', blank=True) socialMediaAccountLink = models.URLField(max_length=400, blank=True,null=True) socialMediaType = models.CharField(max_length=30, choices=SOCIAL_MEDIA_TYPE_CHOICES, default='Instagram') class Meta: indexes = [ models.Index(fields=['businessLocation', 'businessType','name','businessOwner']), ] serializers.py class BusinessOwnerSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password','first_name','last_name') extra_kwargs = … -
Django model not saving POST ajax request
My Django model isn't saving response even after getting a POST request. I'm trying to create a basic like , dislike counter and I'm having trouble updating my like value in database. Although I'm sending POST response to to function likePost in view.py I can't seem to update like_votes field in my Post model. My model class Post(models.Model): post_text = models.CharField(max_length=1000) pub_date = models.DateTimeField('date published') like_votes = models.IntegerField(default=0) dislike_votes = models.IntegerField(default=0) def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) def __str__(self): return self.post_text My ajax function <script type="text/javascript"> var likebtn = document.getElementById("likebtn"); likebtn.addEventListener('click', buttonClikckHandler); var num1 = 1; var like = parseInt("{{post.like_votes}}"); var new_l = like; function buttonClikckHandler() { console.log("clicked like"); const xhr = new XMLHttpRequest(); var new_l = like + num1 % 2; num1 = num1 + 1; document.getElementById("like").innerHTML = new_l; var catid; catid = $(this).attr("data-catid"); $.ajax( { type: "GET", url: "/likepost", data: { post_id: catid , votes : new_l }, success: function (data) { $('#like' + catid).remove(); $('#message').text(data); } }) console.log(new_l, num1); } </script> Views.py def likePost(request ): if request.method == 'POST': post_id = request.POST['post_id'] print( post_id) likedpost = Post.objects.get(pk=post_id) #m = Like(post=likedpost) likedpost.like_votes = int(request.POST['votes']) likedpost.save() #m.save() return HttpResponse("Success!") else: return HttpResponse("Request method is not a POST") -
Django ORM expression for recursive sum type?
I am making a simple PLM software and the recursive component system is necessary for it. Specifically, I would like to know if there is any way one can express the data type below with Django ORM; if not what would be the best workaround? Component ::= Part | [Component] (or Set of Components) I think the problem breaks down into two issues. How to express sum type with Django ORM How to express a List of a type with ORM For the second issue alone, I am using the two Models (or Table); One for the list instance and another for the rows of the lists which have foreign key filed of list instance to indicate which model it belongs to. However, It seems not that useful for this case; Especially considering querying and forms. What would be the closest expression of the data type above in Django ORM? -
How to design Django models?
This is my Django Models class Course(models.Model): course_name = models.CharField(max_length=100, blank=True) def __str__(self): return self.course_name class Video(models.Model): video_name = models.CharField(max_length=100, blank=True) video_link = models.CharField(max_length=500, blank=True) def __str__(self): return self.video_name class Unit(models.Model): unit_name = models.CharField(max_length=100, blank=True) videos = models.ManyToManyField(Video) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.unit_name class Blog(models.Model): blog_name = models.CharField(max_length= 100) def __str__(self): return self.blog_name Course : Python Tutorial 1 Course : Python Tutorial 2 I want my Python Tutorial 2 doesn't have a video list that Python Tutorial 1 has, but every unit in Python Tutorial 1 has the same video list, How I could modify my code to have that system? -
Django create common "createObject" view logic
I've got a django app with multiple models, and mostly crud functionalities. Most of my views are very similar, ie. for example, all ModelnameCreate functions have very similar structure. So I decided to make helper function: (here is an example of helper for creating new objects) def createFuncHelper(request, title_label , formClass , form_render , success_render , renderToViewWithId , success_message): form = formClass() if request.method=='POST': form = formClass(request.POST, request.FILES) if form.is_valid(): form.instance.updatedBy = request.user newObject = form.save() messages.success(request, success_message) if(renderToViewWithId): return redirect(success_render, id=newObject.pk) else: return redirect(success_render) return render(request, form_render, {'form':form, 'title_label':title_label}) Which is called from my each view (for each model) eg.: def BookingCreate(request): return createFuncHelper(request, etc... It works, but the question for my more experience collegues is - if it is the right approach, or are there any serious risks I'm not aware? -
Html file did not work for live streaming in django
In camera.py file class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) # Define the codec and create VideoWriter object def __del__(self): self.video.release() def get_frame(self): success, image = self.video.read() ret, jpeg = cv2.imencode('.jpg',image) return jpeg.tobytes() **In view.py file ** def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera()), content_type='multipart/x-mixed-replace; boundary=frame') ** My url.py file** tyurlpatterns = [ path('live/',stream_views.video_feed,name='video_feed'), And HTML file {% extends 'blog/base.html' %} {% block content %} <img src="{{ url 'video_feed' }}" alt="video_feed"> {%endblock content%} here my html file is not work.It just run other file.Html file can't access this url . what i can do for solving this problem? I expect my every frame continuously pass into my html page. -
How to access data from previous form in django-formtools wizard?
I'm trying to use information selected in a previous step of a wizard in a subsequent step. I assume this is a pretty common use case but my googling has ben of limited help, so I think I'm not approaching it in the django way. I only find a few questions from 10 years ago. I have distinct templates defined for each step It seems like there must be a very basic way to access the previous steps data but I'm struggling (new to Django in general) This is the only documentation I can find but it seems to be just be describing how to use the context dictionary to determine to skip a step or not. There must be some 1 IQ simple way to get a value input in step 1 and display it in step 2.. Please help me! -
Plotly write_image() - Django framework Python
My python code generates perfectly the chart, however, i struggle to save it in my repo. My Django framework is structured as such. I want the script located in playground/views.py to generate in /static/ import plotly.graph_objects as go fig = go.Figure(data=go.Scatter(x=ainfo.index,y=ainfo.Close, mode='lines')) x = fig.show() fig.write_image("../static/fig1.png") And got this error message: FileNotFoundError: [Errno 2] No such file or directory: '../static/fig1.png' In addition, How can I name the file with a variable ? let MyVariable = 1 fig.write_image("../static/"+ MyVariable +".png") -
Can we add a HTML attr with value from our DB in Django?
I have a form, I take the info to this form from my DB. My form.py class TrafficSourcesForm(ModelForm): class Meta: model = TrafficSources fields = ['name', 'token'] widgets = { 'name': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Traffic source name' }), 'token': TextInput(attrs={ 'class': 'form-control', 'placeholder': 'API-token' }) } My views.py def settings(request): error = '' if request.method == 'POST': new_form = TrafficSourcesForm(request.POST, instance=request.POST.get('id')) if new_form.is_valid(): # new_form.save() error = request.POST.text else: error = 'Something went wrong!' new_form = TrafficSourcesForm() forms = [TrafficSourcesForm(instance=x) for x in TrafficSources.objects.all()] return render(request, 'mainpage/dashboard.html', {'new_form': new_form, 'forms': forms, 'error': error}) MY HTML <table class="table table-striped table-hover"> <tr> <th style="width: 42%">Name</th> <th style="width: 43%">Token</th> <th style="width: 15%">Action</th> </tr> {% for form in forms %} <tr> <td>{{ form.name }}</td> <td>{{ form.token }}</td> <td><button class="btn btn-lg btn-success w-100" form="{{form.instance.id}}">Save</button></td> </tr> {% endfor %} <tr> <td colspan="3">Add new traffic source:</td> </tr> <tr> <td><input class="form-control" placeholder="Name"></td> <td><input class="form-control" placeholder="API-token"></td> <td><button class="btn btn-lg btn-success w-100">Add</button></td> </tr> </table> As I am using a table grid, my forms for the inputs and submit button are outside the table. In that way I need to put a tag form="{a variable from DB to match the form}" on my inputs. Something like instance number or name … -
"detail": "JSON parse error - Extra data: line 6 column 6 (char 106)" [closed]
this is my code of posting the data #add user.. @api_view(['POST']) def add(request): student = Member.objects.all() serializer = MemberSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) while posting the data im getting the error like this < "detail": "JSON parse error - Extra data: line 6 column 6 (char 106)" while adding post im getting like this [](https://i.stack.imgur.com/S1eRP.png) -
logout give me error in django --- maximum recursion depth exceeded [closed]
in views from django.contrib.auth import logout def logout(request): logout(request) return redirect('login/') in url path('logout/', views.logout, name="logout"), in html <a href="{% url 'logout' %}">logout</a> error RecursionError at /logout/ maximum recursion depth exceeded RecursionError at /logout/ maximum recursion depth exceeded -
django annotate qs by objects using object_id field
Got user and role. How could i get annotated roles qs by users? from django.db import models, F, Q class User(models.Model): pass class Role(models.Model): ... user_id = models.PositiveIntegerField( verbose_name='Related object ID' ) I want to do something like this: roles = Role.objects.all() roles = roles.annotate(user=Q(User.objects.get(id=F('user_id')))) for role in roles: print(role.user.id) => 123 Traceback: FieldError: Cannot resolve keyword 'user_id' into field PS: Please, don't ask me to do FK or MtM, I need exactly this relation. -
If i have a my cordinate , i want to get every cordinated in the radius of 5 km
i have the database of many events ,i want filter out the events happening within 5 kms of radius from my location.Currently i am doing it using haversine running every event in a for loop,which is very time consuming can anyone suggest an alternative for this method The method i am currently using is haversine in a for loop for comparing every event and thats not a proper way -
How do I solve Installation of PyDictionary error?
I am trying to build a simple word search dictionary using django and when I install pyDictinary which is a django package I get this error: 'python setup.py egg_info did not run successfully.'. How can I solve this, or how other way can I get to use the package? I am made to know that pip has no problem. I run "pip install pyDictionary" on vscode terminal -
djongo RunPython in database migration
There's a django app with djongo as database driver. I want to add custom migration using RunPython. But I can't understand how to reach pymongo client. Here's the code: from django.db import migrations def _custom_migration(apps, schema_editor): db = ... # what to put here? db.collection1.update_many({}, [{'$set': {"field2": "$field1.id"}}]) class Migration(migrations.Migration): operations = [ migrations.RunPython(_custom_migration), ] -
How to make sef image link with uploaded tinymce in django?
I published my django site but everyday i am finding new problems :) Today i realised my images in the article has no slugify link. Forexample in this page https://www.endustri.io/monokristal-gunes-paneli-nedir-calisma-prensibi-avantajlari/ This image has url like this. How can i make this image url like endustri.io/(image or media)/image-name.webp data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAApQAAAGVCAMAAAB3pZE2AAAC2VBMVEXz8/Tz8/QoKCktLS4iQX0iRYI6OjwgNmz///8xMTMhQ38hSIchSoo2NjdYWFohPnchOnIhQn5/f4EhR4W+H3DMzM6mpqchRYQhSIYiRoPI0eEhRIJeXl9iYmTX19fIz97p6eoAAACbnaBuRO/Wi/Sf2N27f+CaPUOkapdYxS6xil1jFKrWOUWscotY5Rah2j1DpGqXWMUusYpdb5AlujV99XpgrKAAAAAElFTkSuQmCC -
Store flutter ocr image data to Django SQL [closed]
I have created a ocr image reader and it's read the image and convert to word but how to store the word data to Django data sqlbase .. Thanks 🙏 Pls help urgent 🙏🙏🙏 -
Selenium test failed with RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it
I'm running tests with selenium and i want to test the admin panel in django so i made the below tests import pytest from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By #create pytest database with admin credintials @pytest.mark.selenium def test_create_admin_user(create_admin_user): assert create_admin_user.__str__() == "admin" @pytest.mark.django_db def test_dashboard_admin_login(live_server, create_admin_user, firefox_browser_instance): browser = firefox_browser_instance browser.get(("%s%s" % (live_server.url, "/admin/login"))) username = browser.find_element(By.NAME, 'username') password = browser.find_element(By.NAME, 'password') submit = browser.find_element(By.XPATH, '//input[@value = "Log in"]') username.send_keys("admin") password.send_keys("admin") submit.send_keys(Keys.RETURN) assert "Site administration" in browser.page_source fixtures: import pytest @pytest.fixture def create_admin_user(django_user_model): """ Return admin user """ return django_user_model.objects.create_superuser("admin", "admin@admin.com", "admin") confest: pytest_plugins = [ "core.test_setup.fixtures", "core.test_setup.selenium", ] when i run the tests it appears that 1 passed, 1 failed the one passed is test_create_admin_user and the one failed is def test_dashboard_admin_login Error: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. -
Truncate consecutive values in a Django (TimescaleDB) QuerySet
I have a QuerySet consisting of a timestamp and a boolean value. When there are consecutive repeating values, I'd like to truncate them to only show the first (and maybe the last one too, but not mandatory). e.g. the given queryet <TimescaleQuerySet [ {'time': datetime.datetime(2023, 1, 23, 10, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 10, 53, 11, 787303, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 10, 53, 20, 646474, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 27, 7, 971506, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 23, 20, 646474, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 23, 11, 787303, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 9, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}] should truncate to <TimescaleQuerySet [ {'time': datetime.datetime(2023, 1, 23, 10, 57, 7, 971506, tzinfo=<UTC>), 'is_on': True}, {'time': datetime.datetime(2023, 1, 23, 10, 53, 20, 646474, tzinfo=<UTC>), 'is_on': False}, {'time': datetime.datetime(2023, 1, 23, 10, 23, 11, 787303, tzinfo=<UTC>), 'is_on': True}] I'm breaking my head over this. Is there an elegant way to achieve this? I want to avoid looping over the whole queryset, it's just too slow when theres >1000 results. -
custom message if there isnt any record to show in django-template
Hello there im trying to show a custom message like "Doesnt exists" if there isnt really any record to show and ignore having None in the template for empty records Template : <div class="col-md-6 col-sm-12 col-xs-12 form-group pull-right "> <label style="color : blue;" class="control-label col-md-5 col-sm-3 col-xs-12 pull-right size_Style"><i class="fa fa-circle" style="color : blue;" aria-hidden="true"></i> knowledge cost :</label> <span class="col-md-12 col-sm-12 col-xs-12 form-group pull-right colorfull"> {{ special_knowledge.knowledgecost|safe }} </span> </div> <div class="col-md-6 col-sm-12 col-xs-12 form-group pull-right "> <label style="color : blue;" class="control-label col-md-5 col-sm-3 col-xs-12 pull-right size_Style"><i class="fa fa-circle" style="color : blue;" aria-hidden="true"></i> knowledge cost percemtage :</label> <span class="col-md-12 col-sm-12 col-xs-12 form-group pull-right colorfull"> {{ special_knowledge.knowledgecost_percent }} </span> </div> based on the given HTML the first Field would Be None becuase i dont have any record for it in my db , so is there any more efficient way than using if for each record ? i tried this method for all to handle any empty record {% if special_knowledge.knowledgecost %} {{ special_knowledge.knowledgecost|safe }} {% else %} Doesnt exist {% endif %} -
Unitest DRF with CONTEXT
I am wondering if anyone could help me with the appropriate way to create a unitest in DRF when using context inside a serializer. as you can see in the serializer below, I am adding a field called distance to my serializer. class CompanySerializer(serializers.ModelSerializer): """Serializer for companies.""" distance = serializers.SerializerMethodField() class Meta: model = Company fields = ['id', 'company_name', 'lat', 'long', 'logo', 'distance'] def get_distance(self, company): """Return context""" print(self.context) return self.context['distances'][company.pk] Then when calling the unitest I get an error: KeyError: 'distances' COMPANY_URL = reverse('company:company-list') def test_company_list_limited_to_user(self): """Test list of companies is limited to authenticated user.""" other_user = create_user( email='other@example.com', password='password123' ) create_company(user=other_user) create_company(user=self.user) res = self.client.get(COMPANY_URL) companies = Company.objects.filter(user=self.user) serializer = CompanySerializer(companies, many=True) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual(res.data, serializer.data) Is there a better way to write this test, so it can pass? I did check and the context distance is create and passed to the serializer with no issue, but the test is not passing :/ Tks a lot! Kind regards Victor Almeida