Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Сelery starting task every milisecond
Celery task schedule worked fine considerate amount of time. Now one of tasks launches and finishes successfully every couple of milliseconds. Did some search at git/stack and found that some older celery versions suffered from this, but now its fixed. Some users experienced this problem due to celery and django TZ difference, but this is not the case. celery version - 5.2.7 broker - redis flower screen -
The transition effect in in sign in and sign up page not working in django
My friend created a Sign in and sign up page which changes dynamically [https://github.com/codecxAb/anytimeFitness] I have done the django integration but it doesn't seem to change dynamically and instead giving and error "GET /signin/%7B%%20static%20'js/signin.js'%7D HTTP/1.1" 404 2792 My django project [https://github.com/RynoCODE/Gym-Website] -
Django graphene performance issue not related to the db but to the rendering
In Sentry APM I am able to see that most of the time spent was in the view.render I am assuming that this part is where the result from the db are being formatted but can't understand why it is taking a lot of time: -
Like count not showing in html and want to know if my models are set up properly
This is my models.py and index.html and views.py I tried the above and I am expecting to get total like count in my index page but i am only getting 0 likes why is that happening. And how do I fix it. `from django.contrib.auth.models import AbstractUser from django.db import models from datetime import datetime from django.contrib.auth import get_user_model class CustomUser(AbstractUser): profile_picture = models.ImageField( upload_to="profile_pics/", blank=True, null=True ) # Add any other custom fields as needed def __str__(self): return self.username class Post(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(max_length=1000) content = models.TextField() created_at = models.DateTimeField(default=datetime.now, null=True, blank=True) likes = models.ManyToManyField( get_user_model(), related_name="liked_posts", blank=True ) class Like(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return f"{self.user.username} likes {self.post.title}"` and this is my index.html `{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <h2>Welcome to the Home Page!</h2> {% for post in posts %} <!-- Display post details as needed --> <div> <h3>{{ post.title }}</h3> <small>{{post.created_at}}</small> <p>{{ post.content }}</p> <form id="likeForm{{ post.id }}" data-post-id="{{ post.id }}" method="post"> {% csrf_token %} <input type="submit" value="Like post"> <span id="likeCount{{ post.id }}">{{ post.likes.count }}</span> Likes </form> </div> {% endfor %} <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script> $(document).ready(function () { $('form[id^="likeForm"]').submit(function (event) { … -
Django Auth Ldap on Windows
Is there any way to make django ldap authentication I am trying to pip install django-auth-ldap but keep getting Could not build wheels for python-ldap, which is required to install pyproject.toml-based projects then I searched and find this project but those settings configuration wont work. Reading docs. but when I try to install ldap but it isn't working... Any help would be appreciated, thanks from now :) I've tried installing django-auth-ldap and django-python3-ldap but neither installing or configuring didn't work... -
Calculating fees for smart contracts, such as USDT-TRC20, on the Tron blockchain
I'm currently engaged in a blockchain project, and one of the key components involves the creation of withdrawal transactions. However, I'm facing the challenge of displaying the transaction fee before broadcasting it to the blockchain. I am well aware of the intricacies involved in calculating smart contract fees on the Tron blockchain. Do you have any suggestions on how to obtain the necessary energy and bandwidth for a withdrawal and how to calculate the transaction fee? I am using tronpy and haven't found a helpful method for this purpose I did not found any helpful way for get contracts fee -
Django Q implement to send periodic emails
I have a Django project with several merchant accounts. When they log in using a URL, a certain view is called that aids with login and authentication. In addition, the same method determines if the merchant's plan expires in a month. If so, the function notifies you by email about the same problem. The problem now is that the view function won't execute if the user doesn't log in, which means he won't get any mail. Can I then have an automatic feature that delivers the mail and verifies each merchant? To notify merchants of their plan expiration even if they don't log in, I want a function in Djnago-Q to run even if the URL is not hit and after a set amount of time. -
Django Custom User Model Admin
In a simple self-training using Django, I'm facing the following problem: 1- I've written a custom user model with two extra fields: phone +fuck 2- I've created a custom admin using custom forms 3- In settings: added AUTH_USER_MODEL = "accounts.CustomUser" where accounts is the app name 1- In admin panel, when trying to add a new user, it doesn't display any of the extra fields and this is a problem, also in the case of editing an existing user. 2- In admin: the last statement is: admin.site.register(CustomUser, CustomUserAdmin) but if i replace it with: admin.site.register(CustomUser), every thing is well and it executed as expected enter image description here [[enter image description here](https://i.stack.imgur.com/qgh3r.png)](https://i.stack.imgur.com/mXrK4.png)