Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my dockerised django app doesn't run when adding nginx
I'm trying to dockerise my django app and trying to serve it using nginx. I'm not sure what's wrong but the nginx redirected to the correct URL but the django app doesn't load at all. for example if I open URL http://localhost:8000/cas/login/?service=http://localhost:8000/ which served by gunicorn, the app loaded properly. Yet when going to http://localhost:1337/ I would be redirected to https://localhost/cas/login/?service=http://localhost/ and would show unable to connect. I'm not sure what's wrong. Any pointer would be appreciated. docker-compose.yml version: "4.0" services: db: image: mariadb ports: - "3307:3306" environment: MYSQL_DATABASE: 'atshrd_db' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/dbb:/var/lib/mysql app: build: . volumes: - .:/django ports: - "8000:8000" expose: - "8000" image: app:django container_name: django_container #command: python manage.py runserver 0.0.0.0:8000 command: sh -c "gunicorn --chdir /django/project --reload project.wsgi:application --bind 0.0.0.0:8000" #command: gunicorn --bind 0.0.0.0:8000 --chdir /django/project --reload project.wsgi:application depends_on: - db nginx: build: ./nginx volumes: - ./project/hrd/static:/var/www/static - ./project/hrd/media:/var/www/media ports: - 1337:80 depends_on: - app Dockerfile FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /django RUN pip install --upgrade pip COPY requirements.txt requirements.txt COPY /project ./project RUN pip install cmake RUN pip install -r requirements.txt RUN pip install opencv-python-headless RUN pip install mediapipe tensorflow==2.11.0 tensorflow-io-gcs-filesystem==0.27.0 RUN pip install face-recognition RUN pip install django_datatables_view RUN pip install … -
Data is not adding to djnago table
I deleted sqlite file first then created superuser before this I'd 5 tables and now am able to add manually but through form Data is not reaching & getting stored to respective tables. Please anybody help me I tried, and still trying but unable to solve it myself -
JavaScript onclick event listener not triggering after the first click
I'm working on a web page where I have a button with an onclick event listener to switch between dynamically generated elements. The first click works as expected, but after the first click, the event listener doesn't seem to trigger anymore. Here's the relevant part of my JavaScript: document.addEventListener('DOMContentLoaded', function () { // ... (other initialization code) trdmDisplayed = 1; nextbtn = document.querySelector('.nextbtn'); nextbtn.addEventListener('click', function () { console.log(`trdm when the button is first clicked: ${trdmDisplayed}`); currentlyDisplayed = document.querySelector(`.indexdiv .shading-div:nth-child(${trdmDisplayed})`); currentlyDisplayed.style.display = "none"; trdmDisplayed = (trdmDisplayed % 20) + 1; toDisplay = document.querySelector(`.indexdiv .shading-div:nth-child(${trdmDisplayed})`); toDisplay.style.display = "block"; }); }); and here is my html: <div class="movies-container"> {%for movie in movies %} <div class="shading-div" id="trdm-{{movie.id}}"> /* other elements... */ <div> <button class="nextbtn" ><i class="fas fa-arrow-right"></i></button> </div> </div> {%endfor%} </div> Additional clarification: The dynamically generated elements consist of a fixed set of 20 elements. Upon clicking the button for the first time, the first element successfully transitions from element.style.display = "block"; to "none", and the second element transitions from "none" to "block" as intended and everything is logged onto the console. However, upon clicking the button for the second time, no information is logged to the console, suggesting that the event listener is … -
Updated Approach in Optimized page for Django and React SEO
I am learning React and building a website. But I came across the doubt if my approach is good for SEO and user experience. As of now I have my front-end completely built in React and it communicates to the backend through Django REST APIs. I am using JWTs to handle authentication and have built part of the admin panel. But the main pages the users will visit have also been partially built in React. And the more I read the more I am concerned this is not the correct way if I want this page to be visible or rank higher. The landing page has a search bar and after the selection is made users will be redirected to a page where the results will be shown more in detail. Here they can see a profile of the retailers related to the search selected previously, select them and then proceed to payment, sort of like an e-commerce site. Users do not need to be logged in for these pages but could be. The main concern is if having the entire application as a SPA is good or what should be my new setup? From what I read I see … -
how to form validation unique
Please tell me. I created a form in which you can select more than 1 artist for one order. Somehow it was made so that if the user mistakenly selected the same artist several times when saving, the duplication was removed. But how can you make sure that the user knows about this, that is, that it was something like “you selected the same artist several times”? class JrtnPerson(models.Model): rtn = models.ForeignKey(Drtn, verbose_name='Подразделение Ростехнадзора', on_delete=models.CASCADE) name = models.CharField(max_length=200, verbose_name='Имя и Отчество') surname = models.CharField(max_length=200, verbose_name='Фамилия') tel_mob = PhoneNumberField(verbose_name="Номер телефона мобильный", blank=True, null=True) tel_rab = PhoneNumberField(verbose_name="Номер телефона рабочий", blank=True, null=True) email = models.EmailField(max_length=100, verbose_name="Электронная почта", blank=True, null=True) # def str(self): # return '%s %s' % (self.surname, self.name) # def save(self, *args, **kwargs): # if not self.JrtnPerson.objects.filter(surname=self.surname, name=self.name).exists(): # super(self.surname, self.name).save(*args, **kwargs) class Meta: ordering = ('surname',) verbose_name = 'Сотрудник Ростехнадзора' verbose_name_plural = 'Сотрудники Ростехнадзора' unique_together = ('name', 'surname') def save(self, *args, **kwargs): self.full_clean() super(JrtnPerson, self).save(*args, **kwargs) def __str__(self): return '%s %s' % (self.surname, self.name) class JrtnCurator(models.Model): expertise = models.ForeignKey(Cexpertise, verbose_name='Экспертиза', on_delete=models.CASCADE) curator = models.ForeignKey(JrtnPerson, verbose_name='Сотрудник Ростехнадзора', on_delete=models.CASCADE) def __str__(self): return '%s' % self.curator class Meta: ordering = ('curator',) verbose_name = 'Куратор от Ростехнадзора' verbose_name_plural = 'Кураторы от Ростехнадзора' def save(self, *args, … -
How can I shorten Docker Compose + Django CLI commands?
I have a dockerized Django project built using cookie cutter Django. The only way to run the cli commands without the terminal throwing errors is to type this super long prefix docker-compose -f local.yml run django python manage.py + my command. As you can see that is ridiculously long and I don't want to have to type that or remember it every time I want to run a migration. So what can I do to shorten these commands to a simple python manage.py blahblahblah? Do I need to create an alias to shorten it, which I'd rather not have to because I want others to be able to clone the repo and add to the code without also having to type this long command. Any help is appreciated thanks!!! -
why do I get this error "TypeError at /user/Imnew Field 'id' expected a number but got [<User: Imnew>]."?
I keep getting this error and I don't know how to fix it I changed it a few times but it's still giving me TypeError at /user/Imnew Field 'id' expected a number but got [<User: Imnew>]. I searched for answers online as well but to no avail what should I do? if I need to post more code please let me know Thanks in advance views.py class PostListView(ListView): model = post template_name = 'website/welcome.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 4 class UserPostListView(ListView): model = post template_name = 'user_posts.html' context_object_name = 'posts' paginate_by = 4 def get_queryset(self): user = get_list_or_404(User, username=self.kwargs.get('username')) return post.objects.filter(author=user).order_by('-date_posted') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', PostListView.as_view(), name='home'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('posts/', include('posts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path('profile/',profile, name='profile'), path('', index, name='index'), ] models.py from django.db import models from django.contrib.auth.models import User class post(models.Model): title = models.CharField(max_length=50) body = models.CharField(max_length=1000000) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date_posted=models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.title}" -
after setting up my social accounts in django i cant find http://127.0.0.1:8000/accounts/login i get http://127.0.0.1:8000/accounts/profile/ instead
please am a beginner and i don't know why i cannot redirect my server to /login/ instead i get /profile/ i set up my social accounts with google for authentication and started my development server it seems like it cannot redirect to /login/ instead it changes automatically to /profile/ this is my settings DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rentapp', # allath appa 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', # social accounts 'allauth.socialaccount.providers.google', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'allauth.account.middleware.AccountMiddleware', ] ROOT_URLCONF = 'rent24.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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 = 'rent24.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.2/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # … -
Django DTR and ZKTeco Biometric device Pull Attendance Data Implementation
This is my implementation of the ZKTeco Biometric device with Django. I am new to this and I would like to ask if what else and how to improve this code. I am using the pyzk library. After a very long research in the creation of this, I am planning to 'get all attendance data from all biometric devices first and save only the earliest attendance time per employee', But I am not doing it now because of the deadline, at least I have a working prototype now. Thank you in Advance. from zk import ZK, const from datetime import datetime import subprocess import logging import traceback from dtr.models import AttendanceRecord, DailyAttendance, AllAttendanceRecord def is_device_reachable(ip_address): try: # Use a short timeout for the ping to avoid long delays response = subprocess.run(["ping", "-c", "1", "-W", "1", ip_address], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) return response.returncode == 0 except subprocess.CalledProcessError: return False @login_required(login_url='/admin') def getAllAttendance(request, start_date, end_date): status = 'success' message = '' start_date = datetime.strptime(start_date, '%Y-%m-%d').date() end_date = datetime.strptime(end_date, '%Y-%m-%d').date() devices = BiometricDevice.objects.filter(status=1) attendance_data_list = [] try: for device in devices: if is_device_reachable(device.ip_address): try: zk = ZK(str(device.ip_address), int(device.port)) conn = zk.connect() current_time = datetime.now() conn.set_time(current_time) conn.get_device_name() conn.enable_device() all_attendance_data = conn.get_attendance() attendance_data = [record for … -
Django Cookie Cutter With Docker: django.core.exceptions.ImproperlyConfigured: Set the DATABASE_URL environment variable
I have looked at many other posts with similar issues but no one seems to have used django cookie cutter with docker to build their django project. I followed the instructions from the django cookie cutter website. Everything build's correctly and the server is launched without issue but I am unable to run python manage.py migrate without getting this error. The full error is this: Traceback (most recent call last): File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/environ/environ.py", line 388, in get_value value = self.ENVIRON[var_name] ~~~~~~~~~~~~^^^^^^^^^^ File "<frozen os>", line 679, in __getitem__ KeyError: 'DATABASE_URL' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/kevinbacon/Desktop/dev/uofu_test/api/manage.py", line 31, in <module> execute_from_command_line(sys.argv) File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/core/management/base.py", line 103, in wrapper saved_locale = translation.get_language() ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/utils/translation/__init__.py", line 210, in get_language return _trans.get_language() ^^^^^^^^^^^^^^^^^^^ File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/utils/translation/__init__.py", line 65, in __getattr__ if settings.USE_I18N: ^^^^^^^^^^^^^^^^^ File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/kevinbacon/Desktop/dev/uofu_test/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
When adding a checkbox next to a password input it breaks
So I am making a sign in page and I wanted to add a show password button. But when I put the checkbox next to the button it makes it look awful and uneven. Heres a picture. enter image description here And heres the code: {% extends 'myapp/base.html' %} {% block content %} <h1>Sign up </h1> <input type="text" id="username" placeholder="Username"> <br> <input type="email" id="email" placeholder="Email"> <br> <input type="password" id="password" placeholder="Password"> <input type="checkbox" onclick="show('password')"> <br> <input type="password" id="passwordC" placeholder="Confirm Password"> <br> <input type="submit" value="Submit"> I tried styling it with css but that only made it worse. I also looked through stack overflow but nothing worked. This is using django if that helps. -
where find job for python developer in 2024?
I’m very interested in the question of where an IT specialist can look for work in the USA in 2024 and what services I can generally provide, given that a lot of this is already being replaced by artificial intelligence I tried to find work on popular sites, but to no avail -
Django Limit Queryaset Objects by Foreign Key
Sorry for this question but I'm reasonably new to Django and it's eluding me. I am updating a system (think school) with users, classes (the teachable kind), etc. I have classes from the legacy system I want to bring into the new system, and I need to limit the list by a legacy_user_id. So far, I have this in models.py from account.models import Profile, LegacyUser class OldClassesManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(LegacyUser.legacy_id) class OldInstructables(models.Model): legacy_user_id = models.IntegerField(null=False) name = models.CharField(max_length=100, blank=False) [other stuff] objects = models.Manager() SOMETHING = OldClassesManager() def __str__(self): return self.name And this in views.py class OldClassList(ListView): model = OldInstructables I think my problem is that I don't know what goes where I put SOMETHING. Any help or insight would be much appreciated. -
As in django I am getting the intermediate all auth page after applying this thing also SOCIALACCOUNT_LOGIN_ON_GET = True?
As in django I am getting the intermediate allauth page after applying this variable also SOCIALACCOUNT_LOGIN_ON_GET = True it is not directly rendering me to the google mails...... Provide me the right approach to solve this error. The solution to the my question -
People to practice django?
Does anyone know if there are discord groups or places where I can find people to work on github projects with django or different frameworks to simply practice, it would help me a lot to learn from people who have more knowledge or experience Practice with people to gain experience -
Stream saved video in django
This is my Video Model class Video(models.Model): id = models.IntegerField(unique=True, primary_key=True) saved_location = models.FileField(upload_to="videos/") def __str__(self): return self.id This is my post methods which saves video inside media/videos class Video_api(APIView): permission_classes=[AllowAny] video_serializer = serializers.video_serializer def post(self,request): try: video_data = self.video_serializer(data=request.data) video_data.is_valid(raise_exception=True) data = video_data.validated_data video_instance = Video.objects.create( id = data.get('id'), saved_location = data.get('video') ) video_instance.save() return Response({"success":True}) except Exception as e: return Response({"success":False,"message":str(e)}) Now I want to stream the saved video inside the media/videos on get request. I don't want to download the video. I just want to stream the video when user performs get request. Please give me solution or any documentation related to it. -
RuntimeError: Failed to lock Pipfile.lock while installing django
I am trying to install django on my system using this command pipenv install django before this step, first i installed pipenv itself using pip pip install pipenv now i made my directory and when i try to install django in it, i get this error Installing django... Resolving django... Added django to Pipfile's [packages] ... Installation Succeeded Pipfile.lock not found, creating... Locking [packages] dependencies... Building requirements... Resolving dependencies... Locking Failed! [ ] Locking... No Python at '"E:\python installed\python.exe' Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts\pipenv.exe\__main__.py", line 7, in <module> # when invoked as python -m pip <command> ^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\cli\options.py", line 58, in main return super().main(*args, **kwargs, windows_expand_args=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\decorators.py", line 92, in new_func return ctx.invoke(f, obj, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\vendor\click\core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\pipenv\cli\command.py", line 209, in … -
setting up pgadmin4 on a VPS running ubuntu. Configuring it from nginx
The final instructions for configuring nginx for pgadmin4 read: location / { proxy_pass http://unix:/tmp/pgadmin4.sock; include proxy_params; } but I already had that proxy_pass configured for this: location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; <----HERE } the app_server refers to: upstream app_server { server unix:/home/boards/run/gunicorn.sock fail_timeout=0; } so, the proxy_pass is sort-of already taken. The instructions come from digitalocean -
Bootstrap JS giving an Uncaught TypeError, using modal and dropdown that requires js
I am developing a Blog App for a Project, i have noticed that for some reason i am no longer able to use my Modal toggle and my dropdown on my navbar. I am using the Bootstrap navbar and modal from bootstrap. Day or so ago i had it all working and no problems what so ever all working as excpted. Today i noticed a console error in my live preview that was giving due to a Null error. Console Error Bootstrap alert.js error Bootstrap Script link in html -
How can Django not see a defined url?
I've recently started learning Django for my course project, and my app works perfectly on my local machine. However, when another person clones the project from GitHub and runs it via Docker Compose, he gets an error 404 (trying to access the form/): Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: admin/ api/ trText/ [name='tr_text'] The current path, api/form/, didn’t match any of these. The app/urls.py is: from django.contrib import admin from django.urls import path, include urlpatterns = [ path("admin/", admin.site.urls), path('api/', include('aitranslate.urls')), ] The aitranslate/urls.py is: from django.urls import path from .views import tr_text, translator urlpatterns = [ path('trText/', tr_text, name='tr_text'), path('form/', translator, name='translator'), ] Why does it see trText/ but doesn't see form/? And how can it work on my local machine without this problem? I would appreciate any help. -
I need help, first time learning Python
I am currently learning python and I am starting this small website using django. I typed in the terminal the following code $ django-admin startproject pyshop and I get this error. I am following a tutorial and I type it just as the tutorial shows, but I continue running into this error. At line:1 char:8 + $django-admin startproject pyshop . + ~~~~~~ Unexpected token '-admin' in expression or statement. At line:1 char:15 + $django-admin startproject pyshop . + ~~~~~~~~~~~~ Unexpected token 'startproject' in expression or statement. + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : UnexpectedToken Please any advice or help will be highly appreciated Thank you I've followed the tutorial, I tried to write the code several times, I searched online. -
Django custom domains feature
I'm currently working on a Django project that allows our users to create their own websites. One of the main features I've been working with is setting up custom domain capabilities. Here's what I did: I initially set the ALLOW_HOST setting to "*", then I've since devised a middleware to manage domain routing: First, it checks whether the host (using request.get_host()) corresponds to www.domain.com. If so, the middleware directs the request to the homepage application using the request.urlconf attribute. Next stop is checking if the host matches dash.domain.com. If it does, voila! The request gets routed to the dash app. And here's where it gets interesting. If neither of the above conditions is met, the middleware dives into the database to see if the host matches any of the registered site domains. If it finds a match, it redirects to the sites app with all the site-specific info. If not, it gracefully returns a 404 error. I've been thinking about the safety aspects of this configuration since ALLOW_HOST setting is "*", and I'd like your opinion. Do you think this approach is robust enough? -
Could not store data to custom user model from django shell
This is custom user model class class User(AbstractUser, BaseUserManager): username=None name = models.CharField(max_length=255) created_by =models.ForeignKey('self',on_delete=models.CASCADE,null=True,blank=True) email = models.EmailField(unique=True) password = models.CharField(max_length=128) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_verified = models.BooleanField(default=False) is_superuser= models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField() USERNAME_FIELD = 'email' REQUIRED_FIELDS=['password'] objects = ContentManager() def __str__(self): return self.email This is my manager.py for User model class ContentManager(BaseUserManager): use_in_migrations=True def create_user(self, email,password, **extra_fields): if not email: raise ValueError("Email must be set") email = self.normalize_email(email) user = self.model(email=email,**extra_fields) user.set_password(password) user.save(using=self.db) return user def create_super_user (self,email, password,name, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_admin',True) extra_fields.setdefault('is_superuser',True) return self.create_user(email,password,**extra_fields) The problem is when I wanted to create the user from django shell by following method. python manage.py shell from api.models import Users user = User.objects.create_user(name="roshan",email="example@example.com",password="password") Even if put some data in name field, it is showing django.db.utils.IntegrityError: (1048, "Column 'name' cannot be null") error. I couldn't figure out where I went wrong. Please help. -
Django 5.0 login failing using admin as well as django.contrib.authLoginView and authenticate()
I have a problem in Django regarding logging my users in. I have created some users using the python manage.py makesuperuser. However, when trying to log one of them in it fails. This holds true for logging in to the admin page as well as my own login page: # I am using the django.contrib.auth.LoginView here, passing my own template urlpatterns = [ path("auth/login/", LoginView.as_view(template_name="login.html"), name="login"), ] With the following html: <h2>Login</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Login"> </form> I have also tried using the django.contrib.auth.authenticate method, but it returns None when passing seemingly valid parameters for debugging purposes. def dashboard(request): print(type(authenticate(request, username = "user3", password = "user3_password"))) return render(request, "dashboard.html") # Prints nonetype If it is of any help, the code is inside Onedrive and when hosted on another computer it runs fine. I am using a python virtual environment with Django 5.0 installed. Any help would be appreciated. -
How to Set Event Reminders in Google Calendar for Multiple Users using Python API without Explicit Consent?
I'm developing an application where I need to set event reminders in multiple users' Google Calendars without explicitly asking for their permission. When exploring the Google Calendar API in Python, I encountered limitations due to privacy and security restrictions. I'm seeking insights into whether it's possible to set reminders for users' events without direct access or explicit permission for each calendar. Any guidance, code examples, or alternative methods using the Google Calendar API or other approaches that might help achieve this functionality would be highly appreciated.