Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where can i find out Python based MCQs and Answers. Please suggest some good references
I am building a Question Bank Model. I need Sample Python based MCQs and Answers to refer as my training data. Please suggest some references I am trying every where and no luck yet. Can one help me with a valid reference to sample Python MCQs covering basics, advanced, data science, AIML Django, Flask. Any great reference will do a great help to me -
How to create a ldap BIND_DN for samba active directory
I am trying to setup samba active directory users authentication for my Django app. I working in linux. I don't have access to windows active directory. I got a docker image smblds for samba AD DC on Ubuntu 22.04 using docker run --name smblds \ --publish 389:389 \ --publish 636:636 \ --detach smblds/smblds:latest The docker started fine. I can see the smb.conf and other tdb files created. But this docker does not set the BIND_DN value. So, I executed the docker and from inside the smblds docker I provisioned the active directory with samba-tool domain provision --use-rfc2307 --interactive I used all the default settings for Realm, Domain, server role, dns backend and Administrator password I see following messages in the output Setting up self join Repacking database from v1 to v2 format (first record CN=ms-WMI-StringSetParam,CN=Schema,CN=Configuration,DC=samdom,DC=example,DC=com) Repack: re-packed 10000 records so far Repacking database from v1 to v2 format (first record CN=server-Display,CN=409,CN=DisplaySpecifiers,CN=Configuration,DC=samdom,DC=example,DC=com) Repacking database from v1 to v2 format (first record CN=51cba88b-99cf-4e16-bef2-c427b38d0767,CN=Operations,CN=DomainUpdates,CN=System,DC=samdom,DC=example,DC=com) Is any of these a BIND_DN. Actually when I try to connect to active directory using python ldap I see invalid credential error. >>> import ldap >>> ldap_server = ldap.initialize("ldap://172.17.0.5/") >>> ldap_server.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) >>> ldap_server.set_option(ldap.OPT_X_TLS_NEWCTX, 0) >>> ldap_server.start_tls_s() >>> … -
Django - pythonanywhere - ProxyConnectionError
I deployed my Django project on pythonanywhere. In the project, I use "storages.backends.s3boto3.S3Boto3Storage" as DEFAULT_FILE_STORAGE. It connects to a cloud storage so that I can upload and save media files on there. It works fine on my local system but on pythonanywhere, it gives this error when a media file is going to be uploaded: ProxyConnectionError Failed to connect to proxy URL: "http://proxy.server:3128" I'm new to this and I don't know what else information is needed on this for someone to answer my question. So let me know to edit my question. -
Testing LDAP authentication in Django
I followed the answer in this question Testing authentication in Django but no one said the result for a successful connection. I copied the same code and got a response which I do not know. Here is the response: Does anyone know what it means? -
Django Multipart Upload with Ajax AWS S3 | How to get presigned URL?
Brother, i cant get it... so i have this: s3fileuploader.py import boto3 from boto3.s3.transfer import TransferConfig from .progresshandler import ProgressHandler from lumen import settings class S3Uploader(object): def __init__(self): self.s3 = boto3.client('s3', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) self.config = TransferConfig( multipart_threshold=1024 * 100, max_concurrency=1, multipart_chunksize=1024 * 100, use_threads=False ) self.folder_name = 'simple_file_upload' self.progress_handler = None def upload(self, file_obj, filename, file_type, file_size): self.progress_handler = ProgressHandler(self.folder_name, filename, file_size) self.s3.upload_fileobj(file_obj, settings.AWS_STORAGE_BUCKET_NAME, # settings.AWS_S3_REGION_NAME, f'{self.folder_name}/{filename}', ExtraArgs={'ContentType': file_type}, Config=self.config, Callback=self.progress_handler) def get_upload_status(self): if self.progress_handler: return self.progress_handler.get_upload_status() return None class S3ParallelMultipartUploader(S3Uploader): def __init__(self): super(S3ParallelMultipartUploader, self).__init__() self.config = TransferConfig( multipart_threshold=1024 * 100, max_concurrency=10, multipart_chunksize=1024 * 100, use_threads=True ) self.folder_name = 'multipart_upload' progresshandler.py import threading from time import perf_counter from django.core.cache import cache class ProgressHandler(object): def __init__(self, cache_key_prefix, filename, size): self._filename = filename self._size = size self.perf_counter_start = perf_counter() self.cache_key = f'{cache_key_prefix}_{self._filename}' cache.set(self.cache_key, { 'uploaded_size': 0, 'progress_perc': 0, 'time_taken_s': 0 }) self._lock = threading.Lock() def __call__(self, bytes_amount): with self._lock: upload_status = cache.get(self.cache_key) upload_status['uploaded_size'] += bytes_amount upload_status['progress_perc'] = int((upload_status['uploaded_size'] / self._size) * 100) upload_status['time_taken_s'] = perf_counter() - self.perf_counter_start cache.set(self.cache_key, upload_status) def get_upload_status(self): upload_status = cache.get(self.cache_key) if upload_status: return {'progress_perc': upload_status['progress_perc'], 'time_taken_s': round(upload_status['time_taken_s'], 2)} return {'progress_perc': 0, 'time_taken_s': 0} views.py s3uploader = S3ParallelMultipartUploader() def create_post_aws(request): if request.method == 'POST': file = request.FILES["file"] title … -
How to setup Keycloak client for Frontend?
I have included the DRF-Social-OAuth2 library and set up the Keycloak client for the Backend. Now I have to create a new public client for Frontend? If yes, what is the right way to do it? -
Issue with django channels `ValueError: Invalid IPv6 URL`
I’ve setup django channels in my project and other things like APIs and Other admin urls are working fine, but when I try to create a socket connection in my project I’m getting this error WebSocket HANDSHAKING /ws/notification/ [127.0.0.1:48494] Exception inside application: Invalid IPv6 URL Traceback (most recent call last): File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/django/contrib/staticfiles/handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 35, in __call__ if self.valid_origin(parsed_origin): File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 54, in valid_origin return self.validate_origin(parsed_origin) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 73, in validate_origin return any( File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 74, in <genexpr> pattern == "*" or self.match_allowed_origin(parsed_origin, pattern) File "/home/jlp-020/Projects/POC_flutter_dating_application_BE/env/lib/python3.10/site-packages/channels/security/websocket.py", line 102, in match_allowed_origin pattern_hostname = urlparse("//" + pattern).hostname or pattern File "/usr/lib/python3.10/urllib/parse.py", line 400, in urlparse splitresult = urlsplit(url, scheme, allow_fragments) File "/usr/lib/python3.10/urllib/parse.py", line 495, in urlsplit raise ValueError("Invalid IPv6 URL") ValueError: Invalid IPv6 URL WebSocket DISCONNECT /ws/notification/ [127.0.0.1:48494] Can anyone help me with this one. -
How to create qr code from url in django? Calling from another function
I wanted to write a function that takes the generated url for each device and converts it to a qr code. this function should be called in add_new_device after url is created. My code is like this, it's not adding device at the moment. def add_new_device(self, request): user = User.objects.get(username=request.data["username"]) # last num of device to add in device_id last_number = len(Device.objects.all()) device = Device() device = self.write_fields_to_object(device, request.data, user) device.device_id = self.random_string_generator() + \ '-' + str(int(last_number) + 1) device.save() # Creates new station data added for the device self.set_station_data(request.data, device) if device.VMIscreen == "true": # Creates VMI screen automatically for url self.auto_create_new_layout(request, device) else: # Creates epmtpy screen for url empty_layout = Layout() self.create_url(empty_layout, device) self.create_qr(device) # Create Event object self.create_notification( user, device, "add", "device", "has added new Device") return "ok" def create_qr(self, device): qr_content = device.screen_url qr_name = f'qr_{device.device_id}.png' qr = make(qr_content) qr.save('media/' + qr_name) def create_url(self, layout, device): screen_url = base_screen_url + device.device_id + ".html" Device.objects.filter(device_id=device.device_id).update( screen_url=screen_url) html = self.edit_device_url_html(layout, device) s3.put_object(Bucket=device_url_bucket, Key=str(device.device_id) + ".html", Body=html, ACL='public-read', ContentType='text/html', CacheControl='no-cache, no-store, must-revalidate') -
Apache2 Django - Remote MySQL/MongoDB Access Denied 1045 (28000)
Im having troubles to access from a Ubuntu Server using Apache2 to a remote MongoDB database with python-mysql-connector. [wsgi:error] [pid 143490:tid 140602848225021] [remote 10.242.2.3:62831] 1045 (28000): Access denied for user 'db-mycon-read'@'176.69.189.21' (using password: YES) Apache2 .conf: <VirtualHost *:80> ... WSGIDaemonProcess Kompetenzauswertung python-path=/home/mycadmin/Kompetenzauswertung python-home=/home/mycadmin/Kompetenzauswertung/venv WSGIProcessGroup Kompetenzauswertung WSGIScriptAlias / /home/mycadmin/Kompetenzauswertung/Kompetenzauswertung/wsgi.py ... </VirtualHost> What works: connecting on local machine connecting via commandline on Ubuntu Server connecting via python-mysql-Connector using a simple python script What doesnt work: connecting via apache2 service Other Information: Django Runs a website that needs to fetch data from a remote db (Website has no ssl cert bc) -
In Django I can't populate a dropdown with variables in the for loop. The dropdown remains empty
I'm new to Django. I can't see items in a dropdown, but I can't figure out why. The dropdown remains empty. I know I might as well not be using the for loop, but I would like to use it. What am I doing wrong? I'm also using a list for x and y, so the loop can loop through the html, but it doesn't work views.py def seleziona_soggetto(request): #Match trip = Full_Record.objects.get(id=request.session.get("selected_trip_id")) partita = f"{trip.team_home}-{trip.team_away}" #Split Match x,y = partita.split('-') options = [x, y] return render(request, 'seleziona_soggetto.html', {"options": options}) seleziona_soggetto.html <select name="seleziona_soggetto" id="id_seleziona_soggetto" style="width:200px;" hx-get="{% url 'seleziona_soggetto' %}" hx-indicator=".htmx-indicator" hx-trigger="change" hx-swap="none"> <option value="">Please select</option> {% for i in options %} <option value="{{ i }}">{{ i }}</option> {% endfor %} </select> urls.py from django.urls import path from . import views urlpatterns = [ path('', views.trip_selector, name="trip_selector"), path('trips', views.trips, name='trips'), path('result', views.result, name='result'), path('seleziona_soggetto', views.seleziona_soggetto, name='seleziona_soggetto'), ] -
Why use One-To-One instead of inherit User class in Django?
So I want to be able to have Organizations and Customers which are users, which have some specific attributes. Everywhere I see, they use One-To-One mapping to the User class like this: class Organization(models.Model): user=models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True) tenant=models.ForeignKey(Tenant, on_delete=models.PROTECT) organization_name=models.CharField(max_length=100, default="No Organization name set") phone_number=models.PositiveBigIntegerField(default=None) description=models.TextField(max_length=None, default="No Description set") is_terms_and_conditions_agreed=models.BooleanField(default=False) status=models.IntegerField(choices=status_choices, default= PENDING) which works fine for me, but this works as well: class Organization(User): tenant=models.ForeignKey(Tenant, on_delete=models.PROTECT) organization_name=models.CharField(max_length=100) alt_number=models.PositiveBigIntegerField() description=models.TextField(max_length=None) is_terms_and_conditions_agreed=models.BooleanField(default=False) status=models.IntegerField(choices=status_choices, default= PENDING) But I cannot find a reference for inheriting User class this way without making it a proxy and making a manager. So my question is, why do we prefer the One-To-One method? -
how to get parent object from child object in Django?
class Offer(models.Model): opportunity = models.ForeignKey(Opportunity, on_delete=models.CASCADE) status = models.CharField() class Opportunity(models.Model): ...some code now i want to access offer from opportunity (child to parent). something like opportunity.offer.status. i have tried this but it doesn't work. Help please thanks. -
How can I give different priorities to flask web-apps?
My Ubuntu server runs several applications built in Python (Django or Flask), and deployed using gunicorn. Some of them also use nginx. I would like to give some of these applications a higher priority, so that, if a prioritized application is used, its performance will not be hurt by non-prioritized applications used at the same time. I know the Unix command nice could be used for giving different priorities to processes, but I do not know where exactly to apply this command: to the Python app? to the gunicorn command line? to nginx? -
How to solve the 1292 error code in django+mysql in production?
My django project works with mySQL database. It runs well on local machine without any sort of problems. Now I am trying to release it in production but my date columns are not accepting the same values which were accepted on local machine. The returned error is as: django "(1292, \"1292 (22007): Incorrect datetime value: '2023-07-23 09:41:00+00:00' for column 'date' at row 1\", '22007')" p.s: I am using a linux server in production and a cpanel dashboard. while my local machine is a windows. I have no clue what I can do to resolve the problem and there is not much relative content on internet about it that I could find. -
no Data are restore from backup
I have used django-dbbackup to get back up from database, There is a profile for each member, which is connected to "User" as "OneToOneField", The problem is that while restoring, no data restoring in the profile table, The other tables are restoring properly. these warnings printed in CMD D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index auth_group_permissions_group_id_permission_id_0cd325b0_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index auth_user_groups_user_id_group_id_94350c0c_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index auth_user_user_permissions_user_id_permission_id_14a6b632_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index django_content_type_app_label_model_76bd3d3b_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index taggit_taggeditem_content_type_id_object_id_tag_id_4bb97a8e_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index app_base_share_Workgroup_share_id_department_id_c474420a_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index app_base_meet_TargetUser_meet_id_user_id_ae3dccd4_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index app_base_meet_Workgroup_meet_id_department_id_9092086a_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: index auth_permission_content_type_id_codename_01ab375a_uniq already exists warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: Error in db restore: FOREIGN KEY constraint failed warnings.warn(f"Error in db restore: {err}") D:\CODES\python\virtualenvs\karapp2\.env\Lib\site-packages\dbbackup\db\sqlite.py:78: UserWarning: … -
Django does not save images that i am uploading
New to Django.This is my first code. I am trying to write a code for resturant that takes fields like name, cuisine, price, pic etc. It is supposed to get those fields and files and save it to the media folder. however the code does not work. some of the code is taken from chatgpt as well. Following is the code for view.py file. from django.shortcuts import render,redirect from django.db import IntegrityError from django.views import View from django.http import HttpResponse from .models import Menu import os from django.conf import settings # Create your views here. class newView(View): def post(self, request): name = request.POST.get('name') cuisine = request.POST.get('cuisine') price = request.POST.get('price') food_type = request.POST.get('food_type') desc = request.POST.get('desc') pic = request.FILES.get('pic') context = { 'menu_items': Menu.objects.all(), 'message': None } if not name or not cuisine or not price or not food_type or not desc: context['message'] = "Please don't leave any fields empty!!" return render(request, 'index.html', context) try: # Change the uploaded file name pic_name = f"{name.replace(' ', '_')}.jpg" # Assuming the uploaded files are in JPEG format m = Menu(name=name, cuisine=cuisine, price=price, food_type=food_type, desc=desc, pic=pic_name) print(os.path.join(settings.MEDIA_ROOT, pic_name)) # Save the file to the storage with the new name with open(os.path.join(settings.MEDIA_ROOT , pic_name), 'wb') … -
Error response from daemon: failed to create task for container
I have a django app. That also has redis, celery and flower. Everything is working on my local machine. But When I am trying to dockerize it The redis and django app is starting. But celery and flower is failing to start. It is giving me this error while starting celery: Error response from daemon: failed to create task for container: failed to create shim task: OCI runtime create failed: runc create failed: unable to start container process: exec: "celery -A core worker -P eventlet --autoscale=10,1 -l INFO": executable file not found in $PATH: unknown Dockerfile # For more information, please refer to https://aka.ms/vscode-docker-python FROM python:bullseye EXPOSE 8000 RUN apt update && apt upgrade -y # && apk install cron iputils-ping sudo nano -y # Install pip requirements COPY requirements.txt . RUN python -m pip install -r requirements.txt RUN rm requirements.txt WORKDIR /app COPY ./src /app RUN mkdir "log" # Set the environment variables ENV PYTHONUNBUFFERED=1 ENV DJANGO_SETTINGS_MODULE=core.settings # Creates a non-root user with an explicit UID and adds permission to access the /app folder # For more info, please refer to https://aka.ms/vscode-docker-python-configure-containers RUN adduser -u 5678 --disabled-password --gecos "" appuser && chown -R appuser /app # RUN echo 'appuser … -
Direct assignment to the reverse side of a related set is prohibited. Use associated_startups.set() instead
I am trying to create nested relationship but it not working as expected **Models.py ** class Meetings(models.Model): spoc = models.ForeignKey(User, on_delete=models.CASCADE,limit_choices_to={'groups__name': 'SPOC'},related_name='spoc_meetings') mentors = models.ForeignKey(User,on_delete=models.CASCADE,limit_choices_to={'groups__name':'MENTORS'},related_name='mentor_meetings') startups = models.ManyToManyField(Startup_info,through='MeetingStartup') meeting_agenda = models.TextField() meeting_name = models.CharField(max_length=500) duration = models.IntegerField() meeting_link = models.URLField(max_length=500,null=True,blank=True) meeting_type = models.CharField(max_length=500,null=True,blank=True) class MeetingStartup(models.Model): meeting = models.ForeignKey(Meetings, on_delete=models.CASCADE,related_name='associated_startups') startup = models.ForeignKey(Startup_info, on_delete=models.CASCADE) starting_time = models.DateTimeField() duration = models.DurationField() Serializers.py class MeetingStartupSerializer(serializers.ModelSerializer): class Meta: model = MeetingStartup fields = ['meeting', 'starting_time', 'duration', 'startup'] read_only_fields = ['meeting'] class MeetingSerializer(serializers.ModelSerializer): startups = MeetingStartupSerializer(source='associated_startups',many=True, required=True) class Meta: model = Meetings fields = ['id', 'spoc', 'mentors', 'meeting_agenda', 'meeting_name', 'duration', 'meeting_link', 'meeting_type', 'startups'] def create(self, validated_data): startups_data = validated_data.pop('startups',[]) meeting_instance = Meetings.objects.create(**validated_data) for startup_data in startups_data: # print(startup_data.pop('startup')) startup_instance = Startup_info.objects.get(startup_id=startup_data.pop('startup')) MeetingStartup.objects.create(meeting=meeting_instance, starting_time=startup_data['starting_time'],duration=startup_data['duration'],startup=startup_instance) return meeting_instance Views.py class MeetingViewSet(viewsets.ModelViewSet): queryset = Meetings.objects.all() serializer_class = MeetingSerializer permission_classes = [AllowAny] authentication_classes =[] It is working well while doing GET request but on Post I m getting this error -
Python full stack
What are the skills required for a full stack python developer in 2023? I just need some assistance from seniors about mandatory skills required for a full stack developer in python to develop my career and learn new technologies and build new websites. -
Uploading Python Django Project to GitHub
I am new in Django. My friend and I are starting to create projects to add them to our portfolio for job hunting purposes. I have a few questions for you - the professionals. Exactly which folders should be present on GitHub when uploading Django projects? Should folders like django_env, .idea, or files like .DS_Store and .gitignore be present there? Where exactly should the requirements.txt and README.md files be located? [enter image description here](https://i.stack.imgur.com/OnhPg.png) In general, how and what exactly should be uploaded to GitHub to present a project professionally? -
Django rest framework use router with pk in URL
I use DRF on my project and have some routes like: router.register(r'user', views.UserView, basename='user') router.register(r'user/{pk}/note', views.NoteView, basename='user') So I want to have an opportinuty to do GET,POST,PUT etc. actions with a note. Some part of NoteView: class NoteView(ModelViewSet, CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin): filter_backends = [DjangoFilterBackend] def get_queryset(self): return Note.objects.all() def list(self, request, *args, **kwargs): ... def create(self, request, *args, **kwargs): ... def update(self, request, *args, **kwargs): ... def destroy(self, request, *args, **kwargs): ... def get_serializer_class(self): if self.action == 'list': return NoteListSerializer return NoteSerializer But it doesn't work with this route, how should I define it? -
Proper use of prefetch_related() and select_related() in Django
I have a scenario which I believe is a good candidate to use prefetch_related() and select_related() in. As the documentation states that these should be used with care, I want to confirm that I am in fact improving performance rather than inadvertently hurting it. Here is the query: foo_items1 = Foo.objects.filter(bar=True) prefetch1 = Prefetch('baz__foo_set', queryset=foo_items1, to_attr='foo_bar1') foo_items2 = Foo.objects.filter(bar=False) prefetch2 = Prefetch('baz__foo_set', queryset=foo_items2, to_attr='foo_bar2') for item in queryset.select_related('baz').prefetch_related(prefetch1, prefetch2): print(item.baz.foo_bar1) print(item.baz.foo_bar2) Essentially, each item has a relation baz, which in turn has a reverse relation foo_set. I would like to optimally iterate over each item, and filter the foo_set on baz depending on whether bar is True or False. Am I doing this right? Or am I overengineering this? -
Issue of database connection lost getting error 2013, 'Lost connection to MySQL server during query'
We are facing the database connection error 2013, ‘Lost connection to MySQL server during query’ in the UAT server(LAMBDA). This error is coming randomly like once or twice a week, for the solution I use to push any kind of code (no matter what it can be a comment also) or I restart the database then the problem instantly resolves. But I’m looking for a permanent solution, please help me to get over of it Thank you # SSH TUNNEL try: tunnel = SSHTunnelForwarder((config('ssh_address'), 22), ssh_pkey = config('tunnel'), ssh_username = config('ssh_username'), remote_bind_address=(config('remote_address'), 3306),local_bind_address=('127.0.0.1',4280)) tunnel.start() print("SSH Started....") except Exception as e: print("==============================================================\nSSH error: \n",e,"\n==============================================================") host = '127.0.0.1' dbSchema = config("schema") user = config('user') passwd = config('password') port = 4280 # port = tunnel.local_bind_port DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': dbSchema, 'USER': user, 'PASSWORD': passwd, 'HOST': host, 'PORT': port, 'OPTIONS': { 'init_command': 'SET max_execution_time=10000000' # In milliseconds } }, 'oldDB': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'eff_eb', 'USER': user, 'PASSWORD': passwd, 'HOST': host, 'PORT': port, 'OPTIONS': { 'init_command': 'SET max_execution_time=10000000' # In milliseconds } } } -
LIKE operation in CHARACTER_VARYING[] field with django postgresql
I have an ArrayField in django model. I wants to do substring search on ArrayField(or charactervarying[]). I am not able to figure out how to do this. I am trying to write a custom lookup as: @ArrayField.register_lookup class ArrayLike(Lookup): lookup_name = "like" def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) rhs_params[0] = [f'%{rhs_params[0]}%'] params = lhs_params + rhs_params return '%s like %s::%s' % (lhs, rhs, 'character varying[]'), params Querying as objects = Model.objects.filter(ArrayField__like=value) I am expecting this behaviour Ex: obj1 < type=['django', 'postgres', 'python'] Model.objects.filter(ArrayField__like='djan') should result in [<obj1>] Can anyone help me on this. I am not able to figure this out even after a day of googling Thanks. I am trying to use icontains as a last resort -
Python / DJANGO / Venv
I want to run a django application that already exists in virtual enviremont.Someone can share me a youtube video that help ? Beacouse I just find out.how to create a django app and after run, but I have django app to test in my windows. run my app in virtual environment