Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django can't login after sign up using custom model
So i create a custom model with AbstractUser: class CustomUser(AbstractUser): email = models.EmailField(unique=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(validators=[phone_regex], max_length=17, blank=False, null=False) # Validators should be a list is_shop = models.BooleanField(default=False) products = models.ManyToManyField('Product', blank=True) class Meta: db_table = "scrape_customuser" def save(self, *args, **kwargs): if not self.pk: self.set_password(self.password) super().save(*args, **kwargs) and a sign up form class UserForm(UserCreationForm): class Meta: model = CustomUser fields = ['username', 'email', 'phone', 'password1', 'password2'] my login logic: def shop_user_signup(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_shop = True user.save() login(request, user) referring_url = request.POST.get('next', None) if referring_url: return redirect(referring_url) else: return redirect('/') else: form = UserForm() return render(request, 'shop_user_signup.html', {'form': form}) The user got created in the database with password got hash to something like this pbkdf2_sha256$600000$TvRyCcSY6eMhnV1i1urh93$aKLqPBrcma5KsuS469crJtS93UI0h+7pduJXeW6ukAU=, is_active=1 and somehow the last login is 2023-11-23 15:49:22.581983 even though the redirect didn't show username when i have <li class="nav-item"> {% if user.is_authenticated %} <a class="nav-link" href="{% url 'logout' %}">{{user.username}} | Logout</a> {% else %} <a class="nav-link" href="{% url 'login' %}">Login</a> {% endif %} </li> When i try to login in the login page i got the … -
Authentication user from a different (external) Python program
I currently running a Django application and want to provide a completely different service using Python running on the same server. This won't be a web service. For this I also want to set up some level of authentication, and kind of want to use the credentials from the Users table in the Django application. Is there a function which I can call to verify the username and password? I'm very close to the solution, but not getting a clean response yet: import os, sys import Dashboard.settings from django.contrib.auth import authenticate os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dashboard.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) user = authenticate(username="testuser", password="testpassword" ) if user is not None: print('Validated') else: # No backend authenticated the credentials print('wrong credentials') This does work, however, my output is the manage.py help menu followed by the output I want. Is there another command than execute_from_command_line(sys.argv) which I can use to mute the help menu? ... [sessions] clearsessions [staticfiles] collectstatic findstatic runserver Validated -
Filtering by distance without using postgis in django-filter
I've checked some answers related to my question but couldn't find solution. I have Foo and related FooAddress models. In django-filter I cannot filter Foo by distance, tried many options but no results. models.py class Foo(models.Model): pass class FooAddress(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name="address") longitude = models.DecimalField(max_digits=9, decimal_places=6) latitude = models.DecimalField(max_digits=9, decimal_places=6) filters.py from django_filters import rest_framework as filters from geopy.distance import distance class FooFilter(filters.FilterSet): point = filters.CharFilter(method="filter_by_distance") class Meta: model = Task fields = ["is_foo", "is_bar"] def filter_by_distance(self, queryset, name, value): point = value.split(",") if len(point) == 2: latitude = float(point[0]) longitude = float(point[1]) query_distance = self.data.get("distance") queryset = queryset.annotate( distance=distance( (latitude, longitude), (F("address_latitude"), F("address_longitude")) # accepts float or int ) ).filter(distance__lte=query_distance) return queryset In filters.py I tried to use geopy's distance method to calculate distance and it accepts float or real number but in my case I am giving F() type object that I cannot extract actual field value. Is there any way to figure out this without using postgis ? Or is it possible to do it with pure PostgreSQL query if yes how can it be done as I am not good at complex SQL queries. Thanks in advance. -
WINDOWS Could not build wheels for pyodbc, which is required to install pyproject.toml-based projects
Hello I having problems with this error: "Could not build wheels for pyodbc, which is required to install pyproject.toml-based projects" I don't know what to do! I searched and installed pyproject.toml and nothing! asgiref 3.7.2 attrs 23.1.0 Django 4.2.7 jsonschema 4.20.0 jsonschema-specifications 2023.11.1 mssql-django 1.3 pip 23.3.1 pyodbc 5.0.1 pyproject-toml 0.0.10 pytz 2023.3.post1 referencing 0.31.0 rpds-py 0.13.1 setuptools 69.0.2 sqlparse 0.4.4 toml 0.10.2 tzdata 2023.3 wheel 0.41.3 Python 3.12.0 -
Django server running on server instead running on local server when I hit on login
Django application is running on a server instead of the local server When I attempt to log in to Django application, it should normally run on your local development server (http://127.0.0.1:8000). However, if you notice that the login process redirects to a server, it might indicate an issue. url path('', auth_views.LoginView.as_view(template_name='frontend/auth-login.html'), name='login'), form <form class="form-horizontal" action="#" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for message in messages %} <div class="alert {{ message.tags }} mb-4 text-center" role="alert"> <strong>{{ message }}</strong> </div> {% endfor %} {{ form|crispy}} <div class="form-check text-start"> <input type="checkbox" class="form-check-input" id="auth-remember-check"> <label class="form-check-label" for="auth-remember-check">Remember me</label> </div> <div class="mt-3 text-end"> <button class="btn btn-primary w-sm waves-effect waves-light" type="submit">Log In</button> </div> <!---- <div class="mt-4 text-center"> <p class="mb-0">Don't have an account ? <a href="{% url 'register' %}" class="fw-medium text-primary"> Signup now </a> </p> </div>--> <div class="mt-2 text-center"> </div> </form> I have try to find view method in views and from in forms but their code not exist in that files -
Django nested formsets - 3 levels
I'm working on an app for construction company, and I want to create form for our daily schedule. For this I have 4 models: Date, DailySchedule, WorkersSchedule and MachinerySchedule. Each day we are working on several construction sites and we have 3-4 machines per CS and a few engaged workers on those sites. I'm trying to use inlineformset_factory with 3 levels of nesting, but without success: form (pick a date) formset0 (choose construction site) formset1 (choose employees) formset2 (choose machinery) date construction_site_1 employee_1 employee_2 machine_1 machine_2 machine_3 construction_site_2 employee_1 employee_2 machine_1 machine_2 machine_3 construction_site_3 employee_1 employee_2 employee_3 machine_1 machine_2 ... models.py class Date(models.Model): datum = models.DateField(blank=True, null=True) def __str__(self): return str(self.date) class DailySchedule(models.Model): date = models.ForeignKey(Date, on_delete=models.CASCADE, blank=True, null=True) construction_site = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.date) + ' --- ' + str(self.construction_site) class WorkersSchedule(models.Model): daily_schedule = models.ForeignKey(DailySchedule, on_delete=models.CASCADE, blank=True, null=True) employees = models.ForeignKey(Employees, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.daily_schedule) + ' --- ' + str(self.employees) class MachinerySchedule(models.Model): daily_schedule = models.ForeignKey(DailySchedule, on_delete=models.CASCADE, blank=True, null=True) machinery = models.ForeignKey(Machinery, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return str(self.daily_schedule) + ' --- ' + str(self.machinery) forms.py class DateForm(ModelForm): class Meta: model = Date fields = "__all__" views.py def daily_schedule_form(request): date = Date() … -
Format datefield in Django Report with reportlab
In my Django App I have an app to generate a reportlab report based on simpledoctemplates. To create the table inside the report I read the data with a value_list query to handover the queryset to the data variable for the table. teilnehmer_alle = Teilnehmer.objects.filter( teilnehmer_sprung__gt=0, teilnehmer_geburtsjahr__range=[riege.riege_ab, riege.riege_bis]).values_list('id', 'teilnehmer_name', 'teilnehmer_vorname', 'teilnehmer_verein__verein_name_kurz', 'teilnehmer_geburtsjahr', 'teilnehmer_sprung' ) and here is the handover to the table: headers = ['Start-Nr.', 'Nachname', 'Vorname', 'Verein', 'Jahrgang', 'Meldung', 'A-Note', 'B-Note', 'Summe'] table_data = [headers] + [list(row) + [''] * (len(headers) - len(row)) for row in teilnehmer_alle] if table_data: t = Table(table_data) content.append(t) everything works fine, but the value of the 'teilnehmer_geburtsjahr' isn't in the format I want to use. Currently it is 'YYYY-mm-dd' but I want only the year information in the report. Is there a way to change this inside the queryset? Or is there another solution? Any ideas? I'have tried to change the queryset without "values" or "value_list" but I didn't find a solution to change the format before I create the table. -
django asgi/channels not deployment failing
I currently have a Django ASGI project that runs well locally, but when I try to deploy it on Render or Railway, I encounter an error. Below are my build script (build.sh), Procfile, and relevant sections: My Asgi.py import django import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application django.setup() from chat.routing import websocket_urlpatterns from hometweet.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "root.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) **Build Script (`build.sh`):** #!/bin/bash # Upgrade pip and setuptools pip install --upgrade pip pip install --upgrade setuptools # Install Dependencies pip install -r requirements.txt # Run Migrations python manage.py makemigrations user python manage.py makemigrations hometweet python manage.py makemigrations profiles python manage.py makemigrations groupapp python manage.py migrate **Procfile** gunicorn root.asgi:application -k uvicorn.workers.UvicornWorker. I've tried various start commands, including: web: daphne -u /tmp/daphne.sock yourproject.asgi:application web: gunicorn root.wsgi:application gunicorn root.wsgi:application web: gunicorn root.asgi:application gunicorn root.asgi:application web: gunicorn root.asgi:application -k uvicorn.workers.UvicornWorker The last command is currently giving me a server error when attempting to access the page. is there something i need to change or add please. Please someone should help me out on how i can deploy it … -
random.choice() in form placeholder doesn't work how we expect
We used random.choice() to show random placeholders in an entry form. class EntryForm(forms.ModelForm): class Meta: my_placeholders = ['The fact that...', 'I am sure that...', 'It is awesome to...', 'I wish this was...', 'I always wanted to know how...', 'The reason I am writing this is...' ] my_placeholders_random = random.choice(my_placeholders) model = Entry fields = ['text'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80, 'placeholder': my_placeholders_random})} This works, but only if the local server is stopped using CTRL-C and restarted with python manage.py runserver or when we make changes in the file and save it. In those cases another placeholder is displayed. However, when the server is running, and we refresh the entry page a couple of times, the placeholder stays the same every time. In what way can we make sure the placeholder will be changed after every refresh? -
i cant show the image in detail page
views.py title = request.POST.get('Title') description = request.POST.get('Description') image = request.FILES.get('image') Course.objects.create(title=title, description=description, image=image) .html <form action="" class="form-control" method="post"> {% csrf_token %} <input class="form-control" name="Title" placeholder="Enter Title"> <input name="Description" class="form-control" placeholder="Enter Description"> <input name="image" class="form-control" type="file" formenctype="multipart/form-data" placeholder="Upload the image"> <button type="submit" class="btn btn-primary" style="margin-top: 10px">Submit</button> </form> detail page <img src="{{course.image.url }}" alt=""> I create the object but the image does not show in detail page how i can show the image of the object -
How to use a variable as character length parameter inside a regular expression [duplicate]
I have a regular expression pattern to find words longer than a certain amount of characters: pattern = r"\w{14,}" where i want the 14 to be dynamic. How can i insert a variable as a character length parameter inside a regular expression? I tried with no success: length = 14 pattern = re.compile(r"\w{" + str(length) + ",}") The pattern is then used as a query in a Django model as: module_list = Contentmodule.objects.filter( # Q(json__text__iregex = r"\w{14,}") Q(json__text__iregex = pattern) ) and i get the error: sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type. -
why doesn't the clean method see field in forms?
I'm facing an issue with my forms in Django. I've created something like this: class EventForm(forms.ModelForm): class Meta: model = Event fields = [ "name", "start_date", "end_date" ] def clean(self): start_date = self.cleaned_data["start_date"] end_date = self.cleaned_data["end_date"] if start_date > end_date: raise ValidationError("Start Date cannot be great than End Date") elif start_date == end_date: raise ValidationError("The dates must be different.") def clean_start_date(self): start_date = self.cleaned_data["start_date"] if timezone.now() > start_date: raise ValidationError("The start date of the event must be after today.") return start_date When I tried to test it, something weird is happening. So, when I tried to input a start_date that is after today, I get the following message: start_date = self.cleaned_data["start_date"] KeyError: 'start_date' It looks like clean() doesn't see the start_date. But why? -
I want to build a new whatsapp utility app in django
I'm new in django, want to build a whatsapp utility app , which can use API endpoints provided by the API provider to send text and media files. functionality should be like. Create a Instance ID using access token(provided by the API provider) Generate a qr_code : with the help of created instance ID and known access token. Scan generated qr_code to login to whatsapp web and send the text and media files using API endpoints provided the API provider. Any help would be appreciated. I wrote a views.py file: ` from django.http import HttpResponseimport requestsfrom django.views.decorators.csrf import csrf_exemptfrom django.http import JsonResponseWAPI_URL="https://wapicloud.in/"@csrf_exemptdef whatsapp_create_instance(request):if request.method == 'POST':api_provider = request.POST.get('api_provider', '')phone_number = request.POST.get('phone_number', '')access_token = request.POST.get('token', '') if api_provider == '' or api_provider == '1': url = WAPI_URL + 'api/create_instance?access_token=' + access_token response = hit_curl_get(url) response_data = {} # 2nd API if response\['status'\] == "success":\`your text\` instance_id = response\['instance_id'\] url_qr = WAPI_URL + 'api/get_qrcode?instance_id=' + instance_id + '&access_token=' + access_token response_qr = hit_curl_get(url_qr) # 3rd API if response_qr\['status'\] == "success": hookurl = "https://webhook.site/XXXXXXXX.com/web/123" enable = "true" url_webhook = WAPI_URL + 'api/set_webhook?webhook_url=' + hookurl + '&enable=' + enable + '&instance_id=' + instance_id + '&access_token=' + access_token response_webhook = hit_curl_get(url_webhook) response_data\['webhook_status'\] = response_webhook\['status'\] response_data\['webhook_message'\] … -
PostgreSQL + Django update large table taking ages to run a simple update
I have a table with around 47millions entries. I need to update this table for around 3mil entries very fast, for this I use type_id and an int inside a range to select records and then update the value on another field, while excluding another record. UPDATE "table_name" SET "changes" = 12 WHERE ("table_name". "type_id" = 78 AND "table_name"."rank" BETWEEN 2 AND 2238079 AND NOT ("table_name"."id" = 55423921)) This query was automatically generated by Django using the update method on a QuerySet, but it follows the bahavior described above and can be changed to what ever is more efficient. The reason I store all those records in the same table is to dynamically add new type_id inside without having to create a new table for each (assuming doing so would improve the speed). Currently the table has multiple indexes, but let's list the fields first: id (PK); type (foreign key containing ID + type name); score (BigInt); score_data (jsonb fr metadatas); changes (IntField); rank (IntField, used for range selection); user (foreign key for the user related to this record); There are different indexes : BTree for field score and rank type for it's PK, probably a BTree (it's the default … -
Optimal model structure for a Django-driven spare parts website
I am developing a website on Django for a spare parts distributor. Besides several additional tables (brands, models, countries, etc.), the main subject are spare parts themselves. My question is what would be the proper database structure for spare parts. The matter is that some characteristics are common between all spare parts (id, article, price, brand, compatibility or car model, etc.) while some other are specific for a category. For example, for a leaf spring, the number of plates is important, and for a petrol tank it is the volume in litres. I can see three options with different pro and contra: One table for all spare parts. The table has all fields and all categories, but many of them are empty. Multi-table inheritance. There is one common model "Part" and many models inherited from it, one table for each category (PetrolTank, Radiator, etc.). This is most logical, but the number of tables can potentially be great (~ no. of categories). The great number of models in one application is not recommended (for example by the nice book "Two scoops of Django"). Proxy models. All parts are kept in one table, which has all fields, many of them inevitably empty. … -
Issue whith testing django view that execute asynchrnous task (celery): unexpected tests results
I try to implement tests in Django (DJango/Docker/django-celery/PostgreSQL) but have 2 issues with tests results when view execute celery asynchronous task. The upload_file ajax view works fine 'in live'. But in tests, I face 2 issues I can not figure out: self.assertEqual(1, RCountry.objects.count()) failed whereas self.assertEqual(1, ListRandomization.objects.count()) succeed. self.assertEqual(1, ListRandomization.objects.count()) succeed even if file_upload file contain more than one record: if file contain 5 rows with differents ran_ide (FK), should create 5 records in Randomization model and self.assertEqual(1, ListRandomization.objects.count()) should failed If self.assertEqual(1, ListRandomization.objects.count()) succeed that mean that task succeed and as upadte_or_create of the 2 models are in the same atomic transaction, success of one should imply success of the other. When I look celery logs container, logs confirm task succeed. #tests.py def test_upload_file_ajax_post_valid(self): ... with tempfile.NamedTemporaryFile(mode='w+', suffix='.csv', delete=False) as temp_file: csv_writer = csv.writer(temp_file) ... with open(temp_file.name, 'rb') as file_upload: response = self.client.post( reverse('randomization_settings:upload_file'), data={'file': file_upload}, HTTP_X_REQUESTED_WITH='XMLHttpRequest', ) # tests self.assertEqual(response.status_code, 200) self.assertEqual(1, RCountry.objects.count()) self.assertEqual(1, ListRandomization.objects.count()) os.remove(temp_file.name) views.py def upload_file(request): if request.headers.get('x-requested-with') == 'XMLHttpRequest' and request.method == "POST": form = FileUploadForm(request.POST, request.FILES) if form.is_valid(): ... # Update of Country (adm_pay) Randomization (tbl_ran) task = upload_list.delay(request.user.username) # asynchronous task ... return JsonResponse({"response": "success"}, status=200) else: return JsonResponse({"response": "form_invalid"}, status=200) else: … -
How to deploy Django app with nginx on non-root url?
I have some boxed solutions written on Django inside with docker-compose. I want to deploy it on the same server and specify different root url. But if I do it Django can't find static files, because it requests this files from root url, instead of specified url. How can I say to Django that root is another url? I was trying different examples for deploy Django with Nginx and nothing works. -
how to use redis in cpanel for python (django) module celery for sending email asynchrnously
I have used celery for sending email asynchronous task I use Redis in localhost for change password but when I want use it for send email asynchronous task in server Cpanel it gives error like :- CELERY_BROKER_URL = 'rediss://myvcci.com:6379/0?ssl_cert_reqs=CERT_NONE' error= A rediss:// URL must have parameter Ssl_cert_reqs and this must be set to CERT_REQUIRED, CERT_OPTIONAL, or CERT_NONE in views.py from home.task import email_send def email(request): a=email_send.delay(email,tokenxyz) return render(request,"send_email.html") in settings.py import redis CELERY_BROKER_URL = 'rediss://myvcci.com:6379/0' CELERY_TIMEZONE="Asia/Kolkata" TIME_ZONE = 'Asia/Kolkata' CELERY_RESULT_BACKEND = 'rediss://myvcci.com:6379/0' CELERY_RESULT_EXTENDED = True in celery.py import os from time import sleep from celery import Celery from datetime import timedelta from celery.schedules import crontab # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alone.settings') app = Celery('alone') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() app.conf.broker_connection_retry_on_startup = True in __init__.py from .celery import app as celery_app __all__ = ('celery_app',) task.py from django.core.mail import send_mail from celery import shared_task from time import sleep @shared_task def email_send(email,tokenxyz): subject = 'Email verification From KartikShop' message = f'Hello\nThanks for visiting our site ,Your verification link is "https://myvcci.com/password/{tokenxyz}" \n\nNote:-this link will be valid for 5 minutes long only after that if you want to change password you … -
Django model.save() doing inconsistent updates
I am using django ORM to communicate with MySQL database inside the callback functions of my RabbitMQ consumers. These consumers are running on a separate threads and each consumer has established its own connection to its queue. Here is the code for two of my consumer callbacks: TasksExecutorService # imports from pika.spec import Basic from pika.channel import Channel from pika import BasicProperties import uuid from jobs.models import Task from exceptions import MasterConsumerServiceError as ServiceError from .master_service import MasterConsumerSerivce class TaskExecutorService(MasterConsumerSerivce): queue = 'master_tasks' @classmethod def callback(cls, ch: Channel, method: Basic.Deliver, properties: BasicProperties, message: dict): # get task task_id_str = message.get('task_id') task_id = uuid.UUID(task_id_str) task_qs = Task.objects.filter(pk=task_id) if not task_qs.exists(): raise ServiceError(message=f'Task {task_id_str} does not exist') task = task_qs.first() # check if task is stopped if task.status == cls.Status.TASK_STOPPED: raise ServiceError(message=f'Task {task_id_str} is stopped') # send task to results queue publisher = cls.get_publisher(queue=cls.Queues.results_queue) published, error = publisher.publish(message=message | {'status': True, 'error': None}) if not published: raise ServiceError(message=str(error)) # update task status task.status = cls.Status.TASK_PROCESSING task.save() return ResultsHandlerService # imports from pika.spec import Basic from pika.channel import Channel from pika import BasicProperties import uuid from jobs.models import Task from exceptions import MasterConsumerServiceError as ServiceError from .master_service import MasterConsumerSerivce class ResultHandlerService(MasterConsumerSerivce): queue = … -
Can't connect to mysql with Django inside docker
I am trying to start django project using MySQL and Docker to containerize it. But get an error. Here is it's traceback: testcasebooks-backend-1 | Traceback (most recent call last): testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection testcasebooks-backend-1 | self.connect() testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner testcasebooks-backend-1 | return func(*args, **kwargs) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/db/backends/base/base.py", line 270, in connect testcasebooks-backend-1 | self.connection = self.get_new_connection(conn_params) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner testcasebooks-backend-1 | return func(*args, **kwargs) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 247, in get_new_connection testcasebooks-backend-1 | connection = Database.connect(**conn_params) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/MySQLdb/__init__.py", line 121, in Connect testcasebooks-backend-1 | return Connection(*args, **kwargs) testcasebooks-backend-1 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/MySQLdb/connections.py", line 193, in __init__ testcasebooks-backend-1 | super().__init__(*args, **kwargs2) testcasebooks-backend-1 | MySQLdb.OperationalError: (2002, "Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)") testcasebooks-backend-1 | testcasebooks-backend-1 | The above exception was the direct cause of the following exception: testcasebooks-backend-1 | testcasebooks-backend-1 | Traceback (most recent call last): testcasebooks-backend-1 | File "/service/./manage.py", line 22, in <module> testcasebooks-backend-1 | main() testcasebooks-backend-1 | File "/service/./manage.py", line 18, in main testcasebooks-backend-1 | execute_from_command_line(sys.argv) testcasebooks-backend-1 | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line … -
Out of two Django forms and two urls only shown up with one form
One Django form is handling Excel file, while another one is handling video file. But the video file form never shown up... Would like to get any help if anyone gets an idea on what's happening around my code settings.py # Media uploading MEDIA_ROOT= os.path.join(BASE_DIR, '') MEDIA_URL= "/" it happens to claim that my media not available when I run local host and set url to media, so I have no choice but to root it on the root file urls.py from django.urls import path from django.contrib import admin from django.conf import settings from django.conf.urls.static import static import hello.views urlpatterns = [ path("", hello.views.upload_file, name="index"), path("upVideo", hello.views.showVideo, name="videoUpload"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) models.py from django.db import models class Document(models.Model): docfile = models.FileField() class Video(models.Model): name= models.CharField(max_length=500) videoFile= models.FileField(upload_to='videos/', null=True, verbose_name="") videoFile= models.FileField(upload_to='somewhere/') def __str__(self): return self.name + ": " + str(self.videoFile) forms.py from django import forms from .models import Video class UploadFileForm(forms.Form): file = forms.FileField() class VideoForm(forms.ModelForm): class Meta: model= Video fields= ["name", "videoFile"] views.py from django.shortcuts import render from django import forms from .models import Video from .forms import UploadFileForm,VideoForm #**************File Upload View****************# def upload_file(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): extract = handle_uploaded_file(request.FILES['file'].file) return … -
Docker compose up problem in fresh win10 machine
I have problem in run command: docker compose up -d failed to solve: archive/tar: unknown file mode ?rwxr-xr-x on win 10 machine, docker version is 4.25.2 perhaps, when I run the command: docker build --no-cache --rm=false . it run successfully without errors ! P.S: I have include image of the error and this is my docker-compose.yml for further assistance, and DockerFile version: "3" services: web: # the application's web service (container) will use an image based on our Dockerfile build: . # map the internal port 80 to port 8000 on the host ports: - "8000:80" # map the host directory to app (which allows us to see and edit files inside the container) volumes: - ".:/app:rw" - "./data:/data:rw" # the default command to run whenever the container is launched command: python manage.py runserver 0.0.0.0:80 # the URL 'postgres' or 'mysql' will point to the application's db service networks: - default depends_on: - db - cache - search env_file: .env-local db: # Select one of the following db configurations for the database image: mysql:5.7 command: --max_allowed_packet=32505856 --character-set-server=utf8 --collation-server=utf8_general_ci ports: - "3360:3306" # allow your local dev env to connect to the db environment: MYSQL_DATABASE: "nnuh" volumes: - ".:/app:rw" - "./data/db:/var/lib/mysql" … -
Django not findind tests within my monorepo
Alright, this seems like a noob question, but here I go: On my current company, we use a monorepo that stores several projects. Django is among one of them. Here's the basic structure: ├── README.md ├── code │ ├── __init__.py │ ├── gunicorn.conf.py │ ├── manage.py │ ├── non-django-project │ │ ├── ... │ ├── django_project │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── apps │ │ │ ├── django_app_1 │ │ │ │ ├── ... │ │ │ │ ├── tests │ │ │ │ │ ├── test_something.py │ │ │ ├── django_app_2 │ │ │ │ ├── ... │ │ │ │ ├── tests │ │ │ │ │ ├── test_something.py │ │ │ ├── django_app_3 │ │ │ │ ├── ... │ │ │ │ ├── tests │ │ │ │ │ ├── test_something.py │ │ │ │ ├── ... │ │ ├── libs │ │ │ ├── lib1.py │ │ │ ├── lib2.py │ │ │ ├── lib1.py │ │ │ ├── tests.py Now, my github workflow is simple, and baiscally setups python and run the django tests: name: django defaults: run: working-directory: ./code on: workflow_dispatch: pull_request: paths: ["code/django_project/**", ".github/workflows/django.yml"] branches: - develop … -
threading issue in django python
i make a thread for multiple user login and click on button called start timer, when its clicked thread is start whats inside start timer is i am placing stock market order, if single user login and cliked that button single order is placed and saved in database but when user login and click that button total 2 trade save in user 1 and user 2 means total 4. timer.py def start_timers(self): timer_thread = threading.Thread(target=self.run_timer,args=(self.user_id,)) timer_thread.start() views.py def start_timer(request): if request.method == 'POST': # Get the user's ID from the request user = request.user id = user.id # print(id) print('userrrrrrrrrrr',User.objects.get(pk=id)) # Start the timer logic from timer.py and save to the database timer_manager = TimerManager(User.objects.get(pk=id)) timer_manager.start_timers() # start_timers(User.objects.get(pk=id)) # For demonstration purposes, return a JSON response response_data = { 'message': 'Timer started!' } return JsonResponse(response_data) # Handle other HTTP methods if needed return JsonResponse({'message': 'Invalid request method'}) i tried threading and as well as concurrent.futures def start_timers(self): with concurrent.futures.ThreadPoolExecutor() as executor: executor.submit(self.run_timer, self.user_id) -
I have django form that is initialized with request, args and kwargs, now I want to create formset from it, how to do it?
class SpecialDateHJRTableEntryForm(forms.ModelForm): class Meta: model = HJRTableEntry fields = ['job_template', 'date'] widgets = {'is_special_date': forms.HiddenInput(attrs={'value': True}),'date': forms.DateInput(attrs={'type': 'date'})} def __init__(self, request, *args, **kwargs): super().__init__(request, *args, **kwargs) This is my form, now I want to create a formset for this form, how to do it? Solution to the above issue.