Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return query set in SerializerMethodField in Django
if I have SerializerMethodField and I wants to return query set. I tried to do this but doesn’t work available_times = serializers.SerializerMethodField() def get_available_times(self, obj): qs = AvailableTimes.objects.filter(hall__id=obj.id) serializer = AvailableTimesSerializer(qs, read_only=True ,many=True) return serializer.data it not working... give and Error. -
Value comparison query Django
Good afternoon ... I need to make a comparative query ... I implemented this snippet in my view, but it returns me an error ... can someone help me .. Models class Room (models.Model): block = models.ForeignKey (Block, on_delete = models.PROTECT) room = models.CharField ('Room:', unique = True, max_length = 50) capmax = models.IntegerField ('Maximum Cap:') available = models.BooleanField ('Available', default = True) busy = models.BooleanField ('Busy', default = False) internet = models.BooleanField ('Internet', default = False) projector = models.BooleanField ('Projector', default = True) computer = models.BooleanField ('Computer', default = False) class Estclass (models.Model): estclass = models.CharField ('Class', max_length = 20) course = models.CharField ('Course', null = False, max_length = 50) period = models.CharField ('Period', null = False, max_length = 50) discipline = models.CharField ('Discipline', max_length = 50) estudents = models.IntegerField ('Qty') professor = models.CharField ('Professor', max_length = 50) allocated = models.BooleanField ('Allocated', default = False) internet = models.BooleanField ('Internet', default = False) projector = models.BooleanField ('Projector', default = False) computer = models.BooleanField ('Computer', default = False) class Allocate (models.Model): date = models.DateField ('Date', auto_now = True, blank = True) days = [ ('Monday', 'Monday'), ('Tuesday', 'Tuesday'), ('Wednesday', 'Wednesday'), ('Thursday', 'Thursday'), ('Friday', 'Friday'), ('Saturday', 'Saturday'), ] day = models.CharField ('Day', … -
django: Standard form is working but not bootstrap model form
I am working on a note app(clone of Google's keep). When adding a Note using Standard form, it works & a note instance is created on the database but when I am using a bootstrap Model form, then it is not working. Both types of form uses the same action, method, and view as well. Here is the link of the form which I wrote. Note- I have commented out the bootstrap Model form & at the bottom, there is the standard form(it starts from here). And, link of the view file. Also, I know the Ajax way of doing it, but still, I want to know where I am missing when I am doing like this. Or it is not possible to do like this. -
How to increment a manually created primary key field of a Django model using a calculated value during save
Is it possible in Django to update the manually created primary key field of a model with a predetermined / calculated value during save()? In the following model, for example: class Port_Berthing(models.Model): doc_number = models.PositiveIntegerField(primary_key=True, unique=True, default=1000, ...) created_on = models.DateField(default=timezone.now, verbose_name='Created on') effective_date = models.DateField(verbose_name='Effective From') berthing_rate = models.DecimalField(max_digits=5, decimal_places=2, ...) will it be possible for me to .get the last doc_number value, increment it by 1 and insert the calculated value in the primary key field doc_number for the new record. And if it is possible, can we do this in the model's save() method? -
Unable to access list elements in Django Webpage
Following is the context dictionary that I am passing I am rendering to my webpage context = {'subdivision_selected': str(subdivision_selected), 'labels': keep_month_names_only(list(rainfall_data[0].keys())), 'data': new_dict} data = {'2011': [26.9, 84.8, 72.8, 111.4, 326.5, 383.2, 583.2, 441.5, 757.1, 212.3, 150.8, 238.5], '2012': [119.9, 45.6, 30.9, 55.8, 533.9, 458.2, 317.3, 369.6, 868.9, 209.7, 300.5, 187.3], '2013': [67.1, 37.6, 43.0, 46.3, 509.3, 777.0, 564.8, 336.7, 473.6, 455.8, 354.2, 92.3], '2014': [41.9, 8.6, 0.0, 11.1, 238.0, 416.6, 467.6, 321.6, 412.9, 402.6, 201.2, 100.4]} After passing the context I am accessing the same from Django Webpage using chart.js as shown in following code {% for a in data %} var ctx = document.getElementById({{ a }}).getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in labels %}"{{ i }}",{% endfor %}], datasets: [{ label: '{{ subdivision_selected }} {{ a }}', data: {{ data.a }}, }] }, }); {% endfor %} When i try to access following line, it returns empty and blank page is seen data: {{ data.a }}, -
How to get list of subscribed queue names in Celery/Django?
My worker is run with: celery worker -A workerTasks -n Worker%h --concurrency=1 --loglevel=info -Q $QUEUE_NAME -f $WORKER_LOG_FILE --pidfile=/logs/worker_pid%h.pid I'm wondering if I can make a python/celery call within the process to find which queue(s) this worker is "subscribed" to? (I do NOT want to find the value of $QUEUE_NAME directly) -
Django - Is there any way to display multiple {% block content %} side by side?
First of all, I'm new to Python/Django in general. The problem I'm facing right now has been itching me for the past day, can't figure out how to make this work. So, I'm trying to create a grid layout (using Bootstrap 4) where I would be able to show Movies/Shows which I have completed watching. The closest I found was a blog tutorial in Python/Django, did help me setup everything, from logging in to creating posts. Now, the website is like a typical blog - everything gets stacked vertically, until it reaches a certain amount of posts, then you see the pagination. What I would like to do, is to display some sort of grid, here's a small example of how it looks now, and what I am trying to create: [ col-md-9 ][ col-md-3 ] In the above example, the {% block content %} and {% endblock %} fill in the col-md-9 section of the site, almost like a container-fluid. Ignore the col-md-3, the blog had it as a sidebar, which I don't really need. What I'm trying to do would need to look something like this: [col-md-3][col-md-3][col-md-3][col-md-3] Not sure how to make the {% block content %} smaller … -
How do I reply to a tweet from my web using following way
I have tweets on my web I need to make reply over a tweet via python script in the following way. As a user, I am on a web page have 10 tweets with a button named reply on each tweet as soon as I click on this button, twitter login page opens and ask for user email and password when I entered correct credential it opens a textarea for replying text with submit button then I write reply text and submit it is replied to that tweet. If I already logged in on twitter the process of login page will be skipped. Any help will be much appreciated -
How to annotate a queryset with the number of hours since creation
I have the following View model: class View(models.Model): # The date/time when this View was created. created_at = models.DateTimeField(default=timezone.now) In my queryset I want to annotate each View object with a hours_since_created field. I have used the following approach: View.objects.annotate(age_in_hours=ExpressionWrapper(Now() - F('created_at'), output_field=IntegerField())) But this sets the age_in_hours field to a really large integer value and I am not exactly sure how I can convert it to hours. Is there anyway where I can add the hours_since_created field as the number of hours that went by since creation? -
how to add object in ArrayReferenceField attribute django (using djongo field)
# Model # class Badge(models.Model): _id = models.CharField(unique=True, default=random_string, editable=False, max_length=100) image = models.ImageField(upload_to=badge_file_path) upload_date = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(auto_now_add=True) qr_pos = models.CharField(null=True, blank=True, max_length=100) fill_color = RGBColorField(null=True, blank=True) back_color = RGBColorField(null=True, blank=True) text_pos = models.CharField(null=True, blank=True, max_length=100) text_color = RGBColorField(null=True, blank=True) handle_text = ArrayReferenceField(to=Text, on_delete=models.SET_NULL, blank=True, null=True) View for text_param in text_params: text_pos = list_to_string(text_param["textPos"]) text_color = rgb_to_hex(text_param["textColor"]) key = int(text_param["key"]) text = Text(text_pos=text_pos, text_color=text_color, key=key) print("created") badge.handle_text.append(text) # badge.handle_text.append(text) (raise an error) -
Django shows Realm has no client
I am using django-keycloak package for authenticating users via keycloack, I followed Django keycloack tutorial and while setting up initially after refresh o client it says to refresh certificate at that time I am getting Realm has no client. Also while adding new user using python manage.py keycloack adduser --realm test --user user1 it raises keycloack exception keycloackclientexception not found -
In Django how to display data from current user that's logged in
here am looking for the particular data of logged in user to display in their profile i dont know how to do that please help me with some hint am new here building a django project this is models.py class Loader_post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Loader") pick_up_station = models.CharField(max_length=150) destination_station = models.CharField(max_length=150) sender_name = models.CharField(max_length=150) phone_number = PhoneNumberField(null=False, blank=False, unique=True) receiver_name = models.CharField(max_length=150) sending_item = models.CharField(max_length=150) image_of_load = models.ImageField(default='',upload_to='static/img') weight = models.CharField(max_length=150) metric_unit = models.CharField(max_length=30, default='SOME STRING') quantity = models.PositiveIntegerField() pick_up_time = models.DateField() drop_time = models.DateField() paid_by = models.CharField(max_length=150) created_at = models.DateTimeField(auto_now=True) published_date = models.DateField(blank=True, null=True) def __str__(self): return self.user.username def get_absolute_url(self): return reverse("Loader:post", kwargs={ "username": self.user.username,"pk": self.pk}) this is view.py class Loader_post_list(ListView,SelectRelatedMixin): context_object_name = 'Loader' model = Loader_post template_name = "my_job.html" select_related = ("user") so here is my question that how can i display the data of that loggedin user in their profile after posting the post the data directly display in their profile -
Editing a photo using PIL - Django 2+ "required positional argument: 'fp'"
I am new to Django and for the first time trying to use the Pillow library to edit my photo without changing the aspect ratio. I created the following code: if request.method == 'POST' and 'btn_custom_img' in request.POST: custom_img_form = CustomImgForm(request.POST, request.FILES) if custom_img_form.is_valid(): cd = custom_img_form.cleaned_data #owner.basic_img = cd['custom_img'] image = Image.open(cd['custom_img']) (w, h) = image.size if (w > 1000): h = int(h * 1000. / w) w = 1000 image = image.resize((w, h), Image.ANTIALIAS) owner.basic_img = image.save() owner.save() else: custom_img_form = CustomImgForm() But I get the following error. owner.basic_img = image.save() TypeError: save() missing 1 required positional argument: 'fp' I think this is due to the lack of file name. ut I don't want to give it. I would like django to always automatically uniquely name my file (as it would do without using Pillow). How to fix my code to change the size of the photo and save it in my object correctly. Any help will be appreciated. -
Custom filtering and grouping in Django Rest Framework
I'm working on functionality which allows users to create custom filters on specific models and store those results as a group. As a working example (imports omitted for brevity): class Client(models.Model): email = CIEmailField() class Activity(models.Model): client = BaseForeignKey("client.Client", null=True, related_name="logged_activities") employee = BaseForeignKey("business.Employee", null=True, related_name="logged_activities") created = models.DateTimeField(auto_now_add=True) We want to create filters which will group Clients on Activitys based on the creation time and associated Employee and store those results in a group to be used later. This is pretty straightforward task, except a user is allowed to modify the filter configuration and update fields on a Client, both of which may change whether or not a Client matches the filter criteria. (Note: in this example it's not possible updating a Client could change the result set, but future filters will.) I'd like a many-to-many so we can easily get the groups a client is in, and conversely get the clients in a group, but it's not clear to me the best way to handle the filter configurations. This is currently supported in our system but the filters don't work correctly and the filter queries are run whenever information about a group needs to be used. Given that, … -
How to add Title/Customize response in DRF Browsable API
I want to add new Top Level Element in my Browsable API response. Currently, It displays like this:- This one is the response in browsable API { "count": 33, "next": "http://127.0.0.1:8000/api/apphosts/?page=2&search=test", "previous": null, "results": [ { "_meta": { "hostvars": { "wyak-tn-e2.kyisc.us.test.com": "{'environment': 'lab'}" } } }, { "_meta": { "hostvars": { "jsifn-tn-e3.kyisc.us.test.com": "{'environment': 'uat'}" } } }, But I need a response in this format, _meta and hostvars required at top level *{ "count": 33, "next": "http://127.0.0.1:8000/api/apphosts/?page=2&search=test", "previous": null, "results": [ { "_meta": { "hostvars": { "wyak-tn-e2.kyisc.us.test.com": "{'environment': 'lab'}" }, { "jsifn-tn-e3.kyisc.us.test.com": "{'environment': 'uat'}" }, { "pro-tn-e3.kyisc.us.test.com": "{'environment': 'pro'}" } } } ] }* My Serializer code is this one, This one contain def to_presentation method which converts output to new format. class AppHostSerializer(serializers.ModelSerializer): dynamic_data = serializers.CharField(read_only=True) def to_representation(self, instance): representation = super(AppHostSerializer, self).to_representation(instance) host_name = representation.pop('host_name') host_vars = representation.pop('host_vars') group_vars = representation.pop('group_vars') description = representation.pop('description') repackaged = {"_meta": {"hostvars": {host_name: host_vars} } } return repackaged class Meta: model = AppHost fields = ( 'description', 'host_name', 'host_vars', 'group_vars', 'dynamic_data', 'group_vars', ) -
Getting "detail": "Authentication credentials were not provided."
When I login via POSTMAN, I get a toke, when I try to use to the token to access the apartments endpoint, I get "detail": "Authentication credentials were not provided." Is there anything I am doing wrong? views.py class ApartmentList(APIView): permission_classes = [IsAuthenticated] serializer_class = ApartmentSerializer queryset = Apartment.objects.all() def get(self,request): apartments = Apartment.objects.all() serializer = ApartmentSerializer(apartments, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = ApartmentSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) views.py Login View @csrf_exempt @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): phone_number = request.data.get("phone_number") if phone_number is None: return Response({'error': 'Please provide your phone number'}, status=HTTP_400_BAD_REQUEST) user = authenticate(phone_number=phone_number) if user: serializer = TokenSerializer(data={ # using drf jwt utility functions to generate a token "token": jwt_encode_handler( jwt_payload_handler(user) )}) serializer.is_valid() return Response(serializer.data) return Response(status=status.HTTP_401_UNAUTHORIZED) settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASS':[ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASS':[ 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ], } -
Django - Model Meta options app_label not working
I have following Django app structure apps ├── apartment │ ├── migrations │ ├── apps.py │ ├── models │ │ ├── apartment.py │ │ ├── core.py I added apps.apartment.apps.ApartmentConfig to INSTALLED APPS. And apartment.py look like: class Apartment(Model): class Meta: app_label = 'apartment' When I run makemigrations, it says no changes detected. And I wrote following code in my apps.py. class ApartmentConfig(AppConfig): name = 'apps.apartment' def ready(self): print(self.label) # returns 'apartment' from .models.apartment import Apartment Now it is working fine. Should I always do this when writing a new model?. As a documentation says: If a model is defined outside of an application in INSTALLED_APPS, it must declare which app it belongs to: app_label = 'myapp' Can anyone explain me why it's not working? Are there better ways to solved this without importing all the models? -
How to update foreignkey field manually in UpdateView post method?
I am trying to manually change a foreign key field (Supplier) of a model (Expenditure). I override the UpdateView post method of Expenditure and handle forms for other models in this method too. A new SupplierForm is also rendered in this view and I am tracking if this form is changed via has_changed() method of the form. If this form has changed, what I ask is overriding the related_supplier field of ExpenditureForm and picking newly created Supplier by this statement: if supplier_form_changed: new_supplier = related_supplier_form.save(commit=False) new_supplier.save() .... # This statement seems to have no effect self.object.related_supplier = new_supplier I override the post method with super(), so even though I explicitly state save() method for all related forms, however I don't call the save method of main model (Expenditure) since it is already handled after super(). This is what start and end of my method looks like; def post(self, request, *args, **kwargs): context = request.POST related_receipt_form = self.receipt_form_class(context, request.FILES) related_supplier_form = self.supplier_form_class(context, request.FILES) self.object = self.get_object() related_receipt = self.object.receipt related_supplier_form = self.supplier_form_class(context) expenditure_form = self.form_class(context) inlines = self.construct_inlines() .... return super().post(self, request, *args, **kwargs) You may find the full code of my entire view here: https://paste.ubuntu.com/p/ZtCfMHSBZN/ So my problem is self.object.related_supplier … -
Django Admin - Create object with data from external API
I'm not new to Django, actually I have been using it for a long time now, but I barely use the Django Admin, so there are still a few things that I still don't get completely. I have a model Profile which is created by an User providing an id. I get all the data for creating that profile from an external API with that id, so it is easy to do that in the main API: the User makes a call providing the id, I make a request to this external API, create the object with the provided information and get back to the User with the result. Since I'm starting to use Django admin for an quick/easier User interaction with the data, I wanted to modify the add_form (not the change_form) so there is form with one field, the username and a button to save the data. The idea is the same, get the username, make the cal to the external API, create the object and show it in the Django admin. But I'm not being able. I have tried with overriding the add_form and overriding the ProfileAdmin.save_form but when I save it will fail because of the … -
Python Celery callback failure method executing on each retry
I have a simple celery retry infrastructure but the issue I am facing is that my on_failure method is called on each retry. I am looking for a place where I can add logic that after retries are finished I would like to set an object status to failure. class BaseTask(Task): abstract = True def on_success(self, obj, **kwargs): # this is called only once when the task is completed obj.success=True obj.save() def on_failure(self, obj, **kwargs): # this is called everytime on retry. obj.error=True; obj.save() @task(bind=true, base=BaseTask, max_retries=5, default_retry_delay=60*60) def retry_my_logic_on_error(obj): try: obj.full_name = requests.get(foo) except Exception: self.retry() Is there a different method that is called on failure when the retries are exhausted? Thanks. -
Django test showing Assertion:Error even if the assertion is true
This might not be the best way to do it, as I am learning how to test with Django, but when I try to test a view that involves a form I get: AssertionError: <User[37 chars], fields=(email;first_name;last_name;role;password1;password2)> != <User[37 chars], fields=(email;first_name;last_name;role;password1;password2)> Without considering the fact that the message is not really helpful as the two sides of the equations look exactly the same, the test is the following: class SignUpViewTest(TestCase): def test_get_request(self): path = '/signup/' data = { 'email': '', 'first_name': '', 'last_name': '', 'role': 'Student', 'password1': '', 'password2': '', } form = UserCreationForm() response = self.client.get(path, data=data) print(response.context['form']) print(form) self.assertEqual(response.status_code, 200) self.assertEquals(response.context['form'], form) Being the view: def signup(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Good news {form.cleaned_data["first_name"]}, you have successfully signed up.') return redirect(home) template_name = 'signup.html' context = { 'form': form, } return render(request, template_name, context) Now, as you can see, I am printing the two forms (one is the response context and one is the empty form I request. I don't think you need to see code from models and forms as the error message is quite explicit, even thou I can't see the error. Also, I have checked … -
Unable to restart apache server after updating config file
I have updated my config file so that i can run my django project and then enable config file using sudo a2ensite weeffective.com.conf And then i am trying to restart my apache server sudo service apache2 restart Which gives following error Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. Then run following to identify whats wrong journalctl -xe Which gives me following error Mar 27 12:25:20 instance-weeffictive sudo[13187]: pam_unix(sudo:session): sessio Mar 27 12:25:59 instance-weeffictive sudo[13192]: root : TTY=pts/2 ; PWD=/et Mar 27 12:25:59 instance-weeffictive sudo[13192]: pam_unix(sudo:session): sessio Mar 27 12:25:59 instance-weeffictive systemd[1]: Starting The Apache HTTP Server -- Subject: Unit apache2.service has begun start-up -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- Unit apache2.service has begun starting up. Mar 27 12:25:59 instance-weeffictive apachectl[13198]: apache2: Syntax error on Mar 27 12:25:59 instance-weeffictive apachectl[13198]: Action 'start' failed. Mar 27 12:25:59 instance-weeffictive apachectl[13198]: The Apache error log may Mar 27 12:25:59 instance-weeffictive systemd[1]: apache2.service: Control proces Mar 27 12:25:59 instance-weeffictive sudo[13192]: pam_unix(sudo:session): sessio Mar 27 12:25:59 instance-weeffictive systemd[1]: apache2.service: Failed with re Mar 27 12:25:59 instance-weeffictive systemd[1]: Failed to start The Apache HTTP -- Subject: Unit apache2.service has failed -- … -
How can I place a block of my code into a function?
I have this code in views.py. '''UIERARCHY - INDEX PAGE - NACH LAENDER - COUNTRIES - DEBITORS - ORDERS LEVEL-3''' def uland_world_country_debitor(request, world_id, country_id, debitor_id): qset = BigTable.objects.values( 'deb_nr_f__dcountry__wcode_f__code', #world 'deb_nr_f__dcountry__wcode_f__code_name', #world 'deb_nr_f__dcountry__country_code', #country 'deb_nr_f__dcountry__country_name', #country 'deb_nr_f__dnr', #debitor 'deb_nr_f__dname', #debitor 'id_nr_f__idnr', #order 'id_nr_f__bezeichnung', #order ).annotate( tmp_code=F('id_nr_f__idnr'), tmp_descr=F('id_nr_f__bezeichnung') ).values('tmp_code','tmp_descr' ).order_by('-nerl_2019__sum' ).annotate( abs_2016__sum=Sum('abs_2016'), abs_2017__sum=Sum('abs_2017'), abs_2018__sum=Sum('abs_2018'), abs_2019__sum=Sum('abs_2019'), abs_2020__sum=Sum('abs_2020', output_field=FloatField())/Value(0.205, output_field=FloatField()), nerl_2016__sum=Sum('nerl_2016', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2017__sum=Sum('nerl_2017', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2018__sum=Sum('nerl_2018', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2019__sum=Sum('nerl_2019', output_field=FloatField())/Value(1000, output_field=FloatField()), nerl_2020__sum=Sum('nerl_2020', output_field=FloatField())/Value(205, output_field=FloatField()), db2_2016__sum=Sum('db2_2016', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2017__sum=Sum('db2_2017', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2018__sum=Sum('db2_2018', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2019__sum=Sum('db2_2019', output_field=FloatField())/Value(1000, output_field=FloatField()), db2_2020__sum=Sum('db2_2020', output_field=FloatField())/Value(205, output_field=FloatField()), ).exclude(abs_2016__sum = 0, abs_2017__sum = 0, abs_2018__sum = 0, abs_2019__sum = 0 ).filter(deb_nr_f__dnr=debitor_id, ) Is there a way to assign a big piece of code, for example the large "annotate" block in the middle, to a function and thus shorten and simplify the notation? Thank you. -
Concurrency issue from read/write from table on multiple threads (race condition)
I am building an app where each user is assigned a task from a tasks table. In order to do so, we are going to mark an existing entry as deleted (flag) and then add an entry that holds the person responsible for the task in that table. The issue here is that if multiple users decide to get a task at the same time, the request would prioritize older entries over newer ones, so there is the chance they are going to read the same task and get assigned the same task. Is there a simple way around it? My first inclination was to create a singleton class that handles job distribution, but I am pretty sure that such issues can be handled by Django direct. What should I try? -
Find existing JWT token for user
I've got a function to manually create a new AccessToken for a user (using the rest_framework_simplejwt library): from rest_framework_simplejwt.tokens import AccessToken def create_access_token_for_user(user): access_token = AccessToken.for_user(user) Now I'm trying to write a test to verify that this is actually working as expected, and I can't seem to find any way of getting the AccessToken for a given user. The test should look something like: def test_access_token_created(client): user = create_user() create_access_token_for_user(user) access_token = AccessToken.get_token_for_user(user) # This, but real assert access_token is not None # Or some check to see if it exists The rest_framework_simplejwt docs don't seem to have anything that does this, or at least nothing that I've been able to use correctly.