Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM .distinct() seems to return duplicate results
I have an Event model that represents an Event happening. I have another EventShow model which represents a date and time that the event is taking place. Each event can have multiple shows, so I have a ForeignKey from EventShow to Event as follows - class Event(models.Model): name = models.CharField(max_length=32) # ... and more class EventShow(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='shows') start_date = models.DateTimeField() I want to get a list of events which have at least one show happening in the future, so in my view I'm calling the ORM like this - events = Event.objects.filter(shows__start_date__gt=now()).prefetch_related('shows').distinct().order_by('shows__start_date') However, I still get the same event showing up multiple times if it has multiple shows. How can I fix this? I looked at the SQL that was being generated by this call - SELECT DISTINCT "core_event"."id", "core_event"."name", "core_eventshow"."start_date" FROM "core_event" INNER JOIN "core_eventshow" ON ("core_event"."id" = "core_eventshow"."event_id") WHERE ("core_eventshow"."start_date" > 2023-08-16 02:48:46.063093) ORDER BY "core_eventshow"."start_date" ASC I'm using SQLite for development. -
Gunicorn & Django: Handle timeout
We run a Django REST API behind Gunicorn (on a Kubernetes Cluster in EKS exposed via AWS ALB). The Gunicorn command: gunicorn config.wsgi --timeout 20 (...) When a request takes over 20 seconds to be processed by Django (due to various reasons), gunicorn will timeout by emitting a SigAbt signal and restart the gunicorn worker. However, this causes an issue in tracking the error in various tools such as Datadog or Sentry which are not able to track the error correctly. Instead, we would like to emit an explicit error (customer error) called TimeoutError. After a thorough investigation, we want to find the best way to raise this TimeoutError at Django Level when the request takes 20 seconds to complete. What would be a recommended solution? -
Django slice then filter queryset
I'm trying to use pgvector to find similar products by name, I've built the embedding on the name, now, when I try to use the method that is stated on the docs for pgvector in order to get the products with a certain distance using ALIAS the query never executed, I tried the other method using group_by which worked the get top 10 for example, but in some cases, top 10 might be too far from being similar to the product, That's why I want to order_by then filter based on the distance only for the 100 in order to ensure that I'm getting similar items, The problem with Django is I can't filter after slicing the queryset, I have a workaround which is: Getting the top 100 ordered by distance and then using their id to filter for the next query which will cause more executing time. (More than 100K records) Is there a better way of doing it, thanks. Slice then filter: result = self.get_queryset().order_by(L2Distance('name_embedding', entry_vector))[:100].alias(distance=L2Distance('name_embedding', entry_vector)).filter(distance__lt=threshold) -
Django Custom User model and Authentication
i want to create a user model for three types of user role Student, Teacher and Principal By inheriting AbstractUser in Django how can i do this.? i have seen many projects but the create a single table for authentication of all students, teachers and principal and link it to another model such as StudentProfile, TeacherProfile and PrincipalProfile using onetoone field i want that all student information such as their username, email, password,... to be saved in a single table similarly i want all info for teacher to be save in single table (Not in student table) same for principal Is it possible? If yes how can i perform their authentication -
I am getting AnonymousUser for request.user after loggin out in Django. How can I fix this?
I have a view called LogoutView that is decorated with the @permission_classes([IsAuthenticated]) decorator. When I call the get() method on this view, I am getting AnonymousUser for request.user after logging out. I have tried the following things to fix this, but none of them have worked: I have checked the request.user.is_authenticated attribute to make sure that the user is authenticated before logging them out. I have returned a 401 Unauthorized response if the user is not authenticated. I have called the logout() method to log the user out. from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from myapp.models import User from django.contrib.auth import authenticate, login, logout import requests from django.shortcuts import get_object_or_404 from django.http import JsonResponse from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, AllowAny from .models import ChatRoom, UserChatRoom from myapp.serializers import ChatRoomSerializer, UserSerializer from django.contrib.sessions.models import Session from django.contrib.auth import login, authenticate from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status import requests from .models import User # Make sure you import your User model correctly from rest_framework.permissions import AllowAny class GoogleLoginView(APIView): permission_classes = [AllowAny] def post(self, request): credential = request.data.get('credential') google_response = requests.get(f'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={credential}') if google_response.status_code == 200: google_data = … -
How can I access templates from an imported Django application?
I want to pip install a Django application and be able to access its templates when adding it to the "INSTALLED_APPS" section in Django project's "settings.py" file. I followed the tutorial here to build a Django app and export it as an installable package, then installed this package into the virtual environment of another Django project. Everything works fine when I add the app's name in INSTALLED_APPS and when I include the urls of the imported app in the project's urls.py file. However, when I run the lightweight server of the Django project and try to access one of the imported app's page, I get a "django.template.exceptions.TemplateDoesNotExist" error. Why would Django allow to access the urls and views of an imported app, but not its templates or templatetags? When running the server and sending a request to it for a specific web page, I was expecting to get this web page (located in the templates of the imported app) to load on my browser. -
django view function is not executing in asgi mode
I am using django development environment to develope an app while trying to execute view function i am getting raise SynchronousOnlyOperation(message) django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. i have configured the django app using asgi mode and running the daphne via command daphne myproject.asgi:application. there is a signup form in my app where user put his name,company_id,email as username and password. i want to store the username,password in user model and the company_id against that user in userprofile model. signup view is failing to execute the django orm queries and i am unable to store the data as expected. ``` async def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.email = user.username user.first_name = request.POST.get('first_name') user.last_name = request.POST.get('last_name') user.save() customer_id = request.POST.get('customer_Id') # Get the customer_id from the form print(customer_id) try: customer = await sync_to_async(Customer.objects.get)(customer_id=customer_id) except Customer.DoesNotExist: return render(request, 'core/signup.html', {'form': form, 'error_message': 'NA'}) userprofile = await sync_to_async(Userprofile.objects.create)(user=user, customer=customer) await sync_to_async(userprofile.save)() await sync_to_async(login)(request, user) # Using sync_to_async for login return redirect('landingpage') else: form = UserCreationForm() return render(request, 'core/signup.html', {'form': form}) ``` -
How can I move data from one model to another with Django/python?
basically i have trhee models where the information of user is already there, but i created a third model called License user, so that i can move the information to that model, how can i do that in an efficient way? Model 1 class License1(models.Model): full_name = models.TextField(blank=False, null=False) email = models.TextField(blank=True, null=True) expire_date = models.DateTimeField(blank=False, null=False) unitcode = models.TextField(blank=True, null=True) wg_version = models.CharField(max_length=10, blank=False, null=False) user_name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(blank=True, null=True) Model 2 class License2(models.Model): full_name = models.TextField(blank=False, null=False) email = models.TextField(blank=True, null=True) expire_date = models.DateTimeField(blank=False, null=False) unitcode = models.TextField(blank=True, null=True) wg_version = models.CharField(max_length=10, blank=False, null=False) user_name = models.CharField(max_length=40, blank=False, null=False) description = models.TextField(blank=True, null=True) User Model class UserLicense(models.Model): """User information model.""" user_name = models.CharField(max_length=40, blank=False, null=False, unique=True) full_name = models.CharField(max_length=80, blank=False, null=False, unique=True) email = models.TextField(blank=False, null=False) I'm usign db.sqlite3, if anyone can explain the process i would be really grateful -
Running R code in Python using rpy2 - Kernel dying
I want to run a R code in my pythons jupyter notebook, My plan is to run the model with both R code and python combined in Django server to publish the ML model(I myself din't make the model so I dont know anything about it). People who made the ML model have used both python varaibles in R code and R varibles in python code. So it would be better if I have all of the programs in a single django server. Due to which I want to run the R code in my python jupyter notebook as the first step. I came accros rpy2 and tried using rpy2 for this. But whenever I try to import something from rpy2 my kernel just dies I just did "pip install rpy2" as suggested to install rpy2. Do I need to set a path like this to for the import to work, But I dont know where to set the path of R to set to since I dont have R folder in my libs even after I installed rpy2 using pip Optional Quetion: Also on the side note is it possible to do what I am thinking on running the … -
Nautobot celery ERROR/MainProcess] Received unregistered task of type
I'm using nautobot with celery and redis for background tasks but it doesn't seem to work. This is my error: [2023-08-15 18:37:13,227: ERROR/MainProcess] Received unregistered task of type 'nautobot_device_onboarding.worker.onboard_device_worker'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: b'[["bcc4229d-f59b-427d-b702-042ff378bfed", {"__nautobot_type__": "nautobot_device_onboarding.utils.credentials.Credentials", "username": "UserAdmin", "password": "Acuat1v3", "secret": "Acuat1v3"}], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (269b) Thw full contents of the message headers: {'lang': 'py', 'task': 'nautobot_device_onboarding.worker.onboard_device_worker', 'id': '3adba9a4-6aee-49ce-bdca-78eafb6c43e1', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '3adba9a4-6aee-49ce-bdca-78eafb6c43e1', 'parent_id': None, 'argsrepr': "(UUID('bcc4229d-f59b-427d-b702-042ff378bfed'), *Credentials argument hidden*)", 'kwargsrepr': '{}', 'origin': 'gen56@f8decca231bf', 'ignore_result': False} The delivery info for this task is: {'exchange': '', 'routing_key': 'default'} Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/celery/worker/consumer/consumer.py", line 591, in on_task_received strategy = strategies[type_] KeyError: 'nautobot_device_onboarding.worker.onboard_device_worker' This file is the worker.py where the task should be defined with the @nautobot_task, the import works but it doesn't define the function. try: from nautobot.core.celery import nautobot_task CELERY_WORKER = True @nautobot_task def onboard_device_worker(task_id, credentials): """Onboard device with Celery worker.""" return onboard_device(task_id=task_id, credentials=credentials) except ImportError: … -
Microsoft Teams integration for Django self-hosted in AWS
I already spent several hours on Microsoft docs making very little progress for what I believe should be a trivial integration, but apparently it's not. I've a Slack integration (via Slack app, built in Django and hosted on AWS) that works this way: our client installs the app and we receive a single token with the token we can pull all slack workspace accounts once that's done, our app sends 2 types of messages using that same token: a message to a public slack channel a 1-to-1 message to an individual I need to replicate this behaviour for Microsoft Teams. I don't want to use Azure, nor node.js, ideally if I could spin up few endpoints to exchange tokens on Django and some logic to send the messages that would be gold. At this point I will take any wisdom from Teams experts ... Thanks -
AttributeError: module 'projeto_cad_chip' has no attribute 'wsgi'
I have a problem when i'll deploy my Django application. The error return is: error return This is my file path: file path I have too my web.config in wwwroot: web.config I'm using windows server 2008 and python 3.7 wsgi.py: wsgi.py I already check my Handler Mappings and FastCGI Settings, but doesn't found anything wrong, by i know. I trying to deploy a Django application in a local Windows Server, but when open in the port 80 returns me this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "c:\users\nmcscript\appdata\local\programs\python\python37\lib\site-packages\wfastcgi.py", line 603, in get_wsgi_handler handler = getattr(handler, name) AttributeError: module 'projeto_cad_chip' has no attribute 'wsgi' StdOut: StdErr: -
Why I ain't able to open a file after downloading "virtualenv env" as I saw it in a Yt tutorial video
I decided to learn the Django tutorial from the Yt video but as I saw that guy gave a command "pip install "virtulenv env" and a new file was opened in his file explorer. Then he again downloaded several other stuffs but I stucked on this step only and he moved ahead of me completing Django download successfully and started coding. A complete set up guidance for Django environment for Windows11, including commands and if raised any issue their solutions. -
How can I add taggit tags to a newly created Django model instance?
I'm unable to add Taggit tags to a newly created Django model instance from within a DRF serializer. When attempting to do use the new instance, the operation fails with list object has no attribute add. class ThingSerializer(serializers.ModelSerializer): def create(self, validated_data): # fails with `list object has no attribute add` thing = Thing.objects.create(**validated_data) custom_tags = validated_data.pop("custom_tags", []) for custom_tag in custom_tags: thing.custom_tags.add( custom_tag.pop("name"), tag_kwargs=custom_tag ) thing.save() def create_with_hack(self, validated_data): # works after fetching the record from DB thing = Thing.objects.create(**validated_data) thing_ = Thing.objects.get(pk=thing.id) custom_tags = validated_data.pop("custom_tags", []) for custom_tag in custom_tags: thing_.custom_tags.add( custom_tag.pop("name"), tag_kwargs=custom_tag ) thing_.save() As noted above, I'm able to work around this by first explicitly fetching record from the database but that is undesirable. Also, the refresh_from_db model method does not solve the problem. Python 3.8 Django 4.2.2 Taggit 4.0.0 -
How to use Django views variables in Google Maps API Javascript on HTML template?
For obvious reasons, I'll be referring to my API KEY by [GOOGLE_API_KEY]. I have the following view : def search_places(request): GOOGLE_API_KEY = os.getenv('google_api_key') search_keywords = request.POST.get('keywords') search_type = request.POST.get('type') top = request.POST.get('top') is_open = request.POST.get('open') w_duration = 1 - (int(request.POST.get('w-duration')) / 100) rating_filter = float(request.POST.get('btnradio-rtg')) price_filter = int(request.POST.get('btnradio-price')) # Converting is_open from string to bool if is_open: is_open = True else: is_open = False df_users = get_all_users_df() dict_users = format_df_users_for_map(df_users) barycenter = compute_barycenter(df_users) return render(request, "index.html", {'google_api_key': GOOGLE_API_KEY, 'dict_users': dict_users, 'barycenter': barycenter } ) Which return in dict_users and in barycenter the following : dict_users = [{'lat': 48.8501531, 'lng': 2.3897723, 'name': 'John'}, {'lat': 48.8490926, 'lng': 2.458714, 'name': 'Jack'}, {'lat': 48.8472106, 'lng': 2.3792469, 'name': 'James'}, {'lat': 48.8490926, 'lng': 2.458714, 'name': 'Jose'}] barycenter = (48.848887225, 2.4216118) In my 'index.html' template, I have : <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="shortcut icon" href="{% static 'css/favicon.ico' %}" type="image/x-icon"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://maps.googleapis.com/maps/api/js?key=[GOOGLE_API_KEY]&libraries=places" defer></script> </head> With a script block : <html lang="en"> <body style="background-color: #f4f6f9;"> <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))}) ({key: "[GOOGLE_API_KEY]", v: "beta"}); // … -
prevent closing of python app using windows CMD X button (by mistake)
I have a running Django app (localy) in "start.bat" file. CALL venv\Scripts\activate.bat manage.py runserver 0.0.0.0:8000 --insecure --noreload Someone on the PC sometimes close the window How can I prevent this? like: warning popup with prompet / hide X button / run in different app than CMD ? I did run it on TK gui but it was messing with my process manager inside the Django. -
Update the text entry widget in a django_jsonform JSONField
I'm using a JSONField from django_transform for a json column in my DB. On the admin page Django renders a nice form that allows users to add entries to the json according to the schema. I want to switch out the text entry input field (a Textinput, I think) for string inputs in the JSONField form with a rich text entry widget. I've tried overwriting the JSONField widget with a rich text widget (I'm using TinyMCE) but that replaces the whole thing and just prints the dumped json string in it. Is it possible to override internal widgets of the JSONField form? -
TypeError at /empinfo/add EmployeeInfoViewset.get_empinfo() got an unexpected keyword argument 'pk'
Here i was used Django Rest Framework to create simple API, But I was facing the Error on try to create new data model.py class EmpPersonalInfo(models.Model): emp_id = models.OneToOneField( 'Employees', models.PROTECT, primary_key=True, db_column='emp_id', verbose_name='Employee ID') dob = models.DateField(verbose_name='Date of Birth') mobile = models.CharField( max_length=10, unique=True, verbose_name='Mobile No.') email = models.CharField(max_length=45, unique=True, verbose_name='Email Address') aadhar = models.CharField(max_length=12, unique=True, verbose_name='Aadhar No.', help_text='Enter Aadhar no. without space') pan = models.CharField(max_length=20, unique=True, verbose_name='PAN No.') add1 = models.CharField(max_length=100, blank=True, null=True, verbose_name='Address line') city = models.CharField(max_length=25, blank=True, null=True, verbose_name='City') state = models.CharField(max_length=25, blank=True, null=True, verbose_name='State') pincode = models.IntegerField( blank=True, null=True, verbose_name='Pincode') class Meta: managed = False db_table = 'emp_personal_info' verbose_name_plural = "Personal Information" def __str__(self): return str(self.emp_id) in my Django app i was used without id field, but in my Mysql Db table i have extra id field Auto increment but not PK, emp_id only used FK and PK here. views.py class EmployeeInfoViewset(viewsets.ViewSet): queryset = EmpPersonalInfo.objects.all() serializer_class = EmpInfoSerializer lookup_field = 'emp_id' @api_view(['GET']) def get_empinfo(request, emp_id=None): with connection.cursor() as cursor: if emp_id is not None: cursor.execute("CALL sp_get_empInfo(%s)", [emp_id]) else: cursor.execute("CALL sp_get_empInfo('')") results = cursor.fetchall() employee_info = [] for result in results: employee_info.append({'emp_id': result[0], 'dob': result[1], 'mobile': result[2], 'email': result[3], 'aadhar': result[4], 'pan': result[5], 'address1': result[6], 'city': … -
Multiple processes spawned when running Django runserver
Sometimes, When I run Django (ver 4.1.6) runserver and monitor the usage memory usage using htop I see that there multiple processes or threads spawned (see the below image). The same thing doesn't happen when running another application's Django even though most of the code is almost identical. Any idea why this is happening? Is there any setting to determine the number of threads? and how do I figure out where the issue is? -
Sending Catalogue WhatsApp Business API
I am trying to ingrate integrate WhatsaApp Business API. I have setup the webhook and can now receive messages through the webhook but when when I send a catalogue, the webhook says Message type is currently not supported.Below is the full response { 'object': 'whatsapp_business_account', 'entry': [ { 'id': '**********************', 'changes': [ { 'value': { 'messaging_product': 'whatsapp', 'metadata': { 'display_phone_number': '***************', 'phone_number_id': ''***************' }, 'contacts': [ { 'profile': { 'name': 'Majesty' }, 'wa_id': 'Majesty' } ], 'messages': [ { 'from': ''***************', 'id': 'wamid.'***************==', 'timestamp': ''***************', 'errors': [ { 'code': ******, 'title': 'Message type unknown', 'message': 'Message type unknown', 'error_data': { 'details': 'Message type is currently not supported.' } } ], 'type': 'unsupported' } ] }, 'field': 'messages' } ] } ] } Is there a way to send catalogue receive it through the webhook -
Django - How to fix multiple pks in url?
I currently have a live search functionality built out mostly working how I want. Functionality works like this: A user searches a word on the search bar. Then the user gets a display of suggested searches that includes text and an image. The user clicks on the text/image from the suggested searches that they want and then the user goes to the template page that includes the primary key in the url. The Problem: When the user is on the template page that includes the primary key and another form submission is made. An additional pk gets added to the URL. Example: http://127.0.0.1:8000/1/2/ This results in Page Not Found 404. How do i fix this? After a user makes another submission I just need the url updated with the new primary key. So this: http://127.0.0.1:8000/1/2/ needs to be this http://127.0.0.1:8000/2/ Any help is gladly appreciated. Thanks! Code Below: urls.py: urlpatterns = [ path('', account_view_home, name='home'), # Below are the urls where the live search is enabled # path ('game_details/', search_results_view, name="game_details"), path ('<pk>/', search_detail_view, name="detail") ] views.py def search_detail_view(request,pk): obj = get_object_or_404(Game_Info, id=pk) user_prices = Shopping_Prices.objects.all() game_leaderboard = User_Info.objects.all() # return render(request, 'detail.html', {'obj':obj}) if request.user.is_authenticated: user_profile = User_Info.objects.filter(user=request.user) context … -
How to resolve the StaleElementReferenceException in selenium
I was trying to create an automation tool using selenium with python which searches google for a particular link and if the link is in the top results it will be marked as indexed and if it is not present it will be marked as not indexed. The first link gets searched with no problem but when I target the search bar to search the next link I'm getting this error. I'm looping over all my links in my database. Below given is the code I used for searching google. parser/parser.py from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from indexer.models import Link from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys def main(): indexed = 0 not_indexed = 0 db_links = Link.objects.all() options = webdriver.FirefoxOptions() options.add_argument("-headless") driver = webdriver.Firefox(options=options) wait = WebDriverWait(driver, timeout=10) visited_google = False for link in db_links: try: if not visited_google: driver.get(f"https://www.google.com") visited_google = True wait.until(EC.element_to_be_clickable((By.XPATH, "//textarea[@id='APjFqb']"))) textarea = driver.find_element(By.XPATH, value="//textarea[@id='APjFqb']") textarea.send_keys(link.link) textarea.send_keys(Keys.ENTER) wait.until(EC.presence_of_element_located(locator=(By.XPATH, "//div[@id='search']"))) search = driver.find_element(By.XPATH, value="//div[@id='search']") anchor = search.find_element(By.XPATH, value=f"//a[@href='{link}']") if anchor: indexed += 1 else: not_indexed += 1 except NoSuchElementException: not_indexed += 1 driver.quit() print(indexed) print(not_indexed) I am using django. My view function … -
How to export in nextjs without regenerate the elements
I have a project with nextjs and I had to get output from it Now, if I want to make a change in the created html pages, I have to go to the chunks folder and edit the js file related to it, but I don't want this to happen because I want to set it with Django variables, and I don't want it to be related in any way. I can also use restful Thankful Also, I tried rendering on the server side and set webpack to false in the nextjs configuration, but no results were obtained. -
Is there a way to know what triggered the beforeunload?
I have a page on my Django app with a form. I would like to alert users if they try to exit the page without submitting their form. I implemented this with the beforeunload method, written below: window.addEventListener('beforeunload', function (e) { e.preventDefault(); e.returnValue = ''; }); However, this also raises an alert when a user submits a page. Is there a way to identify which event is triggering the beforeunload (either submit or exiting, refreshing,etc.)? -
Form Validation Errors Not Displayed in my HTML Template
I developed a login and registration system using Django on a single HTML page with a tabbing system. But, I encountered an error: upon registering, the page just refreshes. To troubleshoot, I debugged by printing errors to the console. It printed that the form is invalid. I intentionally provided invalid details to troubleshoot, like entering a password similar to the username or a password that isn't longer than 8 characters. It printed that in the console, but I want it to show the errors in the HTML template for each field. So, I wrote a login-register view. Everything seems to be okay in the view, but it still isn't showing the errors in the HTML template. Forms class CustomUserCreationForm(UserCreationForm): email = forms.EmailField(label="Email", max_length=255, required=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field_name in self.fields: field = self.fields[field_name] field.widget.attrs.update({'class': 'u-full-width bg-light pb-2', 'placeholder': field.label}) class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Views def login_register_view(request): if request.user.is_authenticated: return redirect('core:home') if request.method == 'POST': action = request.POST.get('action') if action == 'login': # login functionality elif action == 'register': registration_form = CustomUserCreationForm(request.POST) if registration_form.is_valid(): user = User.objects.create_user( username=registration_form.cleaned_data['username'], email=registration_form.cleaned_data['email'], password=registration_form.cleaned_data['password1'] ) user.save() return redirect('core:login_register') login_form = CustomAuthenticationForm() registration_form = CustomUserCreationForm() …