Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-allauth change password not working
first time poster be gentle. I have created a project using allauth with the documentation including adding bootstrap elements. My login/logout/sign up pages all work but when I do change or forgotten password I get a confirmation saying password is changed successfully but only the old password still works. I even span up a fresh project with nothing else added such as custom user etc and this still happens and I can't figure out why it doesn't work out if the box. Any ideas? -
Django migrations wont work..OperationalError at /admin/blog/comment/ no such column: blog_comment.description
Apply all migrations: blog Running migrations: Applying blog.0002_alter_comment_description_alter_reply_description...Traceback (most recent call last): File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return super().execute(query, params) sqlite3.OperationalError: no such table: blog_reply The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/chandansblog/manage.py", line 22, in <module> main() File "/home/chandansblog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 356, in handle post_migrate_state = executor.migrate( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/migration.py", line 132, in apply operation.database_forwards( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 175, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 831, in alter_field self._alter_field( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 463, in _alter_field self._remake_table(model, alter_fields=[(old_field, new_field)]) File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/sqlite3/schema.py", line 336, in _remake_table self.execute( File "/home/chandansblog/.virtualenvs/env/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 201, in execute cursor.execute(sql, … -
create a profile record when creating a user in Django
I'm trying to solve this error: TypeError: Profile.save() got an unexpected keyword argument 'force_insert' signals.py from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import User from .models import Profile @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() model.py class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) The objective is to create a profile record when a user is created. Appreciate any wisdom on this. -
Generate html to pdf using xhtml2pdf in django project
I have an HTML page containing multiple tables. When converting it to a PDF using xhtml2pdf, it works fine if only a few tables are expanded. However, if I expand more tables, I run into a size limitation where the PDF turns out blank if the content exceeds a certain size(30Mb). Views.py def generate_pdf(request): template_path = 'app.html' context = { 'data': 'This is dynamic data passed to the template' } pdf_stylesheets = """ <style> @page { size: A4 landscape; margin: 1.5cm; } .table-wrapper { width: 100%; } table { width: 100%; border-collapse: collapse; table-layout: fixed !important; } thead { display: table-header-group; } tbody { page-break-inside: avoid !important; break-inside: avoid !important; } tr { page-break-inside: avoid !important; break-inside: avoid !important; } td { padding: 8px; border: 1px solid #ddd; font-size: 14px; vertical-align: top; } /* Column widths */ td:nth-child(1) { width: 10%; } td:nth-child(2) { width: 15%; } td:nth-child(3) { width: 10%; } td:nth-child(4) { width: 45%; max-width: 45%; word-wrap: break-word !important; word-break: break-word !important; overflow-wrap: break-word !important; white-space: pre-wrap !important; } td:nth-child(5) { width: 20%; } .message-cell { position: relative; max-width: 45%; word-wrap: break-word !important; word-break: break-word !important; overflow-wrap: break-word !important; white-space: pre-wrap !important; } .message-content { display: inline-block; width: … -
Accessing MEDIA_URL & trailing slash redirect
In order to access {{ MEDIA_URL }} from templates, I added + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urlpatterns. Recently I noticed that this breaks the default APPEND_SLASH functionality in Django. I.e. I get a 404 when the trailing is missing, unless I remove + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from urlpatterns, in which case it correctly redirects to the URL with the trailing slash. I think I'm missing something fundamental, because it seems to me that accessing MEDIA_URL from templates is a basic requirement to display media correctly, without breaking other basic functions in Django. -
Custom GraphQL String Field Parameter
I'm required to sanitize all my inputs coming in via the GraphQL endpoint and remove potential malicious stuff (No the Django build-in mechanism are not enough, it shall be actively removed). As I do not want to add the sanitization for every mutation manually, I thought about creating a custom graphene.String() class called clean_string.String() including nh3.clean() for the sanitization so I must only exchange singe lines: import graphene import nh3 from graphql import StringValueNode, Undefined class String(graphene.String): @classmethod def parse_value(cls, value): if isinstance(value, str): cleaned_value = nh3.clean(value) else: cleaned_value = value return super(String, cls).parse_value(cleaned_value) @staticmethod def parse_literal(ast, _variables=None): if isinstance(ast, StringValueNode): return nh3.clean(ast.value) return Undefined In my schema.py I have then import clean_string class CreateUser(graphene.Mutation): user = graphene.Field(UserType) class Arguments: email = clean_string.String(required=True) password = clean_string.String(required=True) @staticmethod def mutate(_, info, email, password) # sanitized email & password But this does not get called at all. When I have inputs like <img>password</img> and do the sanitation manually the result will be <img>password but with my custom class nothing happens. Does anyone have a clue how to resolve this? Thanks in advance! -
Django url path not routing properly
NoReverseMatch at /post/comment/1 Reverse for 'comment-reply' with arguments '('',)' not found. 1 pattern(s) tried: ['post/comment/reply/(?P<pk>[0-9]+)\\Z'] path('post/<slug:slug>/comment/create', CommentCreate.as_view(), name='post-comment'), path('post/comment/reply/<int:pk>', ReplyCreate.as_view(), name='comment-reply'), path('post/comment/<int:pk>', CommentDetailView.as_view(), name='comment-detail'), class ReplyCreate(LoginRequiredMixin, CreateView): """ Form for adding a blog comment. Requires login. """ model = Reply fields = ['description',] def get_context_data(self, **kwargs): """ Add associated blog to form template so can display its title in HTML. """ # Call the base implementation first to get a context context = super(ReplyCreate, self).get_context_data(**kwargs) # Get the blog from id and add it to the context context['comment'] = get_object_or_404(Comment2, pk = self.kwargs['pk']) return context def form_valid(self, form): """ Add author and associated blog to form data before setting it as valid (so it is saved to model) """ #Add logged-in user as author of comment form.instance.author = self.request.user #Associate comment with blog based on passed id form.instance.comment=get_object_or_404(Comment2, pk = self.kwargs['pk']) # Call super-class form validation behaviour return super(ReplyCreate, self).form_valid(form) def get_success_url(self): """ After posting comment return to associated blog. """ return reverse('detail2', kwargs={'slug': self.kwargs['slug'],}) class CommentDetailView(LoginRequiredMixin,generic.DetailView): model = Comment2 comment2_detault.html: {% extends 'blog/basedetail.html' %} {% block content %} <div class="card mb-3"> <div class="card-body"> <div class="card-title fw-bold">{{ comment.author }} | ({{ comment.post_date }})</div> <p class="card-text">{{ comment.description }}</p> </div> </div> <div … -
Creating long polling requests in django or fastapi
I wanted to build long polling requests in django or fastapi. I want to use redis for it. I will listen to some key in redis. and when something updates i will return changed result as soon as some change happens in my db to client. But my server accepts many requests at the same time. Is there any way to build non blocking version of it? -
Switching from WSGI to ASGI (Gunicorn + Uvicorn) in Django Production – Site Not Loading
I recently built a Django application using Django Channels for WebSocket support. My asgi.py is set up for handling both HTTP and WebSocket connections, and everything works perfectly in development using Daphne and Uvicorn. In Productin initially, my app was running on Gunicorn (WSGI), but since I need WebSocket support, I switched to Uvicorn (ASGI). To achieve this, I modified my gunicorn.service file to use UvicornWorker instead of the default WSGI worker. I encountered the error: Django can only handle ASGI/HTTP connections, not lifespan. To fix this, I created a custom worker class based on a solution from older Stack Overflow answers: from uvicorn.workers import UvicornWorker class MyUvicornWorker(UvicornWorker): CONFIG_KWARGS = {"lifespan": "off"} Then, I updated my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/home/django/my_project ExecStart=/home/django/my_project/venv/bin/gunicorn \ --limit-request-line 8190 \ --access-logfile /var/log/gunicorn/access.log \ --error-logfile /var/log/gunicorn/error.log \ -k project.uvicorn_worker.MyUvicornWorker \ --workers 3 \ --env DJANGO_SETTINGS_MODULE=project.settings.base \ --bind unix:/run/gunicorn.sock \ --log-level=debug \ project.asgi:application ExecReload=/bin/kill -HUP $MAINPID [Install] WantedBy=multi-user.target After restarting gunicorn.service, everything appears to be running fine, gunicorn.service and nginx.service are active ping mysite.com is working No errors in /var/log/gunicorn/error.log -
Django: Migrations not detecting changes after manually deleting migration files in production app
What happened: I had an app called app with migrations up to 0012. I mistakenly deleted migration files, including 0001_initial.py. Now, when I run python manage.py makemigrations app, no new migration files are detected, even though I have made changes to the models. This issue is persisting even in a newly created app called comments, where no migration files are being detected either, despite having added new fields to the models. What I’ve tried: I’ve ensured that the app is listed in INSTALLED_APPS. I’ve run python manage.py makemigrations app to generate migration files, but no changes are detected. I can’t drop the database as it is a production environment, and I need to preserve existing posts and data. What I need help with: I need to figure out how to properly reset or re-sync the migrations without losing any production data. For now i have empty migrations folder with init.py innit that doesnt create any migration file. Specifically, how do I: Recreate missing migrations after deleting files manually (i.e., to match the state of the database, which still has migrations applied up to 0012). Ensure that any new apps or changes to models are correctly detected and have corresponding migration … -
Encrypt and decrypt the data that can be seens in the Swagger of the Django when making any Rest API
I am making a django project and using DRF to make the API's also using the Swagger UI to make it interactive for the backend testing Image of the Swagger Request which can be seen So in this image i want to make the "-d" to be encrypted and also in the frontend when i want to encrypt the data when you go see it in the networks also decrypt the data when API is using making the CRUD operations with the database. I am using the serializers here. How can i implement the encryption and make changes in the serializers or the curl "-d" option so that i can only see the encrypted Data in swagger. Shall i make a middleware to encrypt the data? How i can also encrypt the data whenever my response is being given by the API. So that on frontend when using inspect it is encrypted Data. Thanks in Advance and for your suggestion to make my project better and secure!! -
Can't read "csrftoken" from cookies (Django)
I am working on a Django backend. The backend is deployed on Render, and I am testing email validation logic by sending OTP but for that i need to send "csrftoken" for the POST request. At first the cookie was not getting set in cookies in firefox (but was getting set it chrome), since it was asking for the cookie to have partitioned attribute set, since django does not yet support it, i had to include a custom middleware to do it. Now currently for some reason i am not able to read the csrftoken. views.py: @ensure_csrf_cookie def register(request): if request.method == "POST": ...... elif request.method == "GET": return JsonResponse({"message": "GET request handled"}, status=200) prod.py: from .common import * CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:8001", "http://localhost:8001", "https://forkmemaybe.github.io/temp/", ] CSRF_COOKIE_SAMESITE = "None" CSRF_COOKIE_SECURE = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ "http://127.0.0.1:8001", "http://localhost:8001", "https://forkmemaybe.github.io/temp/", ] SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_SECURE = True HTML page i am making requests from URL: [http://127.0.0.1:8001/live.html] ...... <script> function getCookie(name) { let cookieValue = null; console.log(document.cookie); if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the … -
Get mutual settlements from records. using SQL
How to Generate Mutual Settlements for a Specific Employee in SQL? I have a table where I track mutual settlements for employees. The table contains the following columns: employee_id: The ID of the employee amount: The transaction amount (can be positive or negative, based on the reason) reason: A description of the transaction created_at: The timestamp when the transaction occurred I need to generate a report showing how an employee's balance changes over time, like this: Start Balance Change Final Balance 0 +50 50 50 -15 35 35 +10 45 45 -5 40 My SQL Query (Not Working as Expected) I tried using a window function to calculate the previous balance, change, and final balance, but the results are incorrect: SELECT id, employee_id, COALESCE(LAG(SUM(amount)) OVER (ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS prev_amount, amount AS change, SUM(amount) OVER (ORDER BY created_at ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS final_amount FROM settlement_settlement GROUP BY id ORDER BY created_at; -
Why is request.user not being populated in Django when using custom JWT middleware?
I'm implementing custom JWT authentication in Django and I'm using middleware to decode the JWT token and assign request.user to the authenticated user. However, when I try to access request.user inside my view or decorator, it's not being populated, even though the middleware is correctly decoding the token and assigning it. class JWTAuthenticationMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Check for the presence of the JWT in the Authorization header # Debugging the Authorization header print(f"Authorization Header: {request.headers.get('Authorization')}") auth_header = request.headers.get("Authorization") if auth_header and auth_header.startswith("Bearer "): token = auth_header.split(" ")[1] try: user = decode_jwt_token(token) print(f"JWT Decoded Payload: {user}") # Print decoded token request.user = user # Assign the user here request._force_auth_user = user print(f"JWT Middleware: User assigned: {request.user.email} - {request.user.role}") except jwt.ExpiredSignatureError: print("JWT Middleware: Token expired") except jwt.DecodeError: print("JWT Middleware: Invalid token") response = self.get_response(request) print( f"JWT Middleware (After Response): {request.user if hasattr(request, 'user') else 'No User'}" ) # Debug after response return response class InviteUserView(APIView): """Invite a user via email with role assignment""" @bypass_csrf @authorize @role_required([UserRoleEnum.SUPER_ADMIN.value]) def post(self, request): print(f"DEBUG: User in request inside view - {getattr(request, 'user', 'No User')}") serializer = UserInvitationSerializer(data=request.data) try: if serializer.is_valid(): invitation_link = send_invitation(request, serializer, request.user) response = create_response(201, ResponseCodes.SUCCESS, … -
Bootstrap 4 Navbar Toggler Button Appears but Does Not Expand the Menu
I am using Bootstrap 4 for my Django project, and my navbar toggle button appears when the screen size is reduced. However, clicking the button does nothing—the menu does not expand or collapse. Here is my code:(base.html) {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SkyLog - {% block title %}Home{% endblock %}</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="icon" type="image/svg+xml" href="{% static 'images/airplane-svgrepo-com.svg' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="#"><b>SkyLog</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link mx-3 active" aria-current="page" href="{% url 'home' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="{% url 'login' %}">Login</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="#">LogBook</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="#">Search</a> </li> <li class="nav-item"> <a class="nav-link mx-3" href="#">Analytics</a> </li> </ul> </div> </div> </nav> <div class="container mt-4"> {% block content %} <!-- Page content goes here --> {% endblock %} </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha384-fQybjgWLrvvRgtW6jwXnDdRjjvQcTbLrR9fOr5bT8i4QgFO44FtfFZ4lAAey7m70" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-Uo5Xkna0FgAq06YLyj2hx5Lu5A5xN1W6zVnHJvaApGsXOMA5ol3KSk2EjPmhoUmR" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy5E2fHk1hCwLlG5OWv9F7JqxMk5DQCVRHsENBO" crossorigin="anonymous"></script> </body> </html> I have included Bootstrap 4.3.1 CSS and JS from a CDN. I used data-toggle="collapse" and data-target="#navbarNav" on the button. … -
DRF allauth email authentication unique constraint failed
I am trying to implement an email authentication with djangorestframework, dj-rest-auth and allauth. Here is my custom user model class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Here is my settings.py ... AUTH_USER_MODEL = "users.CustomUser" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_LOGIN_METHODS = {'email'} ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ... It registers a new user as expected if the there is not an existing user with the same email, but if I try to create an user with an email that has already been registered, I got this error: django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email I expected allauth to handle this error since it does with username authentication. Am I missing something? Should I handle this error manually? -
Trying to pull Google Reviews with Python/Django, failed by ChatGpt, Claude and DeepSeek
I have a django app where user sign’s in with google and gives permission to access google business profiles to pull reviews. I store those google tokens in my database. But when I try to pull google reviews, it can not pull. It can not even get google business profile data. I tried Chatgpt, Claude, Deepseek but failed. Here is my django and python code what I tried before. Google sign in code in Django: def google_integration(request, location_id): app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL gb_url = request.GET.get('gb_url') gb_incentive = request.GET.get('gb_incentive') params = f'?location={location_id}&redirect_url={request.META.get("HTTP_REFERER")}' params += f'&gb_url={gb_url}' params += f'&gb_incentive={gb_incentive}' return redirect(app_url + reverse('business:google_integration_from_origin') + params) #@subscribed_business_only def google_integration_from_origin(request): location_id = request.GET.get('location') previous_page = request.GET.get('redirect_url') gb_url = request.GET.get('gb_url') gb_incentive = request.GET.get('gb_incentive') if not location_id: messages.error(request, 'Location not found') return redirect('dashboard:index') app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL flow = Flow.from_client_secrets_file( 'client_secrets.json', scopes=['https://www.googleapis.com/auth/business.manage'], redirect_uri=app_url + reverse('business:google_callback') ) auth_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true', prompt='consent' # Forces Google to show the permission screen again ) request.session['google_auth_state'] = state request.session['location_id'] = location_id request.session['google_callback_redirect_url'] = previous_page or reverse('dashboard:index') request.session['gb_url'] = gb_url request.session['gb_incentive'] = gb_incentive return redirect(auth_url) # @subscribed_business_only def google_callback(request): state = request.session.get('google_auth_state') location_id = request.session.get('location_id') app_url = settings.APP_URL[:-1] if settings.APP_URL.endswith('/') else settings.APP_URL gb_url … -
collaborative plateform Real time cursor problem in web socket
My problem is a cursor position in my project. When the web socket open and at setTimeout send code to the another connection room. then my cursor position and text is not showing currently and my cursor go back. and i am facing experience like gaming ping issues., i am also keep track cursor. My script code is: //This is onmessage if (data.action === "code_update") { if (editor.getValue() !== data.code) { // Prevent redundant updates const cursorPosition = editor.getCursorPosition(); console.log("Cursor: ",cursorPosition) editor.setValue(data.code,-1); // Update without moving cursor to the end editor.moveCursorTo(cursorPosition.row, cursorPosition.column); } } // Send code updates on editor changes (debounced to reduce spam). let debounceTimeout; let lastSentCode = ''; editor.session.on("change", function () { clearTimeout(debounceTimeout); debounceTimeout = setTimeout(() => { const currentCode = editor.getValue(); if (currentCode.trim() !== lastSentCode.trim()) { sendCodeUpdate(currentCode); lastSentCode = currentCode.trim(); // Update the last sent code } },100); }); // Send code updates on the WebSocket async function sendCodeUpdate(code) { const cursorPosition = editor.getCursorPosition(); // Store cursor position await chatSocket.send(JSON.stringify({ action: "code_update", username: username, code: code, cursor_position: cursorPosition, // Send cursor position })); } please check and help me -
how to refer back to the model from utils.py in a Django object
I'm trying to create a field in a django model, that forces a unique value in the model. I'm using utils.py to generate the value. The error I get is: File "/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/utils.py", line 2, in <module> from MCARS.models import Profile ImportError: cannot import name 'Profile' from partially initialized module 'MCARS.models' (most likely due to a circular import) (/Users/evancutler/PycharmProjects/DjangoProject1/MCARS/models.py) Here's my model: class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberid = models.CharField( max_length = 10, blank=True, editable=True, unique=True, default=utils.create_new_ref_number() ) avatar = models.ImageField(upload_to="static/mcars/img/avatars", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) invited = models.BooleanField(default=False) registered = models.BooleanField(default=False) height = models.PositiveSmallIntegerField(null=True, blank=True) phone = models.CharField(max_length=32, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) number = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) here's my utils: import random from MCARS.models import Profile def create_new_ref_number(): not_unique = True while not_unique: unique_ref = random.randint(1000000000, 9999999999) if not Profile.objects.filter(memberid=unique_ref): not_unique = False return str(unique_ref) how do I tell the utils.py to refer back to the model to check if the value is unique and if not, to try again? Thanks! -
Issue with cron django
I am trying implementing django crontab into my django project. Everything works fine except logging, in the docker container folder with logging does not exist. My settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_crontab', 'core', 'crypto', ] CRONJOBS = [ ('* * * * *', 'crypto.management.commands.run_cron_job', '>> /var/log/cron.log 2>&1'), ] Cron task from django.core.management.base import BaseCommand from django.utils.timezone import now import logging logging.basicConfig(filename="/var/log/cron.log", level=logging.INFO) class Command(BaseCommand): def handle(self, *args, **kwargs): logging.info(f"Cron ran at {now()}") self.stdout.write(f"Cron ran at {now()}") Docker compose file version: '3.8' services: db: image: postgres container_name: postgres_server ports: - "5432:5432" networks: - local_network volumes: - db_data:/var/lib/postgresql/data environment: POSTGRES_DB: ${POSTGRES_DB} POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} pg_admin: image: dpage/pgadmin4 environment: PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL} PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD} networks: - local_network ports: - "8080:80" depends_on: - db web: working_dir: /app container_name: app image: python ports: - "8000:8000" networks: - local_network command: > bash -c " apt-get update && apt-get install -y cron vim && mkdir -p /var/log && touch /var/log/cron.log && chmod 777 /var/log/cron.log && service cron start && pip install -r requirements_test.txt && pip install -r requirements_dev.txt && python manage.py makemigrations && python manage.py migrate && python manage.py crontab add && python manage.py createsuperuser --noinput && python manage.py runserver 0.0.0.0:8000" volumes: … -
Django Scraper Matching Issue: match_maker Only Returns 4 Members Instead of 150
Question: I'm working on a Django project that uses Scrapy to scrape member profiles from a website. The scraped data is processed by a method called match_maker. However, I'm encountering an issue where match_maker only returns 4 members, despite having 150 members in the database (excluding 3 staff members). Details: Database: Contains 153 members; 3 are staff members, leaving 150 regular members. Profile Types: Each member has a profile_type of either 'Man', 'Woman', 'Trans', or 'Couple'. Issue: In the match_maker method, there's a loop that processes rooms and assigns them to members. A set named used_rooms is used to track assigned rooms to ensure each room is only assigned once. The relevant code snippet is: if room["username"] in used_rooms: continue When this condition is active, only 4 members are returned. If I comment out this check, the method processes all 150 members, but the number of available rooms exceeds one million, which is incorrect. Objective: I need each room to be assigned to only one member, ensuring no more than one member owns a particular room. I'm looking for guidance on how to resolve this issue so that match_maker correctly processes all 150 members without assigning multiple members to the … -
Django Streaming Video / Audio - RangedFileResponse
Folks, For ages I've been using RangedFileResponse to enable streaming (particularly with Safari), but to allow ranged streaming with Django. (Please note, it's been forked quite heavily, the one I've been using is from https://github.com/devmonkey22/django-ranged-fileresponse. Now, I've been always wondering if there was a more up-to-date way to do this, since there hasn't seemed to be a better answer? I just recently started to use django-extensions more fully, and bumped into the Werkzeug extensions when I enabled SSL for the Dev environment. But I also found that Werkzeug can help with the Ranged file response. This is what I came up with, and it seems to be faster than using the django-ranged-fileresponse. Sometimes significantly faster. from werkzeug.http import parse_range_header from django.http import FileResponse, HttpResponseNotAllowed, HttpResponseBadRequest def stream_video(request, fqpn, content_type="video/mp4"): file_size = os.path.getsize(fqpn) if request.method != 'GET': return HttpResponseNotAllowed(['GET']) if request.is_secure(): range_header = request.META.get('HTTPS_RANGE') else: range_header = request.META.get('HTTP_RANGE') ranges = parse_range_header(range_header) if not ranges: return FileResponse(open(fqpn, 'rb')) # For simplicity, handle only single range requests start, end = ranges[0] with open(fqpn, 'rb') as file_to_send: file_to_send.seek(start) data = file_to_send.read(end - start + 1) response = FileResponse(data, content_type='application/octet-stream') response['Content-Length'] = len(data) response['Content-Range'] = f'bytes {start}-{end}/{file_size}' response['Accept-Ranges'] = 'bytes' response.status_code = 206 # Partial … -
Why transition-duration along with transform scale could not be set via js/css? (But could be set via DevTools)
The problem is setting transition-duration along with transform scaling results in transformation with zero duration (although style shows up in DevTools as expected) if being set through css, js or html style. But results correctly if being set manually through browser DevTools (changing aforesaid style in DevTools). The MRE is just: <div style="transform: scale(~times~); transition-duration: ~time~"> sandy </div> Working through Django latest version. In the meantime, opacity trasition-duration works as expected, so the trouble is about scaling. Checked the issue in firefox, edge and chrome Though the MRE works as expected in fiddle -
why request.post only send csrftoken, not my form's field
im new in django and this is my first project. I create a loginform and when I want to use it, It just send csrftoken not my requierd fields this my form: class MyLoginForm(forms.Form): username = forms.CharField(max_length=50) password = forms.CharField(widget=forms.PasswordInput()) and this is my views: def login_view(request): if not request.user.is_authenticated: if request.method == "POST": form = MyLoginForm (request.POST) print(request.POST) if form.is_valid(): print('valid!!!') data = form.cleaned_data username = data["username"] password = data["password"] try: account = Account.objects.get(username=username) except Exception as error: print(error) return HttpResponseRedirect(reverse("login")) if account is not None: if password == account.password: login(request, account) return render(request, "home.html", {"account": account}) else: return HttpResponseRedirect(reverse("login")) else: return HttpResponse(f"<h2>No such a User : {username}</h2>") else: print(form.errors) # Print form errors to debug return HttpResponse("form is not valid") else: form = MyLoginForm(request.POST) return render(request, template_name="login.html", context={"form": form}) else: return HttpResponseRedirect(reverse("home")) and this is my html: <form method="post" action = ""> {% csrf_token %} <div class="form-group"> <label for="username">نام کاربری</label> <input type="text" id="username" name="username" required> </div> <div class="form-group"> <label for="password">کلمه عبور</label> <input type="password" id="password" name="password" required> </div> <button type="submit">ورود</button> </form> and Im getting this: <QueryDict: {'csrfmiddlewaretoken': ['rxjKh3oNsgdRBtT20rT1uVWLw2qOR2oQqjOct9iPhEsnJiHAUVgriiDj3Tg1qoog']}> usernameThis field is required.passwordThis field is required. -
How to store images
I store various image files in my media file in the Django framework and I use MongoDB to store my data, but as far as I understand, storing photos directly in MongoDB is not a preferred method. What path should I follow at this point to get a more efficient result? I thought about using tools like AWS S3, but I'm not sure if this is the right way, and I'm inexperienced in data management. I would appreciate it if you could briefly explain how to do it.