Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Translate django admin log entry messages
I've a small django mezzanine application in https://github.com/miettinj/mezzanine It translates admin interface correctly, but it also should translate the page history to understandable form. (I guess it comes directly from django_admin_log in database) Now the admin log looks like this: { "model": "admin.logentry", "pk": 2, "fields": { "action_time": "2022-11-18T08:34:03.136Z", "user": 1, "content_type": 18, "object_id": "1", "object_repr": "janes post", "action_flag": 2, "change_message": "[{\"changed\": {\"fields\": [\"Content\", \"Keywords\"]}}]" } } How can I change it so that it translates the action 'changed', remains the field names unchanged and totally removes the unuserfrienly characters: ("[{\) ? -
Implement HTTP methods in different APIView class in django
I have an API with 2 routes some_resource/ and some_resource/<id> and I would like to implement the normal CRUD actions (list, retrieve, create, update, delete). However, I don't want to use ViewSet because I want to have 1 class for each view. Thus I need to set up the route manually for clarity. : class SomeResourceRetrieveView(APIView): def get(self, request, pk, *args, **kwargs): ... class SomeResourceListView(APIView): def get(self, request, *args, **kwargs): ... class SomeResourceCreateView(APIView): def post(self, request, *args, **kwargs): ... So in urls.py it looks like this url_patterns = [ path("some_resource/", InvitationTeamAccessListAPI.as_view(), name="some-resource-list"), path("some_resource/", InvitationTeamAccessCreateAPI.as_view(), name="some-resource-create"), path("some_resource/<int:pk>", InvitationTeamAccessRetrieveAPI.as_view(), name="some-resource-retrieve"), ] However when I use POST on some_resource/, I get a 405. I think django stops at the first matched route and doesn't find an implementation for post. Is there a way to plug all my views to the same pattern but keep them as separate classes? -
Add angular dist folder to Django project
I am doing the following project: https://github.com/ivandmn/Angular-Django In which I make a simple api with django and use angular as frontend, I have already done the ng build of the angular project where I have the "frontend/static" folder with all the static files. My question is how to add the angular files in django, if someone can explain the structure and the code of how to do it, and then how to manage the angular routes together with the Django ones. PS: I have never put an app into production and it is being very complicated for me, if you can help me I would appreciate it Thank you! -
Getting id number (int) from from a model
I'm working with django and i'm trying to retrieve on id number from my profile model class Profile(Model): user = OneToOneField(User, on_delete=CASCADE) image = ImageField(upload_to='accounts/static/images', blank=True, null=True) gender = CharField(max_length=6, choices=GENDER, default='Male', blank=True) biography = HTMLField(blank=True) def __str__(self): return f"{self.user.username} Profile" and in my views i want to get the @login_required def home(request): return HttpResponseRedirect( reverse('profile_view', args=[request.user.objects.id])) when profile id and user id have the same value, every thing is okay. If i delete a profile and then use this view, the pk's won't match. Hot to 'request' it from the profile for a given user ? As above, but this will not work when user and profile have different pk. -
Why is my docker image not running when using docker run (image), but i can run containers generated by docker-compose up?
My docker-compose creates 3 containers - django, celery and rabbitmq. When i run the following commands -> docker-compose build and docker-compose up, the containers run successfully. However I am having issues with deploying the image. The image generated has an image ID of 24d7638e2aff. For whatever reason however, if I just run the command below, nothing happens with an exit 0. Both the django and celery applications have the same image id. docker run 24d7638e2aff This is not good, as I am unable to deploy this image on kubernetes. My only thought is that the dockerfile has been configured wrongly, but i cannot figure out what is the cause docker-compose.yaml version: "3.9" services: django: container_name: testapp_django build: context: . args: build_env: production ports: - "8000:8000" command: > sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/code links: - rabbitmq - celery rabbitmq: container_name: testapp_rabbitmq restart: always image: rabbitmq:3.10-management ports: - "5672:5672" # specifies port of queue - "15672:15672" # specifies port of management plugin celery: container_name: testapp_celery restart: always build: context: . args: build_env: production command: celery -A testapp worker -l INFO -c 4 depends_on: - rabbitmq Dockerfile ARG PYTHON_VERSION=3.9-slim-buster # define an alias for the … -
Django Initial Usage for getting latest id to print to form
I wanna make patient register form and i want each new patient start with initial number. So this is my form. I did these views.py codes but, on the screen nothing. How can i fix this. And then my real goal is start patient register with a default=0 id and then each new patient id must be +1 extra. How can i do this. Thanks for help. Here are my codes. Models.py class Patient(models.Model): GENDER_CHOICES = ( ("M", "Male"), ("F", "Female"), ("O", "Other") ) """ aadhaarId = models.AutoField(primary_key=True ) """ aadhaarId = models.CharField(primary_key=True, max_length=6, help_text= "12 digit aadhar no" ) name = models.CharField(max_length=20) date_of_birth = models.DateField(max_length=8, help_text="YYYY-MM-DD") gender = models.CharField(choices=GENDER_CHOICES, max_length=1) # Patients will be sorted using this field last_updated_on = models.DateTimeField(auto_now=True) class Meta: verbose_name = "patient" verbose_name_plural = "patients" ordering = ["-last_updated_on"] def __str__(self): return self.name + '-' + self.aadhaarId views.py @login_required() def patientCreate(request): if request.method == "POST": intaial_data = { 'aadhaarId': '999088'} form = PatientForm(request.POST, initial=intaial_data) id = request.POST['aadhaarId'] if form.is_valid(): try: form.save() messages.success(request, 'New Patient is successfully added.!') model = form.instance return redirect('/patient-detail/{}'.format(id)) except: messages.error(request, 'failed to add patient') else: form = PatientForm() return render( request, 'patient_records/patient-create.html', {'form': form} ) -
Django - how to filter a model in a foreign key field?
I have two models for categories: list of categories for all users (each unique) and list of connections between user and category. category/models.py class CategoryList(models.Model): name = models.TextField(unique=True, max_length=60, verbose_name='Category name') def __str__(self): return f'{self.name}' class UserCategories(models.Model): category = models.ForeignKey(CategoryList, on_delete=models.deletion.CASCADE, verbose_name='User's categories') user = models.ForeignKey(User, on_delete=models.deletion.CASCADE, verbose_name='User') def __str__(self): return f'{self.category.name}' Also i have transactions: transactions/models.py class Transaction(models.Model): user = models.ForeignKey(User, on_delete=models.deletion.CASCADE, verbose_name='Transaction from') payment_amount = models.DecimalField(default=0, decimal_places=2, max_digits=20, verbose_name='Payment amount') date = models.DateField(auto_now=True, verbose_name='Date') time = models.TimeField(auto_now=True, verbose_name='Time') category = models.ForeignKey(UserCategories, null=True, on_delete=models.deletion.SET_NULL, verbose_name='Category') organization = models.TextField(max_length=60, verbose_name='Organization') description = models.TextField(max_length=300, null=True, blank=True, verbose_name='Transaction discription') I have the next issue: i'm using DRF to do CRUD operations with transactions and when i'm trying to add transaction (it select's current authorized user) or update it - i get all the categories in field category = models.ForeignKey(UserCategories...) and that's not what i want. As i understand selecting a model in foreign key is something like models.ForeignKey(UserCategories.objects.all()), but that's not what i want... I need smth like filtration, while creating/updating transaction it have to show me only list of categories for my current user, not for all! I need final result like category = models.ForeignKey(UserCategories.objects.filter(user=user)) but i don't know (and even … -
Django DRF: "Positional argument follows keyword argument unpacking" when trying to add current user
I'm trying to add the currently logged in user into the "user" foreign key field in the "LeadFacilityAssign" model, everytime a leadfacility object gets created. But I'm getting this: "Positional argument follows keyword argument unpacking" models.py class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) agent = models.ForeignKey("User", null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssign(models.Model): assigned_facilities = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='leadfacility', null=True, blank=True) lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='leadfacility', null=True, blank=True) datetime = models.DateTimeField(null=True, blank=True) user = models.ForeignKey('User', on_delete=models.CASCADE, null=True, blank=True, related_name='owner') serializers.py class AssignedFacilitySerializer(serializers.ModelSerializer): class Meta: model = LeadFacilityAssign fields = ('assigned_facilities', 'datetime', 'user') class LeadUpdateAssignedSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = AssignedFacilitySerializer(required=False, many=True, allow_null=True) class Meta: model = Lead fields = ( "id", "agent", "is_owner", "assigned_facilities", ) read_only_fields = ("id", "agent", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def update(self, instance, validated_data): assigned_facilities = validated_data.pop("assigned_facilities", []) user = self.context["request"].user instance = instance for item in assigned_facilities: instance.leadfacility.create(**item, user) return instance -
I need to make regular working Queue when its not empty in Django
PROJECT: I am making a web app, where users send a ZIP file, it saves to the folder. There is a VM continuously looking for that folder where the zip gets extracted. Note that VM is only 1. So I have to extract, sleep for 20 seconds and remove the files from that folder, VM generates the results, then my Django app generates a CSV from those files, and return to user as downloadable. This is the flow. Problem: MultiUsers: I am using a file, like below def Uplaoder(request): file=takenFromPost() #lets assume this works. with open('busy.txt', 'r') as f: if "false" in f: with open('busy.csv', 'w') as f: f.write('true') #here I made it true so that if its true, the request doesn't disturb it as single VM f.close() finalcsv=workFurther() #here is the whole process lets say. with open('busy.csv', 'w') as f: f.write('false') f.close() return render(request, 'worked.html', {'finalcsv':finalcsv}) elif "true" in f: Uploader(request) #here I send this request again to this so that the user keeps waiting and when the #files gets generated for the second user, he gets the response. Here is the example logic, same as my code works. Problem: Logic seemed me well but the browser doesn't wait … -
User accessible in views but not in template
I am trying to use {% if user.is_authenticated %} in a template, but the user actually doesn't exist. If I try to output {{ user }}, there is nothing. In my settings I have those options for TEMPLATES: "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", I developed an authentication backend class to use the credentials of the active directory and added the class to AUTHENTICATION_BACKENDS in settings.py. class CustomAuthenticationBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): """ Authenticate user from active directory If user is not found, create it """ # Get user from database try: user = User.objects.get(username=username) # If user does not exist, create it except User.DoesNotExist: user = User(username=username) user.displayed_name = kwargs['display_name'] user.email = kwargs['email'] user.save() return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None I added the authenticate logic and the login logic to a django Form: def authenticate_and_login(self, request) -> bool: """ Method to authenticate the user and login return True if user is authenticated and logged in or False and fill the form with errors """ is_logged = False # Init active directory service ad_service = ActiveDirectoryService() # Get username and password username = self.cleaned_data['username'] password = self.cleaned_data['password'] # Get authorized user from … -
How to store mathematical symbols and formulas in column sqlalchemy Postgres as DB
I have two questions: What I want to do is to be able to store a mathematical question with special symbols, formulas that are part of the text. What column should I define in SQLAlchemy so that I can get back the equation without any issue. Second part involves in data entry, I want to upload questions in bulk, now the special symbols cannot be defined/written as text in excel, I was able to do it in MSWord. Is there any specific rules that I can define so I can read the equation in that rule and transform it into mathematical equation. For Ex. similar to latex, if we type [\sqrt{x^2+1}], we see the math format in pdf. That way I can provide a input text where they can write equations in that format and it automatically converts it into math formulae and display it as such. Now is there any intelligent way to achieve this? I'm using Fastapi with SQLAlchemy and for database, I'm using Postgres. If you could point me to relevant resources, that would have great help. -
Django with mysql, faced 'table doesn't exist' error randomly at different times of the day
I'm currently using Django version 2.2.28 with mysql innodb engine version 5.7, before some days i faced a crazy issue, here: (MySQLdb._exceptions.ProgrammingError) (1146, "Table 'db_name.table_name' doesn't exist") What's driving me crazy is that they happen on different tables at different times (not always). I couldn't even get a specific pattern. i can confirm no change in the code happened from along o week and no release happened, The problem started happening 3 days ago and randomly, same table is currently working fine and a minute later the same exception is returned and then back to working fine. i used RDS from AWS, and have different DBs under of it, the issue happening only on one of these DBs. i also checked logs file from mysql and i don't fond any thing useful, i just found errors like this [ERROR] InnoDB: MySQL is freeing a thd though trx->n_mysql_tables_in_use is 2 and trx->mysql_n_tables_locked is 654 and i think it's irrelevant. I make sure about all permissions for the user too. and i did a failover for the whole RDS and nothing working. I don't think it has to do with django's migration command, because this problem always happened randomly. can any one … -
Static files apply on all pages except index.html and base.html
I have an issue about static files. i uploaded the code on pyanywhere all good, it runs, i linked the static urls in pyanywhere>web page corectly. the issue is that my static does not load on the index and base.html but on the other pages (where i have base.html extend it applies). Can you give me some support please? how it looks python anywhere url STATIC_URL = 'static/' STATIC_ROOT = "home/Tsh2Dns/businessplaner/static/" #i tried to give root from pythonanywhere. still same response STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATICFILES_DIR = [ os.path.join(str(BASE_DIR.joinpath('static')),) ] folders: -
How to use a custom ModelForm in User admin
I'm trying to limit standard user possibilities in the User application Django's admin, to avoid the possibility of privileges escalation. I've tried the approach mentioned in docs: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form class UserAdmin(BaseUserAdmin): form = UserForm inlines = (UserProfileInline,) def get_form(self, request, obj=None, **kwargs): if request.user.is_superuser: kwargs["form"] = SuperUserForm return super().get_form(request, obj, **kwargs) class UserForm(ModelForm): class Meta: model = User exclude = ("is_superuser",) # it is just an example class SuperUserForm(ModelForm): class Meta: model = User fields = "__all__ Unfortunately, this results in such an error: "Key 'is_superuser' not found in 'UserForm'. Choices are: date_joined, email, first_name, groups, is_active, is_staff, last_login, last_name, password, user_permissions, username." If I would decide to exclude "groups": "Key 'groups' not found in 'UserForm'. Choices are: date_joined, email, first_name, is_active, is_staff, is_superuser, last_login, last_name, password, user_permissions, username." -
Django html css
I hava a problem with a background image, I can't load the picture on the page, I don't know what the problem is Here is my code: <style> body { background-image: url("../img/mountains.jpg"); } </style> enter image description here -
SMTPSenderRefused at /contacts
I am using Django. I want to send email via html contact form. And I am facing this error: SMTPSenderRefused at /contacts (530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: http://127.0.0.1:8000/contacts Django Version: 4.1.2 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Must issue a STARTTLS command first. p6-20020a1c5446000000b003b47e75b401sm7708347wmi.37 - gsmtp', 'webmaster@localhost') Here is my settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TSL = True EMAIL_HOST_USER = 'email@gmail.com' EMAIL_PASSWORD = 'Key' EMAIL_PORT = 587 EMAIL_USE_SSL = False Here is my view.py def contacts(request): selected = "contact" if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('comments') data = { 'name':name, 'email': email, 'subject': subject, 'message': message } message = ''' New Message : {} From : {} '''.format(data['message'], data['email']) send_mail(data['subject'], message,'' ,['qweaverinfo@gmail.com']) return render(request, 'layouts/auth-signup-success.html', locals()) return render(request, 'layouts/contact.html', locals()) I don't understand how to fix the STARTTLS. Is anyone here to help me? I tried to use the SSL, I met the same problem. I want to the Django documentation, I did not find anything about the STARTTLS command. I was expecting to send email via a html template using Django. -
What is the diffenrence between psycopg2 vs psycopg3
please give me short explanation what is the difference between https://pypi.org/project/psycopg/ and https://pypi.org/project/psycopg2/ If i have Django3.2 what i have to use? Any advantages? In official manual i didn't see any remarks about psycopg. There is only psycopg2 https://docs.djangoproject.com/en/3.2/ref/settings/#std-setting-DATABASES I tried to migrate my project from sqlite to postgres 9 -
Django Creation View Doesn't save any data
My creation view redirect to blog main page well after creation but i can't find any post's been created in the posts or admin page posts, can anyone help please here is my view @login_required def add_post(request): if request.method == 'POST': post_form = PostForm(request.POST, request.FILES, instance=request.user) snippet_form = SnippetForm(request.POST) if post_form.is_valid() and snippet_form.is_valid(): post = post_form.save(commit=False) snpt = snippet_form.save(commit=False) post.creator = request.user snpt.id = post.id post.save() and snpt.save() return redirect('blog:index') else: post_form = PostForm() snippet_form = SnippetForm() return render(request, 'blog/add_post.html', {'post': post_form, 'snpt': snippet_form}) what's wrong in this view cause i been able to save new post from admin add new post but from client it doesn't save anything Do I need to use model create() method here or what? *Any required snippet i will provide but the problem is in this snippet any help is really appreciable -
Multiple models and multiple serializer in single response in DRF
I'm creating a search functionality that returns all model fields like - users, posts, hashtags, images, and videos. I'm trying to create multiple queryset with their multiple serializers to return in a single response. this is my expected response result. { searchresults{ posts[ ],images[ ],videos[ ],user[ ] } } I tried many methods to do this, but the response was unsuccessful. I also tried that one but that required relationship. class HashTagResponseSerializer(serializers.ModelSerializer): class Meta: model = HashtagName fields = ["hashtag",] def get_hashtag(self, obj): ... class UserFollowSerializer(serializers.ModelSerializer): hashtag = HashTagResponseSerializer(many=True, read_only=True) class Meta: model = User fields = ['user_uuid', 'post_language', "username", "display_name", "profile_picture", "hashtag "] -
Creating a new model with a one-to-one relationship with an existing model Django
I want to add a Profile model relationship through a one-to-one field to the existing User model. However I already have a couple of users in the database. How can I migrate the new model while creating these default relationships at the same time? So for example I have two users Foo and Bar already created in the database and after migrating the Profile model both users should have an associated Profile with them. Models class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) first_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "surname"] def get_full_name(self): return f"{self.first_name} {self.surname}" def __str__(self): return self.email def is_staff(self): return self.staff def is_admin(self): return self.admin ### New model I want to create class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default="gravatar.jpg", upload_to="avatars/") username = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return f"{self.user.first_name}'s profile" -
Adding custom title to django form fields
I would like to add custom title to one of my form fields. I made some modifications but it still not working. My forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30) phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] labels = {'fixed_by' : 'Fixed by/Assigned to'} ` my models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') ` Need to change the form field title "Fixed by" to "Fixed by/Assigned to" -
django django.db.models.query_utils.DeferredAttribute object at 0x000
I'm trying to create a custom id for my project def get_default_id(): last_cl_itemid = ClearanceItem.objects.all().order_by('cl_itemid').last() if not last_cl_itemid: return str(ClearanceItem.sem)+ '00' class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=255, default=get_default_id) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' When I try to post something like this { "sem": "1", } It's should look like this 1-00 but When I check the rows in the ClearanceItem <django.db.models.query_utils.DeferredAttribute object at 0x0000024D625844C0>00 How can I do this or any alternative solution -
Removing items from a list in a request.session is not working I do not understand why
I try to create a basic Q&A game. In the request.session['questions'] I am saving the questions I want to render . The flow should be : Question 1 as son the form is loaded --> once the user click next question 2 shoul be rendered an so on until the request.session['questions'] is empty. whit the following code I Only could show the 2 first options and I don`t know why is not working as expected. def game(request): if request.method == 'GET': request.session['questions'] = ['question1','question2','question3','question4'] print(request.session['questions']) q = request.session['questions'].pop(0) form = QForm({'question':q}) print(request.session['questions']) return render(request, 'game.html', {'form':form}) else: if request.method == 'POST' and len(request.session['questions']) >0: q= request.session['questions'].pop(0) print(name) form = QForm({'question':q}) return render(request, 'game.html', {'form':form}) else: return redirect('home') -
Time gap between message.errors in django
I created a Django app with a form. when the form is submitted and found error, messages.error(request, e) is called, where e is the error text. the real code for field, errors in form.errors.items(): print('Field: {} Errors: {}'.format(field, ','.join(errors))) e = 'Field: {} Errors: {}'.format(field, ','.join(errors)) messages.error(request, e) if I have multiple errors, multiple error boxes pops up at same time, but I want to make a time difference of .5seconds between each error popup. I saw time.sleep(0.5) but the issue is it just takes timegap inside forloop not in gap between the popup. There might be a JS fix, I would like to know how here's my html code {% if messages %} {% for message in messages %} {% if message.tags == 'alert-success' %} <!-- Toast --> <div data-toast data-toast-text="{{ message }}" data-toast-gravity="top" data-toast-position="right" data-toast-className="success" data-toast-duration="2000" class="noty-tost d-none rounded shadow bg-success"></div> {% endif %} {% if message.tags == 'alert-danger' %} <!-- Toast --> <div data-toast data-toast-text="{{ message }}" data-toast-gravity="top" data-toast-position="right" data-toast-className="danger" data-toast-duration="5000" class="noty-tost d-none rounded shadow bg-danger"></div> {% endif %} {% endfor %} {% endif %} $(document).ready(function () { $('.noti-toast').click() }); // used to trigger it(using toastify.js from a template, i don't really know much about it, but … -
How to manullay generate a new drf-simplejwt access token post the expiry of old access token using the pre-genrated refresh token for specific user?
I am using django restframework's simplejwt library to manually create tokens for user using the below function. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } The above function get_tokens_for_user will return the serialized representations of new refresh and access tokens for the given user. This function is called while user registration and login. However, after the access token is expired, a new access taken needs to be generated using the refresh token. I am unable to figure out the way/method/function for generating new access token with the refresh token.