Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Choosing frameworks for creating the platform for students
I wanna create a platform as a project for my university. Here are main features: the teacher can create tests and run them at specific times students are limited in time and can pass tests (each test has got it's own time limit) there is an overall student ranking on the home page the teacher can publish the homework What should I choose? I am thinking about Django + React. What would you recommend? -
I can't receive tokens on android app from the django server
I am trying to figure out why I can not receive access tokens on my android app from the django server. The android app structure seems fine to me. Still the issue persists. I tested the server response with postman and it looks fine (I receive both, access and refresh tokens) but on my android app that does not work. I share with you some code snippets hoping someone here could help me. Thank you in advance anybody! LOGIN FUNCTION suspend fun loginUser(userService: UserService, email: String, password: String, context: Context, navController: NavController) { try { val response = userService.loginUser(UserLoginRequest(email, password)).await() if (response.isSuccessful) { val tokenResponse = response.body()!! TokenManager.saveTokens(tokenResponse.accessToken, tokenResponse.refreshToken) withContext(Dispatchers.Main) { navController.navigate(Screen.FeedScreen.route) } } else { withContext(Dispatchers.Main) { Toast.makeText(context, "Login failed: ${response.message()}", Toast.LENGTH_LONG).show() } } } catch (e: Exception) { withContext(Dispatchers.Main) { Toast.makeText(context, "An error occurred: ${e.localizedMessage}", Toast.LENGTH_LONG).show() } } } TOKEN MANAGER package com.example.events.util import android.content.SharedPreferences import android.util.Log import com.example.events.network.NetworkModule import com.example.events.network.RefreshRequestBody import com.example.events.network.RefreshTokenResponse import com.example.events.network.TokenRefreshService import com.google.gson.Gson object TokenManager { private lateinit var preferences: SharedPreferences // Initialise with SharedPreferences fun init(preferences: SharedPreferences) { this.preferences = preferences } val accessToken: String? get() = preferences.getString("access", null) fun isTokenExpired(): Boolean { val expiry = preferences.getLong("expiry", 0) return expiry < System.currentTimeMillis() } … -
How to enable dynamic custom domains
I am a developer for a SAAS web app and excel plugin. With our product, users are able to share outputs of their work with third parties via a browser link. The format of the browser link today is nameofourwebsite.io/titleofoutput. I'm looking to implement two versions of a feature: As a V1, I'd like to enable users to create a custom domain in the form of companyname.website.io/titleofspreadsheet. I am already the owner of the domain website.io. As a V2, (to be implemented at a later date), I'd like for users to be able to bring their own custom domain, similar to the implementation with Stripe (https://docs.stripe.com/payments/checkout/custom-domains). In other words, when a user shares a browser link to the output of their work instead of the link being companyname.website.io/titleofspreadsheet the browser link would be something along the lines of customprefix.companywebsite.com/titleofworkbook. I am not sure how to tackle this problem and I am looking for advice as to the steps we need to take. -
How to ensure changes to variables in .env file reflect in Django project?
I'm encountering an issue in my Django project where changes made to variables in the .env file do not seem to be reflected when I restart the server. Here are the steps I've taken: Verified that the .env file is in the correct location and its name is exactly .env. Restarted the Django development server after making changes to the .env file. Double-checked the syntax of the .env file for any errors or typos. Cleared the cache after making changes to the .env fil (using python manage.py clear_cache) -
In Django, is it possible to use reverse/redirect with a view function (not string) as a to parameter, when using namespaces?
I'm trying to get reverse (via redirect) to work in the context of namespaces and when using view functions. This fails with a NoReverseMatch, somewhat to my surprise. In principle, I'd say that it's out-figurable in an automatic way what I mean. When using this without app_name = ... this works fine. Is this a bug (or simply unsupported)? Or is there a way it could be made to work? # urls.py from django.urls import path from .views import some_other_view, some_view app_name = 'foo_app' # here the app namespace is defined urlpatterns = [ path('some_other_view/', some_other_view), path('some_view/', some_view), # ... ] # views.py from django.shortcuts import redirect def some_other_view(request): return redirect(some_view) # note that the view is simply passed as a function here, not as a string. def some_view(request): # ... actual view here -
Send data from one table to another when instantiated django
What I want is that when creating an instance of the user object the name goes to another table called profile_data but I don't know how to do it, can someone help me? -
Django and django-mssql - problem with rendering ForeignKey field in ModelForm
In my Django application I would like to use 2 databases. First (default one) - sqlite3 and second MS SQL. Since Django don't support MsSQL I'm forced to use 3rd party django-mssql package. I have model with ForeignKey and ModelForm based on this model. The problem is that I get an error "no such table: TLC_OWDP_InstructionParameters" while trying to render ForeignKey form field. It looks like django tries to find the table in wrong database. I tried use PostgreSQL instead of MS SQL and everything works fine. Could someone please help me with this issue? My code below: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'logistyka': { 'ENGINE': 'mssql', 'NAME': 'LOGISTYKA', 'HOST': 'WPLRZD0A', 'PORT': '', 'USER' : '***', 'PASSWORD' : '***', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } models.py class InstructionParameter(models.Model): id = models.AutoField(db_column='id', primary_key=True) instr_number = models.CharField(max_length=30, verbose_name='Numer instrukcji') tab_number = models.SmallIntegerField(verbose_name='Numer tabeli', validators=[MinValueValidator(1), MaxValueValidator(99)]) point_number = models.SmallIntegerField(verbose_name='Numer punktu tabeli', validators=[MinValueValidator(1), MaxValueValidator(99)]) def __str__(self): return f'{self.instr_number} tab.{self.tab_number} p.{self.point_number}' class Meta: verbose_name_plural = 'Instrukcje' managed = False db_table = 'TLC_OWDP_InstructionParameters' class PartParameter(models.Model): id = models.AutoField(primary_key=True) part_number = models.CharField(max_length=30, verbose_name='Numer części') op_number = models.CharField(max_length=4, verbose_name='Numer operacji') instruction_id = models.ForeignKey('InstructionParameter', to_field='id', db_column='instruction_id', … -
one of many python attributes not carrying over to children in GitHub class, with and without Django support
When i subclass my GitHubIssues class (see below), all the children have the expected attributes EXCEPT self.repo_object... when i redeclare it in child classes, it functions as it should... but i shouldn't need to do this if my knowledge of inheritance is correct. class GitHubIssues: class UnknownRepositoryError(UnknownObjectException): ... def __init__(self, repo_name: str, github_key_path: str, data: dict = None): # TODO: test this as standalone more. self.repo_name = repo_name self.repo_obj = None self._IsDjangoForm = None self._GitHubKeyPath = github_key_path self._GitHubKey = None self._IsInIssues = None if not self.IsDjangoForm: self.data: dict = data self.cleaned_data: dict = self.data self.errors: list = [] self.repo_obj = self.GetRepoObject() # other attributes omitted for brevity def GetRepoObject(self): try: g = Github(self.__GitHubKey) for repo in g.get_user().get_repos(): if repo.name == self.repo_name: self.repo_obj = repo return self.repo_obj except BadCredentialsException as e: self.add_error(None, e) except GithubException as e: self.add_error(None, e) except Exception as e: self.add_error(None, e) if isinstance(self.repo_obj, Repository.Repository): pass else: try: raise self.UnknownRepositoryError(404, data=self.repo_obj, message=f"Could not find {self.repo_name}") except self.UnknownRepositoryError as e: self.add_error(None, e) class BugReportForm(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._issue_added = None if kwargs: if 'repo_name' in kwargs: self.repo_name = kwargs['repo_name'] else: self.repo_name = 'BackflowPreventionValveCatalog' if 'GitHubKeyPath' in kwargs: self._GitHubKeyPath = kwargs['GitHubKeyPath'] else: self._GitHubKeyPath = #redacted path else: … -
I created a new model and registered it to admin.py but when I am running python manage.py makemigrations it showing that no migrations to apply
In models.py: from colorfield.fields import ColorField class colour(models.Model): color=ColorField(format="hexa") def __str__(self): return str(self.id) In admin.py: admin.site.register(colour) When I am running python manage.py makemigrations it says: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'userauths' isn't unique. You may not be able to reverse all URLs in this namespace No changes detected And when I am running python manage.py migrate it says: System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'userauths' isn't unique. You may not be able to reverse all URLs in this namespace Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Now When I am going to admin pannel there is a table called colour but when I am clicking it there is an no such table: core_colour error -
Containerized Django application works on local, but not on GKE
Any containerized Django applications work in local, but only return "no healthy upstream" when run on GKE. I tried with this django example: https://github.com/mukulmantosh/cloud-code-helloworld on which I only commented out the mysqlclient in the requirements.txt file. In GKE the application runs behind an ingress internal load balancer (I have no access to Cloud Run for some corporate reason). What I get in local mode: (base) C:\Users\path\to\app>docker run -p 8080:8080 helloworld:1 [21/Feb/2024 10:54:17] "GET / HTTP/1.1" 200 3968 [21/Feb/2024 10:54:17] "GET /static/KE-hello-world.svg HTTP/1.1" 200 116030 [21/Feb/2024 10:54:17] "GET /static/cloud_bg.svg HTTP/1.1" 200 7213 [21/Feb/2024 10:54:17] "GET /static/kubernetes-engine-icon.png HTTP/1.1" 200 6967 [21/Feb/2024 10:54:19] "GET / HTTP/1.1" 200 3968 What I get in the Workload logs on GCP: 2024-02-21 12:03:40.613 CET Not Found: / 2024-02-21 12:03:40.613 CET [21/Feb/2024 11:03:40] "GET / HTTP/1.1" 404 2272 -
Error when starting Django React app with npm start: "Invalid options object" ( 'Something is already running on port 5432' )
`I have a Django-React application with PostgreSQL/MySQL. The app was working fine, until today I attempted to start my frontend using npm start. This is the first time I've encountered the following prompt: ? Something is already running on port 5432. Would you like to run the app on another port instead? » (Y/n) Opting for 'Y' leads to the subsequent error: Would you like to run the app on another port instead? ... yes Invalid options object. Dev Server has been initialized using an options object that does not match the API schema. options.allowedHosts[0] should be a non-empty string. I haven't made any recent changes or installations. What should I do ? I tried to change the start script in the package.json to "start": "set PORT=3000 && react-scripts start", but that didn't work. Additionally, I deleted node_modules, package-lock.json, and ran npm install, but I still got the same error message. -
python Django Field 'id' expected a number but got '{"isTrusted":true}'
mistake:Field 'id' expected a number but got '{"isTrusted":true}' When I attempt to perform the delete operation, an error is being reported, and I'm unsure how to resolve it. view.py class ClassAdminAPI(APIView): @validate_serializer(CreateClassSeriaizer) @super_admin_required def post(self, request): class_data = request.data class_data["title"] = class_data.get("title") class_data["start_time"] = dateutil.parser.parse(class_data["start_time"]) class_data["end_time"] = dateutil.parser.parse(class_data["end_time"]) class_data["created_by"] = request.user if class_data["end_time"] <= class_data["start_time"]: return self.error("Start time must occur earlier than end time") user_data = class_data.pop("users") try: with transaction.atomic(): if Class.objects.filter(title=class_data["title"]).exists(): return self.error("Class with the same title already exists") class_obj = Class.objects.create(**class_data) for data in user_data: if len(data) != 4 or len(data[1]) > 32: return self.error(f"Error occurred while processing data '{data}'") username = data[1] + data[2] user, created = User.objects.get_or_create(username=username, defaults={ "password": make_password(data[1]), "college": data[3], "student_number": data[1] }) if created: profile = UserProfile(user=user, real_name=data[2]) profile.save() class_obj.users.add(user) return self.success(ClassSerializer(class_obj).data) except IntegrityError as e: return self.error(str(e).split("\n")[1]) @super_admin_required def get(self, request): class_id = request.GET.get("id") if class_id: try: class_obj = Class.objects.get(id=class_id) ensure_created_by(class_obj, request.user) return self.success(ClassSerializer(class_obj).data) except Class.DoesNotExist: return self.error("Class does not exist") classes_obj = Class.objects.all().order_by("-create_time") # print("classes_obj:", classes_obj) if request.user.is_admin(): classes_obj = classes_obj.filter(created__by=request.user) print("classes_obj:", classes_obj) return self.success(self.paginate_data(request, classes_obj, ClassSerializer)) @super_admin_required def delete(self, request): Class_id = request.GET.get("id") if not Class_id: return self.error("Invalid Parameter, id is required") class_ids = Class_id.split(",") if Class.objects.filter(id__in=class_ids, created_by=request.user).exists(): return self.error("Current … -
Getting Forbidden (403) CSRF verification failed
I am using Django, DRF , docker, Nginx and AWS EC2 instance for my personal project, application is working fine when it is using HTTP , once i changed to HTTPS i am getting CSRF Verification Failed. used {% csrf_token %} where required in html forms in settings.py CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['http://localhost/', 'example.co.in', 'www.example.co.in'] CORS_ORIGIN_WHITELIST = ['http://localhost/', 'example.co.in', 'www.example.co.in'] Please help me in solving this issue, thank you everyone -
Zegocloud video call Recording issue
How to record video calls using zegocloud,i have created the server call backurl in the admin console but when i call the start record api endpoint of zegocloud its not start recording,Can any body help me to resolve the issue? -
Problem returning context_processor data to html for looping
I'm trying to add categories field to navigation. So far I've made context_processor which querys all the car brands. In my navigation I'm loopin all of the brands and this works. I also want to add dropdowns which contains certain car models for certain car brands. I think the problem lays in returning right data, that is loopable in my _base.html. _base.html <div class="flex pt-3 container w-full"> {% for item in car_brands %} <button id="dropdown-button" data-dropdown-toggle="dropdown-{{item.id}}" class="py-2.5 px-4 text-sm font-medium text-center text-gray-900 bg-gray-100 uppercase" type="button">{{item}}</button> <div id="dropdown-{{item.id}}" class="hidden shadow w-44 bg-gray-100"> <ul aria-labelledby="dropdown-button"> {% for model in models %} <li> <a href="#" class="inline-flex w-full px-4 py-2 hover:bg-gray-50">{{ model }}</a> </li> {% endfor %} </ul> </div> {% endfor %} context_processors.py from .models import CarBrandCategory, CarModel def brand_catalogue(request): car_brands = CarBrandCategory.objects.all() for brand in car_brands: models = [model for model in CarModel.objects.filter(brand_id=brand.id)] print(models) return { 'car_brands': car_brands, 'models': models } If printing, it will give me different lists, consists of different models, eg. [<CarModel: X4>, <CarModel: X5>, <CarModel: 3. Seeria>] [<CarModel: A4>, <CarModel: A6>, <CarModel: A8>] [<CarModel: C klass>, <CarModel: S-Klass>] I was wondering if anyone has experience with this kind of solutions and what could be the most optimal way to … -
Django Rest Framework Pagination isn't working
My settings.py: 'DEFAULT_AUTHENTICATION_CLASSES': [ # 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.BasicAuthentication', # 'rest_framework.authentication.SessionAuthentication', 'authentication.authentication.ExpiringTokenAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, } My views.py: permission_classes = [IsAuthenticated] queryset = Post.objects.all().order_by('-id') serializer_class = PostSerializer pagination_class = PageNumberPagination The code should show 10 result in each page. But it's showing all the 13 result. The result is like this: { "count": 13, "next": null, "previous": null, "results": [ { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_SJpZeBc.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_Fs2qSAY.webp", "order": 2 } ], "caption": "my name is ayon", "created_at": "2024-02-21T09:40:46.069468Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_AvXbLoq.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_lRnFcgd.webp", "order": 2 } ], "caption": "friends will be great", "created_at": "2024-02-21T09:40:40.146627Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_XcnIJ6o.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_MPj4huO.webp", "order": 2 } ], "caption": "friends", "created_at": "2024-02-21T09:40:36.631495Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_LdvliP2.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_nLRwhrS.webp", "order": 2 } ], "caption": "friends foreever", "created_at": "2024-02-21T09:40:33.934885Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_iFAk1XG.jpeg", "order": 1 }, { "image": "http://127.0.0.1:8000/post_pics/temp_EEnnvOX.webp", "order": 2 } ], "caption": "friends foreever", "created_at": "2024-02-21T09:40:27.121978Z" }, { "author": 2, "images": [ { "image": "http://127.0.0.1:8000/post_pics/temp_IrIuNi9.jpeg", "order": 1 }, { … -
email activation failing in django
how im sending the activation email current_site = get_current_site(request) email_subject = 'confirm your email !' message2= render_to_string('authentication/emailConfirmation.html',{ 'name':user.first_name + user.last_name, 'domain':current_site.domain, 'uid':urlsafe_b64encode(force_bytes(user.pk)), 'token':generate_token.make_token(user)}) email= EmailMessage( email_subject, message2, settings.EMAIL_HOST_USER, [user.email], ) email.send() the activate view from django.core.mail import send_mail ,EmailMessage from django.http import Http404, HttpResponse from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes , force_str from django.utils.http import urlsafe_base64_decode from . tokens import generate_token def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise Http404("Invalid activation link") if generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) messages.success(request, "Your account has been activated!") return redirect(reverse('index')) else: raise ValidationError("Invalid activation link")``` the token.py file from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp)) generate_token = TokenGenerator()``` the confirmation email template {% autoescape off %} Confirmation Link: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} whenever i click on the confirmation link it automatically fails -
Django admin: exclude values from dropdown while keeping existing value
I have a site with conference rankings, where FoR codes are one of the fields. The database includes old FoR codes that are no longer used. I'd like to exclude these codes from the dropdown menu of the change form on the admin site, as it takes some scrolling to reach the current codes (screenshot). I tried excluding the old codes by overriding formfield_for_foreignkey, as seen in the below code snippet. However, if a conference entry with an old code is opened in the admin site, then the FoR code dropdown is cleared (screenshot). Is it possible to exclude the old FoR codes while still preserving the FoR code for old entries? In the example I linked above (1, 2), I want to preserve the 0905 code for this old entry, while only showing the current codes for new entries. class RankInline(admin.TabularInline): model = Rank extra = 1 def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "for": kwargs["queryset"] = ForCode.objects.filter(code__startswith="46") return super(RankInline, self).formfield_for_foreignkey(db_field, request, **kwargs) class CommentInLine(admin.TabularInline): model = Comment extra = 0 class ConferenceAdmin(admin.ModelAdmin): list_display = ("acronym", "title", "url") list_display_links = ("acronym", "title", "url") search_fields = ("acronym", "title", "url") inlines = (RankInline, CommentInLine) -
How to connect from mobile phone to the localhost
I am developing a website on Django, the local version is run by development server (python manage.py runserver) on localhost. I can test my site in a browser, the address is http://127.0.0.1:8000/. But now I need to see how my website is looking on the mobile phone. My laptop OS is Linux Mint, the phone OS is Android, both are connected to the WiFi router. I tried this recipe. I found out my WLAN IP (by the command ifconfig), which happens to be 192.168.0.104. By the recipe, I should enter the address together with port number, which is, apparently, 8000 (according to the development server port, see the paragraph 1), so I should see my local website by the address 192.168.0.104:8000, both from the laptop and the phone browser. However, in both devices I get a following error (translated to English): Can not connect. Firefox cannot establish a connection to the server at 192.168.0.104:8000. The site may be temporarily unavailable or too busy. Please try again in a few moments. If you cannot load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure Firefox has permission to access … -
How to using multi router in django?
Currently, I'm using the Django Framework and have a large data block, a router. In Django Framework, how can I split data into subdatabases and use multiple routers??? I want to split the block of data into several parts. Thanks. -
How can I access The request.data Inside My post_save signal after creating the Model Objects
I want to create Projects with Documents But It took time So i wanna add document after creating the projects But I am giving Documents related details inside my request body # Define the signal receiver function @receiver(post_save, sender=Project) def attach_documents_to_project(sender, instance, created, **kwargs): if created: attachments_data = instance.request.data.get('document') -
Advanced search in django rest framework
I have a database containing lots of posts with a number of fields(title, content, tags). I want to build a search system to look for posts. It seemed really easy first but it turns out it is not. For instance, when I type 'how to' I want my system show posts containing at least one of the word('how' or 'to' or 'how to' is the best scenario) but the problem is when I type 'how to' my system searches for only posts containing 'how to' not 'how' or 'to'. Please help me to build the system. class PostsSearch(APIView): def get(self, request, format=None): search = request.GET.get('search') query = SearchQuery(search) vector = SearchVector('title') + SearchVector('tags__name') posts = Post.objects.prefetch_related('tags').annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.0001).order_by('-rank') serializer = PostsSerializer(posts, many=True) return Response(serializer.data) I tried the code I provided above but it does not work at all -
django email activation feature failing
the view def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): raise Http404("Invalid activation link") if generate_token.check_token(user, token): user.is_active = True user.save() login(request, user) messages.success(request, "Your account has been activated!") return redirect(reverse('index')) else: raise ValidationError("Invalid activation link") the url path('activate/<uidb64>/<token>/',views.activate,name='activate'), the token.py file from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp)) generate_token = TokenGenerator() the confirmation email is indeed being sent but whenever i click on that link i get this error ! -
trying to call Post.objects.filter(category=cats) in my view
im trying to call this method in my view: def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats': cats, 'category-posts': category_posts}) and i have the category defined in my model, but for some reason the error is creating a field in my Model called objects -
Javascript: Input value on fields and show value on popup
I have a registration form. After filling up the forms, the reference number will display in popup. A reminder for the user to use for logging in the system. register.html <div>Reference No.<input type="text" name="refno" value="{{ refno }}" readonly></div> <div>Name<input type="text" name="name"></div> ... <button type="submit" id="getInputValue()" class="btn">Submit</button> this is my script function getInputValue() { let textElement = document.getElementById('refno').value; alert(textElement); views.py if request.method == 'GET': random_chars = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8)) refno = f"{random_chars}" return render(request, 'registration_form.html', {"refno": refno}) if request.method == 'POST': refno = request.POST.get('refno') name = request.POST.get('name') ... Applicant.objects.create(refno=refno, name=name, ...) return redirect(/user_login/) So after the button was clicked, the msg should display the reference number before it proceed to the login form. So I'm a bit confused on how to show the popup first before login. If I write return render(request, 'registration_form.html'), it will just return to the form. With this code I have, it doesn't even show a pop up. Thank you in advance.