Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a nested form field or something like that
I'm not entirely sure about the correctness of the question. In fact, I doubt whether I can express exactly what I am looking for. Question: How can I create additional fields based on the previous selection before submitting the form? Let's take the number of pets and the name of the pet in our example. I want how many pet names to be entered first class UrlForm(forms.Form): INT_CHOICES = [(x, x) for x in range(11)] number_of_pets = forms.ChoiceField(choices=INT_CHOICES) and then create as many Charfield fields as the selected value based on the previous selection: #new fields as many as the number of pets pet1 = forms.CharField() pet2 = forms.CharField() Of course, the variable name issue is a separate issue. Question 2: As an alternative approach, can I create a pet name field like a tag field? As in the image: Image taken from here. The question is appropriate but a ReactJs topic. You can share the topic, title, term, article, anything that I need to look at. Thanks in advance. Edit: The pet example is purely fictional. Influenced by the image, I used this topic. -
Django - Autocomplete dropdown field amidst other fields in a form
I am trying to make 1 field in a form an autocomplete dropdown box which lists values from another model, but no success. It is a 'Create' form to feed in employees details. I am new to application developing. So finding difficult in understanding the concepts to implement. Kindly help. here is my model. class State(models.Model): StateCode = models.CharField(max_length=2) StateTIN = models.IntegerField() StateName = models.CharField(max_length=100) def __str__(self): return self.StateName class EmployeeM(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Name = models.CharField(max_length=200) Email = models.EmailField() Contact = models.CharField(max_length=20) State = models.ForeignKey(State,on_delete=models.SET_NULL,null=True) def __str__(self): return self.Name Here is my views, #Create1 html view def create(request): form = EmployeeMForm() if request.method == 'POST': form = EmployeeMForm(request.POST) if form.is_valid(): form.save() return redirect('employeem-list') context = { 'form': form, } return render(request,'EmployeeM/create.html', context) #List States def state_list(request): states = State.objects.all() context = { 'states': states } return render(request, 'State/statelist.html', context) Here is my part of HTML codes where I am trying to make the field 'State' as dropdown box as well as searchable. {% csrf_token %} {{ form.non_field_errors }} {{ form.source }} <table border="1" cellpadding="10px"> <tr> <th>{{ form.Name.label_tag }}</th> <td> {{ form.Name.errors }} {{ form.Name }} </td> </tr> <tr> <th>{{ form.Email.label_tag }}</th> <td> {{ form.Email.errors }} {{ … -
How to provice access for specific users to view certain APIs in django rest framework
I have three APIs created by inheriting APIView class class API1View(APIView): def get(self, request): return Response("API 1 view") class API2View(APIView): def get(self, request): return Response("API 2 view") class API3View(APIView): def get(self, request): return Response("API 3 view") I have three users user1 user2 user3 I three kind of users. customer manager employee Different kind of users should have access to different APIs The Manager can only able to view the API1 and API2 The Customer can only able to view the API1 The Employee can only able to view the API3 In future, I need to able to revoke access of a certain user to certain API. Is it good to use Django Groups or is there any better ways to do it? Or is there any DRF way to do it? (I have seen DRF permissions but I'm not sure if that will work for this scenario.) -
associate vimeo with products using django
I am new to vimeo. I have a database in django that has products, in the table i have a field for video. I need to show the video in my site so i need to use vimeo (embended) but how to associate the video file from vimeo for each product? Is there an attribute where i can put product id in vimeo embendded code? {% for order in item_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ order.product.name }}</td> <td>{{ order.product.category }}</td> <td><a href="{{order.product.video_file}}">{{order.product}}</a> <br/></td> </tr> <br/><br/> {% endfor %} instead of the link for video file i need to play the vimeo video inside my site (embendded), how to do that? -
django How to pass list of data or dictionary using ajaz
i am trying to pass multiple data to my views but it works on single data if i pass list or dictionary i am getting csrf_token incorrect error $.ajax({ type: 'POST', url: '{% url "BugApp:addcomment" %}', data: $("#" + button).serialize(), cache: false, success: function (json) { if(json.status == 1){ $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \ <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \ <div>' + json['result'] + '</div> \ <hr> \ </div>').insertBefore('#' + placement); $('.commentform').trigger("reset"); }else{ window.location.href = 'http://127.0.0.1:8000/account/login' } -
Setting the correct "my_app/static/my_app/example.jpg" static tree structure in Django
According to step 4 in Django's Static Article, best practise is to set up your app's static tree structure as such: my_app/static/my_app/example.jpg ...in order to mitigate duplicate/naming issues when you later run collectstatic as two apps COULD have the same named static files. So how do I set up my app's settings and templates to allot for this kind of structure? Right now, I just have a static folder within each app, and my files inside it. I have my settings.py as such: # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = str(BASE_DIR) + "/media/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = str(BASE_DIR) + "/static/" # URL that handles the static files served from STATIC_ROOT. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' ...and my templates that import from their respective static folders looks like this: <link rel="stylesheet" href="{% static "style.css"%}" /> In order to implement what the article says, do I … -
JsPdf only get one png image element instead of all element
So i kinda confused to use jsPdf and Html2canvas. I have some page like this, https://i.stack.imgur.com/gspxL.png[1] And i need to download whole element on the page except the video. Its already work but instead of printing the whole element, it only takes the face cropped images part like this [https://i.stack.imgur.com/u10vS.png] I use jspdf with html2canvas. And here is the code for the pages <div class="container"> <a class="nav-link" href="{%url 'kepalsuan:home'%}"> <div class="logo text-center mt-1 mb-3"><img src="{% static 'images/logo1.png'%}" alt="Logo"></div> </a> <hr /> <div class="result text-center"> <div id="printedPart"> <!-- <h3>Play to see the Result!</h3> --> <h2>It Takes <span style="font-size:40px;font-weight:600;">{{ duration }}</span> seconds to detect It!</h2> <div class="hasilakhir mt-3"> {%if output == "REAL" %} <img src="{% static 'images/realstamp.png'%}" alt="real" height="100px" width="auto" style="float:left; padding-left:350px;"> <h1 id="realaccuracy" style="color:green; float:right; padding-right:400px; padding-top:20px;">{{ confidence }} %</h1> {%else%} <img src="{% static 'images/fakestamp.png'%}" alt="fake" height="100px" width="auto" style="float:left; padding-left:350px;"> <h1 id="fakeaccuracy" style="color:red; float:right;padding-right:400px;padding-top:20px;">{{ confidence }} %</h1> {%endif%} </div> <hr> <!-- <h1 class="mx-auto mt-5" style="font-weight:900;">Result</h1> --> <h3 style="margin-top:125px;">Face Cropped Frames</h3> <div id="faces_images" class="col-12 mb-2"> {% for each_image in faces_cropped_images %} <img src="{%static each_image%}" class="faces" width="auto" height="150" /> {%endfor%} </div> </div> <video height="320" width="640" id="predict-media" controls> <source src="{{MEDIA_URL}}{{original_video}}" type="video/mp4" codecs="avc1.4d002a" /> </video> </div> <div class="text-center"> <a class="btn btn-warning mt-5 btn-lg" href="javascript:downloadResult()" style="color:white;font-weight: … -
Where to put a GLOBAL .css file for ALL apps to use in Django project?
I've seen similar questions asked on SO, but from the searching I've done I haven't found an answer for this. I know that you can have a static folder in both the project level, and the app level. I have a .css file that I would like ALL apps to utilize. I would think this belongs in the project's static folder, but I don't know how to "access" it from my app's template.html file. My project's tree structure looks like this: | Website | templates - base.html | static | css - style.css | Main_Project | apps | Main_App | templates - app_template.html | migrations - admin.py - models.py - ... The relevant part of my settings.py looks like this: # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = str(BASE_DIR) + "/media/" # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '/media/' # Absolute path to the directory that holds static files. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = str(BASE_DIR) + "/static/" # URL that handles the static files served … -
Accessing Django app in Docker container from another Docker container
Objective I have a docker-compose.yml that, among others, runs three Docker containers that are in the same network: a Django app, nginx and a Selenium image. My objective is to be able to test the Django app from the Selenium container. Problem When trying to make get requests from the Selenium driver driver.get("http://nginx:80") Django refuses the connection on the grounds that the host is disallowed. I get a: Invalid HTTP_HOST header: 'nginx'. The domain name provided is not valid according to RFC 1034/1035. I tried adding the name of the container (nginx) to the ALLOWED_HOSTS variable in settings.py but it still somehow will not accept it. Any ideas? -
Django - ChoiceField without using forms.py file
I’m trying to use a choice field in Django views.py I don’t have the forms.py in this folder. what should i do? models,py class Post(models.Model): category = models.CharField(max_length=100, default='Unclassified') class Category(models.Model): Name = models.CharField(max_length=100, default='Unclassified') views.py class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = [ "category", ] -
Properly migrating Postgres database to Docker/Django/Heroku/Postgres
I have a Django project hosted on an IIS server with a Postgresql database that I am migrating to Docker/Heroku project. I have found a few good resources online, but no luck yet completely. I have tried to use the dumpdata/loaddata function but always run into constraint errors, missing relations, or content type errors. I would like to just dump the whole database and then restore the whole thing to Docker. Here is my docker-compose: version: "3.7" services: db: image: postgres volumes: - 'postgres:/var/lib/postgresql/data' ports: - "5432:5432" environment: - POSTGRES_NAME=${DATABASE_NAME} - POSTGRES_USER=${DATABASE_USER} - POSTGRES_PASSWORD=${DATABASE_PASSWORD} - POSTGRES_DB=${DATABASE_NAME} networks: - hello-world web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - '.:/code' ports: - "8000:8000" env_file: - .env depends_on: - db networks: - hello-world networks: hello-world: driver: bridge volumes: postgres: driver: local -
How to implement Azure AD authentication for a web app developed in Django which is running in a Infrastructure as a service (IaaS)?
There is a web application developed in Django which is running in IAAS server. How can we implement Azure AD in that web application? i.e when some clicks the web app link it should authenticate using Azure AD of a company. -
create custom view permission in django
I need to create a permission that allows the User to see the "Alumno" model, but I only , but I only need it to see the records of that model that have the same foreign key as "id_colegio"... for example, if my User has the foreign key of id_colegio = 1, I need him to be able to see all the records of "Alumno" whose foreign key "id_colegio" = 1 models.py class User(AbstractUser): profesor = models.BooleanField(default=False) rut_user = models.IntegerField(null=True) id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio', null=True,verbose_name="Colegio") class Alumno(models.Model): rut_alumno = models.IntegerField(primary_key=True) dv_alumno = models.CharField(max_length=1) p_nombre = models.CharField(max_length=15 , verbose_name = "Primer nombre") s_nombre = models.CharField(max_length=15, blank=True, null=True) ap_paterno = models.CharField(max_length=15) ap_materno = models.CharField(max_length=15, blank=True, null=True) fecha_nac = models.DateField() genero = models.CharField(max_length=1) direccion = models.CharField(max_length=25, blank=True, null=True) nivel_socio = models.CharField(max_length=10) id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING, db_column='id_examenes') rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING, db_column='rut_apoderado') id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio') id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso') id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') def __str__(self): return f"{self.rut_alumno , self.p_nombre , self.ap_paterno}" class Meta: managed = True db_table = 'alumno' class Colegio(models.Model): id_colegio = models.IntegerField(primary_key=True,verbose_name="Colegio") nombre = models.CharField(max_length=20) telefono = models.IntegerField(blank=True, null=True) direccion = models.CharField(max_length=25) id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna') -
What is the differences between django 1.11 and django 3.8?
So far I have been using Django 1.11.10. I learnt it on this version. But I should upgrade it to 3.8 . How can I do this. Which sites or documentation can I use? What kind of path should I follow? -
Form with image upload not working in Django
I am trying to get this form to work but I seem to be missing something. This is what I have so far. When I submit the form nothing happens, no error message, just a blank form. views.py here is my views file. It only has this one view def add_book_view(request): if request.method == 'POST': form = AddBookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('books:book_list') else: form = AddBookForm() return render(request, 'settings/add_book.html', {'form' : form}) form here is my form. I have stripped out the css because I apparently have too much code and not enough "description". I am really trying to get this solved. <form method="POST" enctype="multipart/form-data"> {% csrf_token %} Title: <input class="settings-form-input" type="text" name="title" maxlength="256" required="" id="id_title"> Author(s): <input class="settings-form-input" type="text" name="authors" maxlength="256" required="" id="id_authors"> Genre: <select name="genre" id="id_genre"> <option value="0" selected="">None</option> <option value="1">Action-Adventure</option> <option value="2">Autobigraphy</option> <option value="3">Biography</option> etc... </select> <br/> Book Cover: <input type="file" name="book_cover" accept="image/*" required="" id="id_book_cover"> <br/><br/> Description: <textarea class="settings-form-textarea" name="description" required="" id="id_description"></textarea> <input type="hidden" name="added_by" id="id_added_by" value="{{ user.first_name}} {{ user.last_name }}"> <input type="submit" class="form-button" value="Add Book"> </form> models.py This is my models file. This form isn't letting me post because it says I have too much code and not enough details so now I am … -
Django OneToMany Add to a specific ID
I got 3 models, OneToMany situation, "Patients => Hospitalized and Consult". I access the form for adding a consult from a DetailView(which is intended to the Patient, like a Profile). How can I add a consult for that specific Patient(specific ID)? Models are like: class Patient(models.Model): NameandLastName = models.CharField(max_length = 50) ... class Consult(models.Model) Patient = models.ForeignKey(Patient, on_delete = models.CASCADE) simptoms = models.CharField(max_length = 50) option_pay = models.CharField(max_length = 40, choices = pay_method) ... (...) - there are more fields. Thanks for your time. -
Add "All" choice to Django ModelForm
I have Django ModelForm to filter data by a certain field - 'model_name' with form method="get" class TruckTripForm(ModelForm): class Meta: model = TruckTrip fields = ['model_name'] This is my view: def table(request): trips = TruckTrip.objects.all() form = TruckTripForm() if request.GET.get('model_name'): models_query = request.GET.get('model_name') trips = trips.filter(model_name=models_query) form = TruckTripForm(request.GET) context = { 'form': form, 'trips': trips } return render(request, 'tripweight/index.html', context) The problem is that I want to add choice 'all' to my form, so i can disable all my filter and get all of my objects. But right now with this ModelForm I can only filter my queryset -
Error in authenticate a websocket with token authentication on django channels?
I face an error when calling the websocket url with passing a JWT token for authentication purpose: my websocket request is: ws://127.0.0.1:8000/chat/chat_2/?token= the error is: raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'chat/chat_2/'. I'm using a custom authentication middleware: middleware.py """ General web socket middlewares """ from channels.db import database_sync_to_async from django.contrib.auth import get_user_model from django.contrib.auth.models import AnonymousUser from rest_framework_simplejwt.exceptions import InvalidToken, TokenError from rest_framework_simplejwt.tokens import UntypedToken from rest_framework_simplejwt.authentication import JWTTokenUserAuthentication from channels.middleware import BaseMiddleware from channels.auth import AuthMiddlewareStack from django.db import close_old_connections from urllib.parse import parse_qs from jwt import decode as jwt_decode from django.conf import settings from django.contrib.auth import get_user_model User = get_user_model() @database_sync_to_async def get_user(validated_token): try: user = get_user_model().objects.get(id=validated_token["user_id"]) print(f"{user}") return user except User.DoesNotExist: return AnonymousUser() class JwtAuthMiddleware(BaseMiddleware): def __init__(self, inner): self.inner = inner async def __call__(self, scope, receive, send): # Close old database connections to prevent usage of timed out connections close_old_connections() # Get the token token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] # Try to authenticate the user try: # This will automatically validate the token and raise an error if token is invalid UntypedToken(token) except (InvalidToken, TokenError) as e: # Token is invalid print(e) return None else: # Then token is … -
Why Django Is fail to run when every thing looks fine, django.core.exceptions.ImproperlyConfigured?
When I Run : python3 manage.py runserver The Error Was : django.core.exceptions.ImproperlyConfigured: Cannot import 'CharacterCounter'. Check that 'FreeOnlineTools.CharacterCounter.apps.CharactercounterConfig.name' is correct. Settings are : Folder Structure : Apps File : Python Version : Python 3.10.4 Which Python is : /home/pythondev/Django/venv/bin/python Requirements.txt : What did i do wrong hear all files are just the default settings? -
Change the foreignKey id to another Field
I don't know if there is a logic for this, because i seen it before when I programed with C# and VB, but in Django, it's seems hard to get it. So what I want to ? I want the table in database save the name and not the id of the foreignKey. And this is the model.py from pyexpat import model from statistics import mode from venv import create from django.db import models from django.contrib.auth.models import User from django.db.models.base import Model from django.forms import IntegerField class Post(models.Model): name = models.CharField(max_length=150) def __str__(self): return str(self.name) class Person(models.Model): post = models.ForeignKey(Post , on_delete=models.CASCADE) name = models.CharField(max_length=100, unique=True) def __str__(self): return f"({self.name} is {self.post})" class Room(models.Model): name = models.CharField(max_length= 150, unique = True) def __str__(self): return str(self.name) class Classification(models.Model): name = models.ForeignKey(Person, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) date = models.DateField(auto_created=False) create_date = models.DateTimeField(auto_created=True) def __str__(self): return f"({self.name} Take {self.room} at {self.date})" The result in Database table: enter image description here What I want to see in the database table, is that Django replace the id's in name_id column with names, and room_id with room names is that possible ? Thank you -
Django request.user resets to AnonymousUser after redirect via url
I have a Django project that is used a basic authentication (django.contrib.auth). I am using a middleware to check if an user is authenticated to redirect to a login page if not. It works as expected until I am using site urls like the following path("edit/<int:id>/", netinventory_views.NodeEdit, name="edit"), path("nodes/<int:id>/", netinventory_views.NodeTest, name="test"), That cause request.user is reset to AnonymousUser. middleware.py: from django.utils.deprecation import MiddlewareMixin from django.shortcuts import redirect from django.conf import settings from django.core.cache import cache EXEMPT_URLS = [settings.LOGIN_URL.lstrip('/')] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URLS += [url for url in settings.LOGIN_EXEMPT_URLS] class AuthRequiredMiddleware(MiddlewareMixin): def process_request(self, request): path = request.path_info.lstrip('/') if request.user.is_authenticated: user = request.user cache.set('_cached_user', user) return else: if path not in EXEMPT_URLS: return redirect('login') -
stand alone django script gets Lost connection to MySQL server during query
I have a standalone python script (i.e. not part of a web app) that makes use of the ORM. I call djago.setup(), make some queries, then call a function that can take 8 hours or more to run. When the function returns I want to make more queries, but they fail with Lost connection to MySQL server during query. My DB wait_timeout is set to 8 hours and if the function returns in less than 8 hours I don't get the error, so I thought I understood what was going on. But then I read about CONN_MAX_AGE which we do not set. If that is not set it should default to 0, which should mean that it gets a new connection for each request so we should not get the Lost connection message. Does that not work when using djago.setup()? Further reading I saw said to call close_old_connections() or connection.close() before calling the long running function. What is the difference between these 2 and is one a better practice than the other? -
prepopulate django formset with certain values
I've struggled for weeks with Django's ModelFormSet & co, head exploding. I searched hours,days on the internet to find a solution, but nothing really helpful for my special problem: I have 2 models (here simplified): class BaseSetting(models.Model): """This is a basic model which holds namespace and key of a setting.""" namespace = models.CharField(max_length=25) key = models.CharField(max_length=255) class ScopedSetting(models.Model): """Model class for all scoped MedUX settings. Settings are generally saved as strings, but are interpreted at retrieval and casted into their correct types. ScopedSettings knows about ``str``, ``int``, ``bool``""" base = models.ForeignKey(BaseSetting, on_delete=models.CASCADE) """The FK to the basic settings fields like namespace, key.""" tenant = models.ForeignKey( Tenant, verbose_name=_("Tenant"), on_delete=models.CASCADE, default=None, null=True, blank=True, ) group = models.ForeignKey( Group, on_delete=models.CASCADE, default=None, null=True, blank=True ) device = models.ForeignKey( Device, on_delete=models.CASCADE, default=None, null=True, blank=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None, null=True, blank=True, ) scope = models.IntegerField(choices=Scope.choices) """The scope where this setting is valid.""" value = models.CharField(max_length=255, null=True) ATM I am using django-extra-views to get a simple ModelFormSetView - and it shows a form, but not what I want: For each BaseSetting (namespace,key) there exists up to 5 different ScopedSettings which could be applicable to the current user, depending on their scope: the vendor, the … -
HOW TO CHANGE THE FOREIGN KEY VALUE AND SAVE IN DB TROUGHT A FUNCTION (RESOLVED)
I WANTED TO CHANGE THE FOREIGN KEY VALUE TROUGHT A FUNCTION. SO HERE IS MY SOLUTION. I THNINK THIS WILL BE HELPFUL FOR SOMEONE ONE DAY. -
Cannot login to Agora RTM with Django and Javascript
I'm having difficulty logging in my RTM client and keep getting Error code 3: RTM:ERROR Error Code 3: login failed with args: {"UID":"l6T1ri6cqWCtEkmy","RTM_TOKEN":"006APP_IDIABVkygsLYuEGlBVKo+r7rsHsmQLZYt/gRZ4pezQayPmhJvA8okAAAAAEAAbLbcBPyeuYgEA6AM/J65i"}. Uncaught (in promise) RtmInvalidArgumentError: Error Code 3 - not a valid user id. A user enters a room name in the lobby page which is used to generate the RTC and RTM tokens. This is the lobby's JS code: <script> let form = document.getElementById('lobby__form') let handleSubmit = async (e) => { e.preventDefault() let room = e.target.room.value.toUpperCase() let response = await fetch(`/get_token/?channel=${room}`) let data = await response.json() let UID = data.userAccount let token = data.token let rtmToken = data.rtmToken sessionStorage.setItem('UID', UID) sessionStorage.setItem('token', token) sessionStorage.setItem('rtmToken', rtmToken), sessionStorage.setItem('room', room) window.open('/room/', '_self') } form.addEventListener('submit', handleSubmit) </script> I generate a random string which I use as a UID in a Django view which acts as my endpoint: from django.http import JsonResponse from agora_token_builder import RtcTokenBuilder from agora_token_builder import RtmTokenBuilder from django.utils.crypto import get_random_string import time def getToken(request): appId = 'APP_ID' appCertificate = 'APP_CERT' channelName = request.GET.get('channel') userAccount = get_random_string(length=16) role = 1 expirationTimeInSeconds = 3600 * 24 currentTimeStamp = time.time() privilegeExpiredTs = currentTimeStamp + expirationTimeInSeconds token = RtcTokenBuilder.buildTokenWithAccount(appId, appCertificate, channelName, userAccount, role, privilegeExpiredTs) rtmToken = RtmTokenBuilder.buildToken(appId, appCertificate, userAccount, role, privilegeExpiredTs) return JsonResponse({'token': …