Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React axios object returns null with django rest framework
I am using axios to create a new instance in django rest framework. I do it with multipart/form-data but it returns null instead of the actual object. I also use the FormData const formData = new FormData() formData.append("image", selectedFile); formData.append('profile', currentUser[0]?.profile) formData.append('test','1') axios.post('http://127.0.0.1:8000/create_post/', formData, { headers: { "Content-Type": "multipart/form-data", }, }).then(res=>console.log(res)).catch(err=>console.log(err)) } -
Element could not be scrolled into view error
I have been working on a simple recipe app in django and want to be able to sort the recipes by country of origin. I am trying to get the hang of Test Driven Development, so I am using Selenium. Unfortunately, I get this error. I'm confused because there should only be one recipe in the database, and yet a call for a second recipe is made when the recipe doesn't exist. When I run python manage.py runserver, I can interact with the recipe card exactly the way I would imagine, but I get an error when trying to test it. How should I fix this error? ElementNotInteractableException: Message: Element '<a class="recipe-card" href="/recipes/2/">' could not be scrolled into view (edit) I have tried adding a second recipe to test with, but am then told that /recipes/3/ could not be scrolled into view. The Selenium test code class RecipesTest(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(5) self.continent = Continent.objects.create(name='test_continent') self.country_1 = Country.objects.create(name='test country 1', continent = self.continent) self.country_2 = Country.objects.create(name='test country 2', continent = self.continent) self.recipe_1 = Recipe.objects.create(name='test recipe 1', country = self.country_1) def tearDown(self): self.browser.quit() def test_recipes(self): self.browser.get('%s%s' % (self.live_server_url, '/countries/1/')) recipe = self.browser.find_element(by=By.CLASS_NAME, value="recipe-card") recipe.click() The html file recipe_list.html {% … -
Accessing static content from css file with Google App Engine/Google Cloud Storage
I have a Google Cloud Storage bucket from which my Google App Engine django application retrieves its static content. This works swimmingly as long as the content is being accessed through staticfiles, but becomes a problem when I try to link src urls through my css (e.g. background image, font). In my bucket logs I can see this is because no authentication info is being passed in the request for these assets being linked via css, whereas those grabbed through the static system (e.g. staticfiles or {% static '' %} ) I'm wondering what the correct solution is to this RATHER than just using inline css within the html to invoke the staticfile system as doing so is bad practice. This is my current approach, I can see it requesting the correct bucket resource, it just isn't authenticating: @font-face { font-family: "syne":; src: url("path/to/font.ttf") format("truetype") } -
How can I create a shared portal for tenant
I have a question about django-tenent-scheme library. How may I create a tenant management portal, that is not shared with other tenants? I want to display a main page where a new customer can create his account and after that new tenant will be created. For instance, myapp.net/Portal is for creating new customers and for managing accounts, buying licenses, etc. And after creating a client he gets his own URL client.myapp.net. Is there any way to create a management portal in the project or should I create another project, deploy it with another server, and manage it by DNS like myapp.com A --> portal IP *.myapp.com A --> app ip I can create a tenant for the portal with the domain myapp.net but the portal is available in all tenants like client.myapp.net/portal -
Problem with Stripe Checkout (Nextjs and Django)
I am trying to make a payment page in nextjs using stripe. if i guendo the guide it works correctly, but i don't want to use the form to call the /create-checkout-session endpoint but i want to use an onClick function on a div to make a call with axios. Frontend Code 'use client'; import React, {useEffect, useState} from 'react'; import Container from "@/components/Container"; import axios from "axios"; const PagamentiPage = () => { const data = { product_id: 1, price: 599, name: "Test", description: "lorem ipsum dolor sit amet consectetur adipisicing elit.", } return ( <Container> <div className="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div className="description"> <h3>{data.name}</h3> <h5>Price: {data.price/100} €</h5> </div> </div> <form action="http://127.0.0.1:8000/pagamenti/create-checkout-session" method="POST" > <input type="hidden" name="product_id" value={1}/> <input type="hidden" name="price" value={70000}/> <input type="hidden" name="name" value={"Test"}/> <input type="hidden" name="description" value={"Frf"}/> <input type="hidden" name="username" value={"Federiko98"} /> <button type={"submit"} className={"bg-red-300 p-2 rounded"}> Checkout </button> </form> </Container> ); }; export default PagamentiPage; Backend Code class StripeCheckoutView(APIView): def post(self, request, *args, **kwargs): data = request.data try: checkout_session = stripe.checkout.Session.create( line_items=[{ 'price_data': { 'currency': 'eur', 'unit_amount': data.get("price"), # centesimi 'product_data': { 'name': data.get("name"), 'description': data.get("description"), }, }, 'quantity': 1, }], metadata={ 'username': data.get("username"), 'product_id': data.get("product_id"), }, mode='payment', success_url=f'{YOUR_DOMAIN}?success=true', cancel_url=f'{YOUR_DOMAIN}?canceled=true', ) … -
Pass token from frontend to backend and access claims that can be used to filter data from database, React Django MySQL project
The map function in the Schools.js file shows all schools in the database. I want it to only fetch and display the shools where the dist_office_id = place_id and the school_name is not empty. the place_id is a claim in the token. I want to pass the token from the School.js file (frontend) to the views.py file (backend) where i need to access the place_id claim from the token. When i hardcode the place_id = 3 it works fine as expected but there are many district offices and it should only show schools under any district that the user may belong to. import { useEffect, useState } from 'react'; import jwt_decode from "jwt-decode"; import {Table, Button, ButtonToolbar} from 'react-bootstrap'; import {FaEdit} from 'react-icons/fa'; import {RiDeleteBin5Line} from 'react-icons/ri'; import {getSchools, deleteSchool} from '../services/SchoolService'; import AddSchoolModal from '../components/modals/api_modals/AddSchoolModal'; import UpdateSchoolModal from '../components/modals/api_modals/UpdateSchoolModal'; const Schools = () => { const [schools, setSchools] = useState([]); const [addModalShow, setAddModalShow] = useState(false); const [editModalShow, setEditModalShow] = useState(false); const [editSchool, setEditSchool] = useState([]); const [isUpdated, setIsUpdated] = useState(false); const token = localStorage.getItem("authTokens") if (token){ const decoded = jwt_decode(token) var place_id = decoded.place_id } useEffect(() => { let mounted = true; if(schools.length && !isUpdated) { return; } getSchools() … -
how do i add password placeholders in django?
I tried creating placeholders but this only worked for my username and email fields but not for the password fields. i already tried using "TextInput".Can someone please help? class SignUpForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2' ] widgets = { 'username': forms.TextInput(attrs={ 'placeholder': 'Username', }), 'email': forms.TextInput(attrs={ 'placeholder': 'Email' }), 'password1': forms.PasswordInput(attrs={ 'placeholder': 'Password'}), 'password2': forms.PasswordInput(attrs={ 'placeholder': 'Confirm Password' }) } I tried using widgets dictionary and changing it to from "TextInput" to "PasswordInput" -
Can we create a duplicate record which is indexed in MySQL database?
I am using Django framework. I want to index a particular field named "Product_id" in one of the models named as "Products". Here is the schema of "Products" model - I found that querying products on the basis of "product_id" is the only choice. Unfortunately it is taking longer time to check if product with given "product_id" exist or not existing_product = Products.objects.get(product_id=1234) I searched a lot and found that indexing a field in the model reduces query time. But, I am concerned about another record being created with same product_id My questions are - Can I have two records with same "product_id" but different db_indexes? What if I try to create a new record with a duplicate "product_id"? (i.e creating record with already existing "product_id" ) Does indexing reduces time for querying? -
Django get_foo_display not working as expected
so I have been trying to code this and I have been seeing everyone's code, I am pretty new to Django and not really sure how it works but what I am trying to do is display the choicefield value in template. This is my models.py class Orders(models.Model): order_choices = ( ('王者', 'wangzhe'), ('小乔', 'xiaoqiao'), ('打野', 'da ye'), ('伽罗', 'jia luo'), ) progress = ( ("In Progress","In Progress"), ("Completed","Completed") ) account = models.ForeignKey('users.AccountUser', on_delete=models.CASCADE) member = models.ManyToManyField('users.Member') order_type = models.CharField(max_length=255, choices=order_choices) status = models.CharField(max_length=50, choices=progress, default="In Progress") order_number = models.CharField(max_length=12, unique=True) def get_order_choices(self): return self.order_choices def get_progress(self): return self.progress def __str__(self): return self.order_type While this is my views.py from users.models import Member from .forms import OrderForm from .filters import OrderFilter from .models import Orders import os @login_required def services(request): if request.method == "POST": form = OrderForm(request=request, data=request.POST) if form.is_valid(): order = form.save() messages.success(request, "Order Submitted!") else: for key, error in list(form.errors.items()): messages.error(request, error) else: form = OrderForm(request) choices = [] for c in Orders.order_type.field.choices: choices.append(c[0]) return render( request=request, template_name = "services/services.html", context={"form": form, "choices": choices, "member_id": request.user.member_id } ) @login_required def orderSearch(request): orders = Orders.objects.all() myFilter = OrderFilter(request.GET, queryset=orders) orders = myFilter.qs return render( request=request, template_name = "services/orderSearch.html", context={ "orders": … -
I was deploying my Django app in Vercel and got stuck due to this error, Can anyone assist?
So I am trying to launch my web app created from Django in Vercel. But I am getting stuck in running checks step of Vercel. enter image description here I used checkly to see what error it was and It showed this. I don't understand why. -
Searching for the last photo sent by a user by his username in telegram using telebot
I need to get the last photo sent by a certain user in a chat in order to later get the necessary information using ocr I can’t understand and find how to do this, now I can get the photo I just sent @bot.message_handler(commands=['photo']) def handle_photo(message): chat_id = message.chat.id file_id = message.photo[-1].file_id file_info = bot.get_file(file_id) file_path = file_info.file_path file = bot.download_file(file_path) image = Image.open(BytesIO(file)) -
strange module not found error when using celery
on running this command ~/W/p/F/backend> celery -A config.celery_app worker it throws [2023-09-14 14:45:38,243: CRITICAL/MainProcess] Unrecoverable error: ModuleNotFoundError("No module named 'abcd'") Traceback (most recent call last): File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/worker/worker.py", line 202, in start self.blueprint.start(self) File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/bootsteps.py", line 112, in start self.on_start() File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/apps/worker.py", line 135, in on_start self.emit_banner() File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/apps/worker.py", line 169, in emit_banner ' \n', self.startup_info(artlines=not use_image))), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/apps/worker.py", line 231, in startup_info results=self.app.backend.as_uri(), ^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/app/base.py", line 1293, in backend self._backend = self._get_backend() ^^^^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/app/base.py", line 965, in _get_backend backend, url = backends.by_url( ^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/app/backends.py", line 68, in by_url return by_name(backend, loader), url ^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/celery/app/backends.py", line 48, in by_name cls = symbol_by_name(backend, aliases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/envs/fitavatar/lib/python3.11/site-packages/kombu/utils/imports.py", line 59, in symbol_by_name module = imp(module_name, package=package, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/insoluble/.pyenv/versions/3.11.5/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked ModuleNotFoundError: No module named 'abcd' I'm aware of the abc module but didn't find any reference of this abcd. I'm running Celery 5.3.4 (emerald-rush) on Python 3.11.5. -
Dynamic Serializer Meta Pollution Between Calls
I have a a dynamic serializer where I pass arguments from API calls into the serializer to filter specific fields from the relevant model class. I do this by leveraging the serializer's __init__ function to directly set self.Meta.fields, which are otherwise a default set of fields I configured. Given a model with 3 fields, id, description, and trigger, when I make an unfiltered call, /api/endpoint I get what I expect, a list of json objects containing all the fields in the model. Then when I make a filtered call, i.e., /api/endpoint?fields=id I also get what I expect, a list result containing just the id field. However, when I make another unfiltered call I continue to get just a list of objects with only the id field. The only time from now on I get what I want is if I make a new filtered call. Here is my serializer code. class BaseSerializer(serializers.ModelSerializer): # id comes from `serializers.ModelSerializer` description = DescriptionSerializer() trigger = TriggerSerializer() class SerializerA(BaseSerializer): def __init__(self, *args, **kwargs): fields = kwargs.pop("fields", None) super().__init__(*args, **kwargs) if fields: self.Meta.fields = fields <--- this does NOT reset between calls class Meta: model = ImplIdDescriptionTriggerModelA # there are more ImplModels... fields = '__all__' … -
In Django StreamingHttpResponse cannot return results in slices as expected. it waits for all iterations to end and returns the results at once
In Django, StreamingHttpResponse cannot return results in slices as expected. Instead, it waits for all iterations to end and returns the results at once. How should I solve this problem? thanks!!! Here is full code https://github.com/hugozach/streaming-http-response-error-demo StreamingHttpResponse can be working -
results from ajax doesnt show up in my html template rendered with django
before I go into details about my problem, I just want to say I'm new in DJANGO/AJAX world, so if you think I can do what I want, with an easier/more efficient way, I'd be more than happy to hear it, thank you so much in advance. I have a web page which contains a search bar, and a sort of complex table structure, we are supposed to be able to search an item using the search bar and show the relative result in the table using AJAX, without the page reload, I managed to write the AJAX CALL, send it to the view, get the result data in view, so far everything works well, I print the results in view, and it works fine I get the result, but once I render the template with the result data, the table's fields are empty. I don't know where did I go wrong. any help would be much appreciated. this is the script that make the Ajax call(I use an AJAX call to show live search result, something like what google does on search, and gave every result a class name of 'SearchResultItem') $(document).on('click', 'a.SearchResultItem', e=>{ e.preventDefault(); targetAuthorityId = e.target.parentElement.id $.ajax({ … -
Django Deployment Failed during build process on Railway
I tried to deploy my django project on railway but it failed without any build or deploy logs i made procfile,requirements.txt, runtime.txt and staticfiles but this didn't change the results i created the django project and made another app called Portfolio and updated everything needed and made sure the website works locally well then uploaded everything on github repository here is a screenshot of the repository main branch -
Please enter the correct username and password for a staff account & CSRF token missing or incorrect
I am using forms.py to create a profile and using signals.py. There's a OneToOneField relationship between the profile and user. However, when I try to log in at http://127.0.0.1:8000/admin after filling out the form, that receive the following message: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." Additionally, when I refresh the page, sometimes get a "CSRF token missing or incorrect" error. Forbidden (CSRF token from POST incorrect.): /admin/login/ [14/Sep/2023 17:23:18] "POST /admin/login/?next=/admin/ HTTP/1.1" 403 2518 here is what I wrote: profile_form.html {% extends 'main.html' %} {% block content %} <h1>Edit Account</h1> <form method="POST" action="{% url 'edit-account' %}" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit" /> </form> {% endblock content %} forms.py from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import Profile class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['first_name', 'email', 'username', 'password1', 'password2'] labels = { 'first_name':'name', } def __init__(self, *args, **kwargs): super(CustomUserCreationForm, self).__init__(*args, **kwargs) for name, field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) class ProfileForm(ModelForm): class Meta: model = Profile fields = ['name', 'email', 'username', 'location', 'bio', 'short_intro', 'profile_image', 'social_github', 'social_linkedin', 'social_youtube','social_twitter', 'social_website'] signal.py from django.contrib.auth.models import User # Create your … -
Can I assign a combination of variables using one "with" template tag?
I have the template code value="{{ key|slice:":4" }}-{{ suggestion.pk }}" which slices the variable key, appends a "-" and the value of suggestion.pk. I now want to assign this combined value to the name id using the built-in with template tag. Is there a way to do this using one with tag or do I have to use a custom template tag? Using {% with id={{ key|slice:":4" }}-{{ suggestion.pk }} %} {{ id }} {% endwith %} doesn't work and throws the error Could not parse the remainder: '{{' from '{{'. I also tried doing something like {% with id= key|slice:":4"-suggestion.pk %} {{ id }} {% endwith %} or adding some extra quotes, which also didn't work. -
Permissions error in Docker even after giving user proper permissions
If I run uWSGI as root I get an error: | *** WARNING: you are running uWSGI as root !!! (use the --uid flag) *** and rightfully so since it is unsafe. So I create a user and give it permissions to the relevant folders: RUN adduser --disabled-password --gecos '' django-user && \ mkdir -p /vol/web/media && \ mkdir -p /vol/web/static && \ chown -R django-user:django-user /vol && \ chmod -R 755 /vol && \ chmod -R +x /scripts However, after running I run into PermissionError: [Errno 13] Permission denied: for files within /vol directory. Since it is flagged -R, this doesn't make sense. -
Django: self symmetrical intermediate model
I'm trying to make a symmetrical intermediate relationship between same models class Person(models.Model): name = models.CharField(max_length=128) friendship = models.ManyToManyField('self', through="Friendship") intermediate model: class Friendship(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='friend1') person2 = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='friend2') date_befriended = models.DateField() reason = models.CharField(max_length=64) I tried solving it by adding adding through_fields=("person", "person2") to Person(friendship), but it didn't work as expected... Note for future solution seekers:related_name is, I'm pretty sure, obligatory in the Intermediate model to avoid errors: myapp.Friendship.person2: (fields.E303) Reverse query name for 'myapp.Friendship.person2' clashes with field name 'myapp.Person.friendship which also occurs for Friendship(person/friend1) -
Configure docker-compose logging log file path and name for Celery worker
Is it somehow possible to define the path and file name of the logfiles? Because otherwise they are somewhere on the system and the requirement is to have them in the mapped logs folder. celery_worker: container_name: 'celery_worker' env_file: - .env environment: - CELERY_WORKER_NAME=celery_worker_mdx logging: driver: "json-file" options: max-size: 1k max-file: "3" build: context: backend dockerfile: Dockerfile command: sh -c "./wait-for.sh rabbitmq:5672 -- celery -A backend worker --queues=myqueue.queueA --hostname=celery-worker --concurrency=10 --pool threads" restart: unless-stopped depends_on: - rabbitmq volumes: - ./backend/backend/customer_settings/backend.py:/code/backend/customer_settings/backend.py - ./logs/backend:/code/logs When I add the --logfile parameter to the celery command then I get the logfile in the desired folder, but all other docker compose related logging settings are ignored and I still run into the problem with huge logfiles. My second approach: I also tried to define the logger and handler in settings.py, but the logger writes only to the file, if I open the django shell within the worker and log from there. If the worker is triggered via RabbitMQ rpc, the logging outputs in the same functions are only written to the console. Even the files are created properly according to settings.py for the celery worker. The loglevels are set to debug in the loggers section and … -
Use Django messages framework when a webhook is called
I have set up an URL in Django that is being used as webhook from another service. It has implemented like: @csrf_exempt @require_POST def hoof_alert(request): json_rx = json.loads(request.body.decode("utf-8")) if json_rx["alerts"][0]["status"] == "firing": messages.error("Alarm fired") else: messages.success("No more alarm") returns HttpResponse(status=200) Now, the main issue is that, even if the function is called, as I see it happens on the console and my service get back the code 200 status, I can't see the message popping up on the front end. My guess is that, the message is attached to the request done on the webhook, which is not the request an user will do when access the website. So, my question is, how do I make the message being visible on the front end when the hook is called? -
Send Sms and Mms to users with my company numbers
Is it possible to utilize a third-party API in Python for sending both MMS and SMS messages? I'm looking to avoid sending SMS messages using the purchase numbers provided by the third-party platform. Instead, I intend to send SMS and MMS using my personal phone numbers or a list of numbers that I can add to the platform. I've attempted to send messages using Python with Twilio or Click Send, but it seems they only allow sending messages from the numbers they provide on their platforms. What I'm aiming for is to send MMS from my company's specific number. -
Djongo library error when adding an object to database
I am getting a djongo library error when I am trying to add an Station object in my admin panel. The error page says there is no exception message supplied so I am facing difficulty to pinpoint what is causing the error. The error is of RecursionError File "C:\Users\Admin\Envs\routemaster\lib\site-packages\sqlparse\tokens.py", line 19, in __contains__ return item is not None and (self is item or item[:len(self)] == self) RecursionError: maximum recursion depth exceeded in comparison I asked chatgpt about the same and it suggested me to check my models.py file for any loops in relationship with other models but I did and I think my models.py file is not causing this, So can it be a bug on djongo's side? models.py from djongo import models class City(models.Model): name = models.CharField(max_length=100) class Station(models.Model): name = models.CharField(max_length=100) # Add other station-related fields as needed city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return self.name class Bus(models.Model): number = models.CharField(max_length=10) # Add other bus-related fields as needed # Define a Many-to-Many relationship with Station stations = models.ManyToManyField(Station) def __str__(self): return self.number -
Django test for JWT Api
I am writing test for JWT Api Django and receiving the error '..in test_refresh_token self.assertIn("refresh", resp.json()). AssertionError: 'refresh' not found ' Could you please help to understand what I am doing wrong? class TestJWTAuth(APITestCase): @classmethod def setUpTestData(cls): faker = Faker() profile = faker.simple_profile() cls.user_pass = faker.password(8) cls.user = User.objects.create_user( username=profile["username"], password=cls.user_pass, email=profile["mail"], ) def test_no_data(self): resp = self.client.post(reverse("token_obtain_pair")) self.assertEqual(resp.status_code, status.HTTP_400_BAD_REQUEST) data = resp.json() self.assertIn("username", data) self.assertIn("password", data) def test_with_valid_user_data(self): resp = self.client.post( reverse("token_obtain_pair"), data={ "username": self.user.username, "password": self.user_pass, }, ) self.assertEqual(resp.status_code, status.HTTP_200_OK) data = resp.json() self.assertIn("access", data) self.assertIn("refresh", data) def test_with_invalid_user_data(self): resp = self.client.post( reverse("token_obtain_pair"), data={ "username": self.user.username, "password": "INVALID_PASSWORD", }, ) self.assertEqual(resp.status_code, status.HTTP_401_UNAUTHORIZED) self.assertDictEqual( resp.json(), { "detail": "No active account found with the given credentials", }, ) def test_refresh_token(self): resp = self.client.post( reverse("token_obtain_pair"), data={ "username": self.user.username, "password": self.user_pass, }, ) self.assertEqual(resp.status_code, status.HTTP_200_OK) refresh_token = resp.json()["refresh"] resp = self.client.post(reverse("token_refresh"), data={"refresh": refresh_token}) self.assertEqual(resp.status_code, status.HTTP_200_OK) self.assertIn("refresh", resp.json())