Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - concatenate all the groups for each post
I have 2 model in my Django app: models.py: class Post(models.Model): id = models.CharField(verbose_name="Post ID", max_length=1200, primary_key=True) post_name = models.CharField( verbose_name="Post Name", max_length=1000, blank=True, null=True, ) post_description = models.TextField( verbose_name="Post Description", max_length=600, null=True, blank=True, ) platform = models.CharField( verbose_name="Platform", max_length=25, null=True, blank=True, ) type_dropdown = ( ("Carousel ads", "Carousel ads"), ("Image ads", "Image ads"), ("Video ads", "Video ads"), ("Lead ads", "Lead ads"), ("Follower ads", "Follower ads"), ) type = models.CharField( verbose_name="Type", max_length=15, blank=True, null=True, choices=type_dropdown, default="Type 1", ) link = models.URLField( verbose_name="Link", max_length=4000, blank=True, null=True, ) created_at = models.DateTimeField(default=now, null=True, blank=True) insert_date = models.DateTimeField(null=True, blank=True) user_last_update = models.ForeignKey( User, on_delete=models.PROTECT, null=True, blank=True, ) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return f"{self.post_name}" class Group(models.Model): group_name = models.CharField( verbose_name="Group Name", max_length=150, blank=True, null=True, ) post = models.ManyToManyField( Post, related_name="combo_post", ) created_at = models.DateTimeField(default=now, null=True, blank=True) insert_date = models.DateTimeField(null=True, blank=True) user_last_update = models.ForeignKey( User, related_name="combo_user", on_delete=models.PROTECT, null=True, blank=True, ) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return f"{self.group_name}" I use in CBV (Django Class-Based Views) i i want to get a query set of all the posts with another column that concatenate all the groups for each post. How can i do that? I tried this one but didn't work: from django_mysql.models … -
How to Upload, Edit, and Merge Word Documents in a Django Project?
In my Django project, I need to upload different Word documents for various tests, edit these documents to include the test data, and eventually combine them into a single document. How can I achieve this? I want to know if it's possible to achieve this in Django without creating a form. If yes, then how? I have already implemented this by creating a form, but now the process of handling 100 tests feels redundant and time-consuming -
request data not able to access with this code in wrapper function how can i python3 django decorator
not able to access request data in deorator how can i do this ? in my wrapper function def my_decorator(view_func): def wrapper(request, *args, **kwargs): print('-start-') print(request.data) print(args) print(kwargs) print('-now-') response = view_func(request, *args, **kwargs) return response return wrapper class HandymanCompleteProfileIos(APIView): @my_decorator def post(self, request, format = None): return JsonResponse({"A":"a"}) -
django cannot show user count when i called it
i'm new to django and i'm stuck here, when i want to show my total user excluding is_staff and is_superuser it cannot show what i wanted. Here's the code : Views.py def dashboard_view(request): # Menghitung jumlah user yang bukan staff dan bukan superuser user_count = CustomUser.objects.filter(is_staff=False, is_superuser=False).count() return render(request, 'dashboardowner/index.html', {'user_count': user_count}) Urls.py : path('dashboardowner/index/', views.dashboard_view, name='dashboard_view'), index.html (this file is inside dashboardowner folder, so here is the structure (mysalon->templates->dashboardowner->index.html)) <!-- Sale & Revenue Start --> <div class="container-fluid pt-4 px-4"> <div class="row g-4"> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-line fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Total Bookingan</p> <h6 class="mb-0">$1234</h6> </div> </div> </div> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-bar fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Estimasi Pendapatan</p> <h6 class="mb-0">$1234</h6> </div> </div> </div> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-area fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Jumlah Staff</p> <h6 class="mb-0">$1234</h6> </div> </div> </div> <div class="col-sm-6 col-xl-3"> <div class="bg-secondary rounded d-flex align-items-center justify-content-between p-4"> <i class="fa fa-chart-pie fa-3x text-primary"></i> <div class="ms-3"> <p class="mb-2">Jumlah User</p> <h6 class="mb-0">{{ user_count }}</h6> </div> </div> </div> </div> </div> <!-- Sale & Revenue End --> What i expected is the number of … -
Django channels error:- Could not connect to ws://192.168.1.21:8000/ws/sc/,
IMO I think it is unable to find the route /ws/sc route but I dont understand why as I have linked it properly. The error is give when I try to establish a connection using postman Following is the postman error:- Could not connect to ws://192.168.1.21:8000/ws/sc/ 12:30:20 Error: Unexpected server response: 404 Handshake Details Request URL: http://192.168.1.21:8000/ws/sc/ Request Method: GET Status Code: 404 Not Found Consumer class :- from channels.consumer import AsyncConsumer, SyncConsumer class MySyncConsumer(SyncConsumer): def websocket_connect(self, event): print("Websocket Connected", event) self.send({ 'type': 'websocket.accept' }) def websocket_receive(self, event): print("Message recieved", event) def websocket_disconnect(self, event): print("Websocket Disconnected", event) Routing class from django.urls import path, re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/sc/$', consumers.MySyncConsumer.as_asgi()), ] Asgi class import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import core.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'gs3.settings') application = ProtocolTypeRouter( { "httpa": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( core.routing.websocket_urlpatterns ) ), } ) Settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-*3c_890(%*-no1e64qvxtq^1su(8-pyb5t46p-kzpqu=1173%i' # SECURITY WARNING: don't run with debug … -
How to Serve media files on render.com for Django app deployed?
`Below is following render.com documentation for serving static and media when deploying Django webapp. Everything works, except when you upload a profile picture. Below, setting.py, build.sh and render.yaml code. It was deployed via blueprint instance with PostgreSQL. Also useing PGAdmin 4 GUI If you spot an issue, great. If not I have spent A week on my Linux/Ubuntu machine on my wondows laptop trying to get Nginx to server the media files. https://djangocareershifterswebsite.onrender.com (with sqlite 3 db) https://careershiftforum.onrender.com (with postgresql db) setting.py import os import dj_database_url from django.core.management.utils import get_random_secret_key # Generate or retrieve SECRET_KEY from environment variables SECRET_KEY = os.getenv('DJANGO_SECRET_KEY', default=get_random_secret_key()) # Define BASE_DIR to point to the root directory of your Django project BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = os.getenv("DEBUG", "False").lower() == "true" ALLOWED_HOSTS = ['careershiftforum.onrender.com', 'localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'rest_framework', 'corsheaders', ] AUTH_USER_MODEL = 'base.User' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'careershiftforum.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'careershiftforum.wsgi.application' # Use dj_database_url to parse the DATABASE_URL environment variable DATABASE_URL = os.getenv('DATABASE_URL') DATABASES = … -
FilteredRelation with OuterRef not working after updating to Django 5
After updating to Django 5, I have the same problem described in this post: How to use FilteredRelation with OuterRef? My queryset looks as follows: ModelA.objects.annotate( model_b_objects_count=SubqueryCount( ModelB.objects.filter( model_a_id=OuterRef('id') ).annotate( outer_user_id=OuterRef('user_id'), # user_id within ModelA model_c_relation=FilteredRelation('model_c_objects', condition=Q(model_c_objects__user_id=F('outer_user_id') ) ) ) While using Django 4.1, it was working fine, since trying to update, I get the error ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Anyone know how to fix this or is it sth that Django has to fix? I tried the solution provided in the mentioned post, but still got the same error. -
Bonjour la team mon projet en django ne se lance pas voici le messages d'erreur que j'ai au niveau de mon terminal
(GestFibOpt) C:\Users\JOHAN MOLLO\Desktop\GestFibOpt>python manage.py runserver C:\Users\JOHAN MOLLO\AppData\Local\Programs\Python\Python311\python.exe: can't open file 'C:\Users\JOHAN MOLLO\Desktop\GestFibOpt\manage.py': [Errno 2] No such file or directory j'ai essayé de lancer le projet avec la commande python manage.py runserver -
DJANGO ForeingKey selection from the reference table depending on the user
Section -> Complexes -> Line -> Equipment -> Report I need to make sure that when adding a Report, only the equipment Section to which the user belongs and status=true is in the Equipment list. I just started learning Django. Tell me what you need to look at to solve this problem. `class Section(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) def __str__(self): return self.name class Complexes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) section = models.ForeignKey(Section, on_delete=models.SET_NULL, ...) def __str__(self): return self.section.__str__()+" "+self.name class Line(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) complexes = models.ForeignKey(Complexes, on_delete=models.SET_NULL, ...) def __str__(self): return self.complexes.__str__()+" "+self.name class Equipment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) name = models.CharField(max_length=30, blank=True, ...) line = models.ForeignKey(Line, on_delete=models.SET_NULL, ...) status = models.BooleanField(default=True, ...) ... def __str__(self): return self.name +" "+ self.explanation +" "+ self.line.__str__() class Report(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, ...) equipment = models.ForeignKey(Equipment, on_delete=models.DO_NOTHING, ...) ...` -
Django stuck after running Docker command as subprocess
When I run this command: manim_command = f'sudo docker run --rm -v {base_dir}/manim/python_code_files:/mnt/code -v {base_dir}/media:/mnt/output manim-image manim -ql /mnt/code/user_code.py -o /mnt/output/{class_name}' using subprocess.run or subprocess.Popen or os.system, It successfully runs(create an image or video file), but it blocks the terminal and prevents the further rendering of the template. If the file is already present, it will successfully display it. But if the file is not present, it will render but not show. I have tried running the docker container in detached mode, but that just renders the template before creating the file. obviously we have to wait till the process is over: while True: if check_file_exists(class_name): break time.sleep(2) print('File created') so, it waits till the file is created, but when I add this block, it waits for the the file to be created, prints 'File created' and then gets stuck just before rendering the template. why doesn't it render? try: # Run the function run_manim_command(class_name) print('function completed') except Exception as e: result_message = f"Error executing shell command: {e}" #after POST request context = {'previous_code': previous_code, 'MEDIA_URL': settings.MEDIA_URL, 'class_name':class_name, 'placeholder': False, } return render(request, 'run.html',context) It even prints 'function completed' I have tried: using thread to run as an asynchronous process … -
Exception occurred in file 'chrome.py', line 64: 'NoneType' object has no attribute 'split'
I am using pyhtml2pdf for converting HTML to PDF which has a requirement of Chrome headless. When the server is run as python manage.py runserver there is no issue. But when the django is run as a service it throws and error regarding split with chrome.py : Exception occurred in file ‘/var/www/myProject/env/lib/python3.11/site-packages/webdriver_manager/drivers/chrome.py’, line 64: ‘NoneType’ object has no attribute ‘split’. -
Sending Checkbox Status via hx-vals to Django
How can I correctly send the status of a checkbox to Django using hx-vals? I attempted the following method: hx-vals='{ "solved": "document.querySelector("input[name="solved"]").checked", "comment": "document.querySelector("input[name="comment"]").checked", "no_solution": "document.querySelector("input[name="no_solution"]").checked", }' In the Django views, I expected to retrieve the values like this: filter_solved = request.GET.get("solved") == 'true' However, I couldn't make this work. How can I fix this? Ty!!! -
Problem with Django class-based LogoutView
Logout Page Not Working ***Here is my user urls.py code *** from django.urls import path from users_app import views from django.contrib.auth import views as auth_views urlpatterns = [ path('register/', views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='logout.html'), name='logout'), ] -
Hello! I have a problem. When deleting a comment, the error Post matching query does not exist appears
I have a problem. When deleting a comment, the error Post matching query does not exist appears. And I do not know what to do with it. Thank you in advance! Error: Does Not Exist at /news/post/6 Post matching query does not exist. Note! I use the django framework Here is the code: views.py: from django.shortcuts import render from django.urls import reverse_lazy from .forms import PostForm, CommentForm from .models import Post, Comment from django.views import View from django.views.generic.edit import UpdateView, DeleteView class PostListView(View): def get(self, request, *args, **kwargs): posts = Post.objects.all().order_by('-created_on') form = PostForm() context = { 'post_list': posts, 'form': form, } return render(request, 'news/post_list.html', context) def post(self, request, *args, **kwargs): posts = Post.objects.all().order_by('-created_on') form = PostForm(request.POST) if form.is_valid(): new_post = form.save(commit=False) new_post.author = request.user new_post.save() context = { 'post_list': posts, 'form': form, } return render(request, 'news/post_list.html', context) class PostDetailView(View): def get(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) form = CommentForm() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'post': post, 'form': form, 'comments': comments, } return render(request, 'news/details_view.html', context) def post(self, request, pk, *args, **kwargs): post = Post.objects.get(pk=pk) form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.author = request.user new_comment.post = post new_comment.save() comments = Comment.objects.filter(post=post).order_by('-created_on') context = { 'post': … -
How i can show gis_models map in django templates?
models.py: ADDRESS_WIDGETS = { # ... 'point': gis_forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}), } srid = 4326 class Address(UUIDMixin, models.Model): city = models.ForeignKey(...) street = models.CharField(...) house_number = models.CharField(...) entrance_number = models.SmallIntegerField(...) floor = models.SmallIntegerField(...) flat_number = models.SmallIntegerField(...) point = gismodels.PointField( _('address geopoint'), srid=srid, ) tours = models.ManyToManyField(...) class Meta: # db_table, verbose_name, unique_together forms.py: class SettingsAddressForm(forms.ModelForm): def __init__(self, request: HttpRequest = None, *args, **kwargs) -> None: super(SettingsAddressForm, self).__init__(*args, **kwargs) if request and isinstance(request, HttpRequest): user = Account.objects.get(account=request.user.id) self.fields['city'].initial = user.agency.address.city self.fields['street'].initial = user.agency.address.street self.fields['house_number'].initial = user.agency.address.house_number self.fields['entrance_number'].initial = user.agency.address.entrance_number self.fields['floor'].initial = user.agency.address.floor self.fields['flat_number'].initial = user.agency.address.flat_number self.fields['point'].initial = user.agency.address.point class Meta: model = Address fields = ['city', 'street', 'house_number', 'entrance_number', 'floor', 'flat_number', 'point'] widgets = ADDRESS_WIDGETS views.py: def settings(request: HttpRequest) -> HttpResponse: request_user = request.user user = Account.objects.get(account=request_user.id) address_form = SettingsAddressForm(request) # ... return render( request, 'pages/settings.html', { 'request_user': request_user, 'user': user, 'address_form': address_form, 'style_files': [ 'css/header.css', 'css/body.css', 'css/tours.css', 'css/profile.css', ], }, ) pages/settings.html: {% extends 'base.html' %} {% load static %} {% block content %} <section class="home"> <div class="container"> {% if user.account.is_active %} <div class="left"> <!-- ... --> {% if user.agency %} <div class="agency_info"> <h3>Турагенство</h3> <form method="post"> {% csrf_token %} {{ agency_form.as_p }} <!-- ↓↓↓ here ↓↓↓ --> {{ address_form.as_p }} … -
'django' is not recognized as an internal or external command
I had installed django at C:\Users\05554F744 Now, to create a Django project, I'm doing C:\Users\05554F744\Box\Nupur\Learning\Python\Django>django -admin startproject djangoprojects I get the message "'django' is not recognized as an internal or external command,operable program or batch file." What should I do to fix this? I want my "djangoprojects" folder inside C:\Users\05554F744\Box\Nupur\Learning\Python\Django -
Sending GET request from front-end app to the back-end app does not contain cookies ( front nextJS + back Django )
So basically from what I read across the internet, Django cookies are stored in the sessions I guess, and when we try to access them what so ever, there will be sessionid in the cookies and it makes the cookies (like accessing the user stored in the request and stuff) achievable. My problem is that I have a front-end, and in that I try to get the data of a 'Post'. The problem is that in my GET request, from what I invested, there are no cookies sent to the back-end, and because of that, the sessionid is gone and my user that is stored (or better to say must be stored) in the request is gone (AnonymousUser it is). The fun fact is there is another view in my Django app for logout, which works prefect and the request does have the sessionid and access to the user in the request. My question is, is this a problem with my views ?! Is it general ?! What is causing this to happen ?! I really need this to be fixed, cause all my project is actually getting collapsed because of this problem I have with fetching data. How do … -
How to get the body from the POST request correctly in the Django Rest Framework
All I want is to get the body from my request, but I don't understand how to do it, I tried request.data but it returns a string, after I tried using json.loads(request.data), but it just refused to work. I just want to parse the nested json, why is it so difficult in Django. My code class TestCheckView(views.APIView): def post(self, request, pk): result = Result() test_id = request.data.get("id") data = dict(request.data) for question in data["questions"]: print(type(question)) for answer in question["answers"]: result.total += 1 if Answer.objects.get(id=answer["id"],question_id=question["id"]): result.score += 1 result.test = Test.objects.get(id=test_id) result.save() what i want get "id":1, "title":"Тест по теме тестов", "questions":[ { "id":1, "title":"Вопрос 1", "answers":[ { "id":1, "title":"Ответ 1", "is_right":true }, { "id":2, "title":"Ответ 2" } ] }, { "id":2, "title":"Вопрос 2", "answers":[ { "id":3, "title":"Ответ 1", "is_right":true } ] } ] } -
Vue + Vuetify with Dhango, not all styles are loading
I am working on a SPA application (my first work with frontend frameworks) that needs to show in a spreadsheet the patients and their studies, I have connected vue and vuetify to my project but after build/dev command not all styles are loading. package.json file I have configured that generated vue files are going to my statics folder vue config static folder settings py Аfter that I load them in my html file index html But on an actual page it seems like some styles are missing, like there is not vuetify icons and fonts result result console How do i fix this issue @vue/cli 5.0.8 vuetify - 3.6.7 Tried to reinstall vue, tried to reconfigure static and etc. -
Again on Django template inheritance
The difficulty I have is precisely described in Django Accessing Parent Data in templates from child data but the answer given there, accepted by the OP, is given in the “recipe” spirit, as are an incredible number of others I found, concerning the same issue. Even the django official documentation, having to document an enormously vast field, suffers from this disease. So, since I would like not the fish but the fishing rod, please let me restate the question in my terms: I have a father template and children templates, the latter all filling one block defined in the father template, one at a time. The father template is shown by calling a father-view in father.py, with a father-context, and the view-template relation for the father is given by a line in some urls.py file. This fills the upper part of the browser screen with some type of “summary data”. When this is done, it is time to fill up the lower part, with different types of detail information, one at a time of course. I do this with different children views, using in the father-template idioms like {% url ‘djangoapp:details1’ param1_a %} or {% url ‘djangoapp:details2’ param2_a param2_b param2_c … -
Django -> ModuleNotFoundError: No module named 'google'
I have installed google-cloud-translate both on my localhost and on my production environment. pip install google-cloud-translate When I import it in my Django app with from google.cloud import translate_v2 as translate then It works fine on my localhost but on my production environment I get this error: ModuleNotFoundError: No module named 'google' Although the package is installed in the correct folder: /home/mysuer/.local/lib/python3.9/site-packages I also created a small test script: try: #import google from google.cloud import translate_v2 as translate print("Module 'google' found!") except ImportError as e: print("Module 'google' not found:", e) When I execute this script then the output is: Module 'google' found! So with the test script the package was found and with my Django app the package was not found!? Anybody who can help me on this? I tried debugging, reinstalling the package, checking my Python version, creating a test script, ... but I cannot find a solution... -
Django: Two indepent searchable dropdown with select2 and ajax does not work
I would like to have two searchable dropdowns which are linked to two different modals (Dog & Service). The first dropdown for the products (services modal) works fine (expect, that i dont have a preview), but the second dropdown which should be linked the to the dog modal doesn't work as expected. The searchfunction only shows results which are in the other modal (service). However if I select one of the results, the actual selection in the dropdown equals the value from the correct dog modal. I already tried to find the same problem online, but could not. .html <!-- Searchbox_dog linked to Dog Modal --> <form method='post' action='' class="mb-3"></form> <label for="dog" class="form-label">Dog:</label> <select class="form-select select2" name="searchbox_dog" id="searchbox_dog"> {% for dog in dogs %} <option value='{{dog.id}}'>{{ dog.dog_name }}</option> {% endfor %} </select> </form> <!-- Searchbox_service linked to Service Modal --> <form method='post' action='' class="mb-3"> <label class="mb-1">Search service:</label> <select class="form-select select2" name="searchbox_service" id="searchbox_service"> {% for service in services %} <option value='{{service.id}}'>{{ service.name }}</option> {% endfor %} </select> </form> javascript let csrftoken = '{{ csrf_token }}' $('#searchbox_dog').select2({ dealy: 250, placeholder: 'Search dog', minimumInputLength: 1, allowClear: true, templateResult: template_dog_searchbox, ajax:{ type: "POST", headers:{'X-CSRFToken':csrftoken}, url: "{% url 'get_dogs' %}", data: function (params) { var … -
I have created a CustomUser model and it shows up in base app and not under Authorization and Authentication
I have created a custom user model which is inside the base app and the custom user model shows up in base app in the admin site instead of authorization and authentication. Why is it coming under it? Here is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import CustomManager # Create your models here. class CustomUser(AbstractBaseUser): name = models.CharField(max_length=50,default='Yet to be updated...') email = models.EmailField('email_address', unique=True) USN = models.CharField(max_length=10, default='Yet to be updated...') is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) # updated = models.DateTimeField(auto_now=True) # created = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomManager() def has_perm(self, perm, obj=None): return self.is_superuser def has_module_perms(self, app_label): return self.is_superuser def __str__(self): return self.email Here is my managers.py from django.contrib.auth.base_user import BaseUserManager class CustomManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError("Email is must") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) return self.create_user(email, password, **extra_fields) Here is my admin.py from django.contrib import admin from .models import CustomUser # Register your models here. admin.site.register(CustomUser) why is the custom user not under Authorization and Authentication and how can I add … -
Django multi-selection in the form with CBV django
I have 2 models: Group and Post. Group is ManyToManyField to Post models.py class Group(models.Model): group_name = models.CharField( verbose_name="Group Name", max_length=4000, blank=False, ) class Post(models.Model): id = models.CharField(verbose_name="Post ID", max_length=1200, primary_key=True) group = models.ManyToManyField( Group, verbose_name="Group", related_name="post_group", ) How can i select 2 groups for one post in the form? Thanks a lot I tried somethings but without any success -
how to prevent sql injection in snowflake filter function
Im using input from the user to query snowflake within DRF view, how to prevent in the below code sql injection possibility? entity_id = kwargs['pk'] table = session.table("my_table").filter(col(ID_COL)==entity_id )