Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django website showing index of/ instead web pages
I hosted my Django app on namecheap shared hosting three months ago, it has been working properly. The recently it stopped and was showing index of/ and files and folders in my public_htm folder. I have tried following the steps I used in hosted the site again but same thing keeps showing. Please what can I do to resolve this issue. -
After replacing ASCII interpretations of accentuated words in Postgresql tables these changes are not shown in my Django
I had names of cities in my DB that were shown like this 'C & oacute;rdoba' instead of Córdoba. This is, of course, because of the encoding. It is a very old table, maybe 20 years old, so probably before unicode UTF-8 was invented :)) So I changed all those escaping characters in the table with things like this: SELECT nombre_localidad, replace(nombre_localidad,'ó','o') FROM localidades as you can see, I removed the tilde so I left it as o instead of 'ó' which works well when I see it on my PGAdministrator viewer for the tables, but when I returned to my Django Application and I pulled the list of cities from my select lists, they are still showing the original thing, C & oacute;rdoba instead of Cordoba. Why is still Django picking the old data. Yes, I clicked on save data changes (F6) in my PgAdministrator -
How do we enable CGO from 0 to 1 in go environment
How do I change cgo from = 0 to 1 to run race in Go lang? How do I change cgo from = 0 to 1 to run race in Go lang? I have tried to run this go code but I get this error at the terminal what could be the problem, Kindly help me find it the solution. I want to run this program -
simple-jwt isn't authenticating my login attempts
I've created a custom user model that allows users to log in with their email and phone number. I tried implementing simple jwt authentication but I keep getting the error: { "detail": "No active account found with the given credentials" } Note that I've attempted logging in using only active accounts and super user accounts created both before and after attempting to login This is in my models.py file class CustomUserManager(BaseUserManager): def create_user(self, name, email, phone_number, password, **other_fields): if not phone_number: raise ValueError('You must provide a phone number') user = self.normalize_email(email) user = self.model(email=email, name=name, phone_number=phone_number, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, name, email, phone_number, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff = True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser = True') return self.create_user(name, email, phone_number, password, **other_fields) class User(AbstractBaseUser, PermissionsMixin): name = models.CharField(max_length=200) email = models.EmailField(unique=True, null=True) phone_number = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=50) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS =['name', 'email'] def __str__(self): return self.name My backends.py file to allow users to log in with their email class EmailOrPhoneNumberBackend(ModelBackend): def authenticate(self, … -
Django:- Real-time Name Display Issue: 'Account Not Found' Despite Existing Account Number
There is a name field in the CustomUser model that I want to display when a user inputs an account number in the Transfer model. What this means is validation: Imagine you want to transfer funds to someone's account. When the sender inputs the receiver's account number, I want the name field from the CustomUser model to be displayed in the name field of the Transfer model in real-time, to accomplish this, I need to query the Account model and send the results to a JsonResponse, But I don't understand why it says Account Not Found even though the account number does exist in the database. Models.py class Account(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) account_number = models.IntegerField() account_balance = models.DecimalField(max_digits=12, decimal_places=6, default=0.0) account_status = models.CharField(max_length=40, choices=ACCOUNT_STATUS) is_accepted_for_Loan = models.BooleanField() class Transfer(models.Model): name = models.CharField(max_length=100) account_number = models.IntegerField() sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sender_user') receiver = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='receiver_user') amount = models.DecimalField(max_digits=12, decimal_places=6, default=0.0) timestamp = models.DateTimeField(auto_now_add=True) Template <input type="number" id="account_number" placeholder="Receiver's Account Number"> <p>Receiver Name: <span id="receiver_name"></span></p> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $('#account_number').on('input', function() { let url = "{% url 'Get_Receiver_Infor' %}; var accountNumber = $(this).val(); if (accountNumber.length > 9) { $.ajax({ url: url, type: 'POST', dataType: 'json', success: function(data) { $('#receiver_name').text(data.name); }, … -
How to cancel a HTMX request?
I've this HTMX form which uploads image to the server. I want to add a cancel button which cancels the HTMX request. HTML side of it: <form id="uploadForm" hx-post="{% url 'pins:upload_image' %}" hx-target="#imageUploadResponse" hx-swap="outerHTML" hx-on::before-request="removeResponseText(), showProgressBarCancelButton()" hx-sync="closest form:drop" enctype="multipart/form-data"> {% csrf_token %} <!- REST OF THE CODE CAN BE IGNORED BECAUSE IRRELEVANT -> <footer class="modal-card-foot"> <button type="submit" class="button is-success" id="imageUpload">Upload</button> <button id="abortUpload" onclick="abortHTMXUpload()" class="button is-hidden">Cancel </button> </footer> </form> JS side of it: <script src="https://unpkg.com/htmx.org@1.9.5"></script> <script> const burgerToggle = document.querySelector(".navbar-burger"); const navbarMenu = document.querySelector(".navbar-menu"); const uploadButton = document.querySelector(".upload"); const modal = document.querySelector(".modal"); const modalForm = document.getElementById("uploadForm"); const progressBar = document.getElementById("progress"); const abortUpload = document.getElementById("abortUpload"); // Rest of the code can be ignored due to irrelevant from this topic htmx.on('#uploadForm', 'htmx:xhr:progress', function(evt) { htmx.find('#progress').setAttribute('value', evt.detail.loaded/evt.detail.total * 100) }); function abortHTMXUpload() { htmx.trigger('#uploadForm','htmx:abort') } </script> I hope the code is self-explanatory. I've gone through the HTMX docs, tried htmx:xhr:abort and similar, nothing seems to work. -
Barcode-django-weasyprint-vuejs Generation timing out
im trying to generate a pdf that will contain one pallet barcode with the items barcodes under that pallet. the issue is happening when the pallet contain big number of items under it the call is taking around 1.7 min and then timing out. My django view :`class XivaAllBarcodeWeasyTemplateView(WeasyTemplateResponseMixin, DetailView): template_name = 'invoices/barcode_all_pallet.html' def get_object(self): try: return PurchasePallet.objects.get(pk=self.kwargs.get("pk")) except PurchasePallet.DoesNotExist: raise Http404("Not found") def get_context_data(self, **kwargs: Any) -> Dict[str, Any]: context = super().get_context_data(**kwargs) size_unit_dict = {'1': 'KG', '2': 'LB'} context['size_unit_dict'] = size_unit_dict return context ` -
filter by intersection of lists
I have a Object-Class that has a ManyToManyRelation to groups. Now I want to get all the objects from that class where at least one group of the user is in the groups attribute of the Class. Something like: MyClass.objects.filter(groups hasIntersectionWith request.user.groups.all()) How can I do that? -
How to retrieve attributes of class passed in the view inside the mixin used by this view
I have an AxiliarClass with attributes and i pass it to the view as an attribute. I have a mixin that i use in the view but i need to get the attributes from the AuxiliarClass inside the mixin, how can in do it. class AuxiliarClass: extra_fields=[{"key": "value"}] class TurmaListCreateView(MytMixin, generics.CreateAPIView): model=MyModel serializer_class = MyModelSerializer extra_fields_class=AuxiliarClass class MytMixin(): extra_fields_class=None def get_queryset(self): print("i need to access the the extra_fields array here and the values inside it") I want to be able to acess the values inside the extra_fields array inside the get_queryset funtion in Mymixin I tried this, but im not able to see the array and i dont know how to get it class MytMixin(): extra_fields_class=None def get_queryset(self): print(self.extra_fields_class.__dict__.keys()) -
nested forloop: list items sorted by outer one
I have a nested forloop like this: {% for category in categories %} {% for task in tasks %} {% if task.category == category.id %} // show category name if it was not already printed {% endif %} {% endfor %} {% endfor %} I have a list of categories and some tasks. Each task has a foreignkey to a category. Now I want to list the tasks sorted by categories. So for each category I want to print a title. How can I achieve this? I don't know if it is possible to use simple variables in django template to distinguish if I already printed the category name? Or what is best practice to do this? -
Best opensource ML model for matching clash of clans bases
I have a small database containing images of clash of clans bases. What I want is to upload a clash of clans base to the system and the system should search into the database images and return some similar bases based on the input image. A very simple matching AI sort of thing. I am using Django and an opensource model called "Deep Image Search" from this repo: https://github.com/TechyNilesh/DeepImageSearch.git its code snippet is following: from pathlib import Path from DeepImageSearch import Load_Data, Search_Setup import os image_list = Load_Data().from_folder(['media/images/']) ST = Search_Setup(image_list=image_list, model_name='vgg19', pretrained=True, image_count=100) ST.run_index() metadata = ST.get_image_metadata_file() The model loads in settings so that I dont have to load it on every request. I use the model as follows: class CheckLink(APIView): permission_classes = (AllowAny,) def post(self, request): fs = FileSystemStorage(location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL) image_file = request.FILES['image'] saved_image = fs.save(image_file.name, image_file) images = settings.ST.get_similar_images(os.getcwd()+fs.url(saved_image), number_of_images=3) files = [] for image in images: image_ = StrategySerializer(Strategy.objects.get(picture__icontains=image)).data["picture"] files.append("localhost:8000/"+image_) # image = StrategySerializer(image).data return Response(files) This returns a link of similar images found in the database folder. The problem is it is not accurate at all. I dont know if I am using it right or not. Following is an image in my database: This … -
404 problems when using persian slugs in django
Hi i am using django and some slug fields . But when I use persian slugs I got 404 errors ! when I use English slugs , I got no error . here is the urls.py : re_path(r'^details/(?P<slug>[\w-]+)/', Details_view , name="Details_page"), I am not sure that I am using right regular expression ! -
'WSGIRequest' object has no attribute 'is_ajax' ,Error while adding ajax to django project
AttributeError at /order 'WSGIRequest' object has no attribute 'is_ajax' error occurred while adding ajax to django project whole project stuck. I am creating a django project and I tried with a guide. I have my code working in Development, but once I ajax added to code code get errors on ajax requests. In development, using this for submission of quizzes works perfectly well, but in development, it doesn't. I tried using pk for the submission and it returns errors and is unable to create an accurate result instance. Below are below order.html cart.js and views. while doing my restaurant Django project is added ajax for passing message to server . but server shows error and no output shown. Messege shown if request.is_ajax(): error cart.js function order(){ var test='Ajax test'; var ur='food/order'; var orderData={}; orderData['test']=test; $.ajax({ url:ur, type:'POST', data:orderData, success:function(data){ console.log("Data sent")} }) } views.py @csrf_exempt def order(request): if request.is_ajax(): test=request.POST.get['test'] print(test) ctx= {'active_link':'order'} return render(request,'food/order.html',ctx) cart.js function order(){ var test='Ajax test'; var ur='food/order'; var orderData={}; orderData['test']=test; $.ajax({ url:ur, type:'POST', data:orderData, success:function(data){ console.log("Data sent")} }) } orders.html {% extends 'food/base.html' %} {% load static %} {% block title %}Order Food here {% endblock %} {% block content %} <div class="container-fluid m-4"> … -
Avoid n+1 queries in django admin nested detail inlines
I currently have a model in my admin with a child inline: class ChildInline(admin.StackedInline): # displays fields that load other associations @admin.register(Statistic) class ParentAdmin(admin.ModelAdmin): inlines = ( ChildInline, ) This results in an n+1 problem, that could easily be solved with prefetch_related if I could get it to work! I've tried to use prefetch_related on both the child and the parent get_queryset method (among other things) with no luck in eliminating the n+1 issue. Anyone have any working code for this? -
What can cause JSON serialization error during django bulk create
I am getting a weird error when performing a bulk_create. MyModel is a ForeignKey on Item model. It's code that was working perfectly fine. Just made some changes that clean up the objects to be bulk-created, the data on the item themselves is what has been there before. items are unsaved instances of Item model. I see in the traceback that the item objects are being dumped to JSON at some point. I just don't understand why it's becoming problematic now when it wasn't before. Here is the traceback: File "/home/user/Documents/software/work/my-project/apps/myapp/importer.py", line 574, in bulk_write_to_db Item.objects.bulk_create(items, batch_size) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/query.py", line 803, in bulk_create returned_columns = self._batched_insert( File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1831, in _batched_insert self._insert( File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1805, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1822, in execute_sql cursor.execute(sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/debug_toolbar/panels/sql/tracking.py", line 246, in execute return self._record(super().execute, sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/debug_toolbar/panels/sql/tracking.py", line 167, in _record return method(sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers( File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/psycopg2/_json.py", line 78, in getquoted s = self.dumps(self.adapted) File "/home/user/Documents/software/work/my-project/venv/lib/python3.10/site-packages/psycopg2/_json.py", line 72, in … -
REMITA API integration with DJANGO for receiving payment from users
Good day all, am currently working on a project with django(python) that involves payments with remita(only). I have gone throuh remita documentations, but ... Users will create account and make payment, Get a response with json response instead of webhook, and save to django model am able to make payment but am not getting response from the transact performed. Please i need help. Thanks in anticipation payment.html <title>make Payment</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/js/bootstrap.bundle.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <style type="text/css"> .button {background-color: #1CA78B; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 4px;} input { max-width: 30%;} </style> <div class="container mt-3"> <h2>Remita Checkout Demo</h2> <p>Try out our Payment Gateway</p> <form onsubmit="makePayment()" id="payment-form"> <div class="form-floating mb-3 mt-3"> First Name: {{request.user.first_name}} </div> <div class="form-floating mb-3 mt-3"> Surname: {{request.user.surname}} </div> <div class="form-floating mb-3 mt-3"> <input type="text" class="form-control" id="js-email" placeholder="Enter Email" name="email"> <label for="email">Email</label> </div> <div class="form-floating mt-3 mb-3"> <input type="text" class="form-control" id="js-narration" placeholder="Enter Narration" name="narration"> <label for="pwd">Narration</label> </div> <div class="form-floating mt-3 mb-3"> <input type="text" class="form-control" id="js-amount" placeholder="Enter Amount" name="amount"> <label for="pwd">Amount</label> </div> <input type="button" onclick="makePayment()" value="Submit" button class="button"/> </form> </div> <script type="text/javascript" src="https://remitademo.net/payment/v1/remita-pay-inline.bundle.js"></script> <script> function … -
Django testing of PDFs - single test passes but same test fails when all tests are run
I have a Django app in which I have been using Reportlab to produce various PDFs. These are all functioning correctly. However, tests are failing in an odd manner. in various tests I'm using pypdf2.PDFReader like this: response = self.client.get(pdf_url) reader = PdfReader(BytesIO(response.content)) text = '' for page in reader.pages: text += page.extract_text() self.assertTrue("Apples" in text) I have one test which fails when I run the whole test suite. self.assertTrue("Apples" in text) AssertionError: False is not true The strange thing is, if I run the single test on it's own, or one single TestCase, everything passes. Also, if I run tests in reverse, I get 2 failures instead of 1. I checked the content being sent to Reportlab and it contains the string "Apples". PDFReader finds all the other content, but not "Apples". -
Add django package dependency to project setting installed app
i write django package name example and it has dependency to other package like rest-frame work. i want to my dependencies be added to installed app of project that using this app, text,ihave seen this question and answers but i want to add the dependencies to setting not make the user manually add them. so is it possible to add them to INSTALLED_APPS ? i have try : from django.apps import AppConfig class MyPackageAppConfig(AppConfig): name = 'example_package' def ready(self): import importlib from django.apps.registry import apps for dependency in self.get_dependencies(): try: importlib.import_module(dependency) except ImportError: pass def get_dependencies(self): # Define your package's dependencies dependencies = [ 'django-foo', 'django-bar', ] return dependencies but it didnt work i also try this: from django.apps import AppConfig class MyPackageAppConfig(AppConfig): name = 'example' def ready(self): from django.conf import settings # Add your package to INSTALLED_APPS settings.INSTALLED_APPS.append("django-foo") and in both case i add them to my inint.py file to run -
Where is my Django project on an Azure Web App
I've successfully deployed a Django app on Azure. For the time being, it's based on SQLLite, but I plan to migrate to MySQL or PostgreSQL. I connected to the Kudu console to locate my project folder. But I cannot see it. I would need that to access manage.py and launch some makemigrations, migrate and createuser for my database server to come. Is that due to the fact I am using a basic (and free) susbscription? Any other hint? Any help is welcome Richard -
How can I take the password from the card and automatically transfer it to a form on another page?
I have a history of generated passwords. Each password has its own frame with ID. Each password has login, website and date of creation in models ( Django Database). Of course when generating a password all fields except date and password are empty. On each password in the password history there is a "Save" button that would give some password a login and a website where it is used. I want that when I go to the form with saving, the password would be automatically written in the form for the corresponding field. In other words, on the history page I want to take the password id, and insert the required password, the id of which matches in the save field on the form page. history.html: <h2 class="text-center mb-4">Passwords History</h2> {% for password in passwords %} <div class="card text-center mb-4"> <div class="card-header">Password ID {{ password.id }}</div> <div class="card-body"> <h5 class="card-title">{{ password.password }}</h5> <h6 class="card-title">{{ password.login }}</h6> <p class="card-text">{{ password.website }}</p> <a href="{% url 'save_pass' password.id %}" class="btn btn-info" >Save to your Passwords</a> </div> <div class="card-footer text-muted">{{ password.date }}</div> </div> {% endfor %} In history.html every card of Password has its own "save" button. This button links to "save_pass" form in … -
ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send'
I have Django application with websockets (channels). When i run this application with gunicorn core.asgi:application i experience this error Traceback (most recent call last): Sep 18 02:20:16 PM File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/workers/sync.py", line 135, in handle Sep 18 02:20:16 PM self.handle_request(listener, req, client, addr) Sep 18 02:20:16 PM File "/opt/render/project/src/.venv/lib/python3.11/site-packages/gunicorn/workers/sync.py", line 178, in handle_request Sep 18 02:20:16 PM respiter = self.wsgi(environ, resp.start_response) Sep 18 02:20:16 PM ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Sep 18 02:20:16 PM TypeError: ProtocolTypeRouter.__call__() missing 1 required positional argument: 'send' I tried looking at all of the stackoverflow or gh issues pages that were in similiar situation but nothing helped (they mostly talk about adding .as_asgi() which i already done). Also it's important to add that when i run my app with python manage.py runserver it does work fine, only on gunicorn it does not. chat/routing.py from django.urls import path from .consumers import ChatConsumer websocket_urlpatterns = [ path(r"ws/chat/<str:streamer_username>/", ChatConsumer.as_asgi()), ] core/asgi.py import os from django.core.asgi import get_asgi_application from channels.security.websocket import AllowedHostsOriginValidator from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault("DJANGO_SETTINGS_MODULE", "streamx.settings") asgi_application = get_asgi_application() from chat import routing # noqa: E402 from chat.middleware import JwtAuthMiddlewareStack # noqa: E402 application = ProtocolTypeRouter( { "http": asgi_application, "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)) ), } ) chat/consumers.py import json from django.contrib.auth import … -
CORS issue when making GET requests to Django server behind Caddy reverse proxy
I'm encountering a CORS (Cross-Origin Resource Sharing) issue when making GET requests to my Django server, which is hosted behind a Caddy reverse proxy. Here's the situation: I have a Django server running, serving an API. The Django server is behind a Caddy reverse proxy. I'm trying to make GET requests to my Django API from a front-end application hosted at a different domain. Using JS And Ajax requests I have already tried the following: Enabled the django-cors-headers package and added it to my INSTALLED_APPS and MIDDLEWARE settings in the correct order. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', # Added this app ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # Placed CorsMiddleware here 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Configured CORS settings in my Django project's settings.py. DEBUG = True ALLOWED_HOSTS = ["*"] USE_X_FORWARDED_HOST = True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_METHODS = [ 'GET', 'POST', ] CORS_ALLOWED_ORIGINS = [ "https://www.example.net", "http://localhost:5000", "http://127.0.0.1:5000", "http://127.0.0.1:5501" ] Despite these configurations, I'm still encountering a CORS-related error when making GET requests to my Django API. Here's the error message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.net/nodeData/?nid=13. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. … -
Django Rest-Framework Token Authentication not working
Hello everyone I am trying to create simple signup, login and logout page. When I enter details of signup in postman it is working I checked on admin page but when logging in it always says Invalid credentials These are all the codes I have written If you want anything more please comment on this I will provide the info ASAP settings.py INSTALLED_APPS = [ .... 'app', 'rest_framework', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', ] serializers.py from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name') extra_kwargs = {'password': {'write_only': True}} class UserLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField(write_only=True) views.py from django.shortcuts import render from rest_framework import generics, permissions, status from rest_framework.response import Response from django.contrib.auth import login, logout from django.contrib.auth.models import User from rest_framework.permissions import AllowAny from .serializers import UserSerializer, UserLoginSerializer from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import ObtainAuthToken class UserRegisterView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [permissions.AllowAny] class UserLoginView(generics.CreateAPIView): serializer_class = UserLoginSerializer permission_classes = [permissions.AllowAny] def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) if serializer.is_valid(): user = serializer.validated_data.get('user') if user: login(request, user) token, created … -
How to add a confirmation popup dialog when saving an object in Django admin?
I have a model with name and email as fields. I want to show a warning popup to the user if there is already an entry with the same name. The user is allowed to create the entry once they acknowledge the warning. I'm looking to implement two specific features in this Django admin interface: Conditional Confirmation Pop-up: I want to display a confirmation pop-up dialog before saving data, but I want it to appear based on a specific condition. This condition is determined by user input. Confirmation for Data Saving: After clicking the 'Save' button, I want to see a confirmation dialog. Data should only be saved if the user confirms the action. I've attempted to use messages to achieve this, but I couldn't find a way to display a warning or error message before saving the data. -
How can I create tables dynamically in Django admin panel
i want to make a table for each event automaticly ,each table contains the participants of this event the result should look like this : models.py: class Student(models.Model): email = models.EmailField(unique=True) phone = models.CharField(max_length=10, blank=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) gender = models.BooleanField(default=1 ) ... class Event(models.Model): name = models.CharField(max_length=50) poster = models.ImageField(upload_to=get_poster_image_path,null=True,blank=True,default="events\posters\default.png") description = models.TextField(null=True,blank=True) event_date = models.DateField(null=True,blank=True) ... registrations = models.BooleanField(default=True) is_active = models.BooleanField(default=True) class EventParticipant(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) participant = models.ForeignKey(student, on_delete=models.CASCADE) join_date = models.DateTimeField(blank=True,null=True,default=timezone.now) ...