Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
How to resolve in django AttributeError: module 'learning_logs.views' has no attribute 'new_entry'
This is my views.py: from django.shortcuts import render, redirect # Create your views here. from .models import Topic from .forms import TopicForm, EntryForm def index(request): """The home page for learning Log.""" return render(request, 'learning_logs/index.html') def topics(request): """Show all topics.""" topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) def topic(request, topic_id): """Show a single topic and all its entries.""" topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) def new_topic(request): """Add a new topic""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): form.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'form: form'} return render(request, 'learning_logs/new_topic.html', context) def new_entry(request, topic_id): """Add a new entry for a particular topic.""" topic = Topic.objects.get(id=topic_id) if request.method != 'POST': # No data submitted; create a blank form. form = EntryForm() else: # POST data submitted; process data. form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) # Display a blank or invalic form. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) Here is my urls.py: … -
Django Decorator that refreshes on current page of request if condition is failed
So, I am trying to write a decorator that restricts access to some pages. But instead of redirecting to a new page, which I have done and I am okay with for some instances, in this case I simply want it to show an error on the current page. I am okay with it refreshing the current path but I keep running into errors regarding paths. Here is my current working code with redirect. How do I modify this? def member_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME, message=default_message): def decorator(view_func): @wraps(view_func) def _wrapped_view(request, *args, **kwargs): member = ProfileMember.objects.get(user=request.user) print(member.first_name) if not test_func(member): print("failed the test") messages.add_message(request, messages.ERROR, message) print(messages) if test_func(member): print("pass the test") return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url) login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator def user_preapproved(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, home_url='/', message=default_message): """ Decorator for views that checks that the user is an approved member, displaying a message if provided. """ actual_decorator = member_passes_test( lambda m: m.preapproved, login_url=home_url, redirect_field_name=redirect_field_name, message=message ) if view_func: return actual_decorator(view_func) return actual_decorator My attempt at simplify it works … -
How to manage dependencies in a shared git subtree?
Lets say I have four git repos named A,B,C, & D A,B, & C (customer repos): Each repo contains a Django project for customers 1, 2, & 3 respectively Each customer exists in an air gapped environment From a user perspective, each of the Django projects are, more or less, functionally the same The repos have similar dependencies, although, they may vary in their versions (Django 2.x vs Django 4.x, PostgreSQL 13 vs 14, PostgreSQL vs SQLite, python package versions, etc.) D (common repo): This repo contains the code (Django apps & utilities) that is common across the customer repos This repo has been added as a git subtree to each of the customer repos The problem occurs when their is a dependency clash between the code in the customer repos and the common repo. For instance, if there was a line of code in the common repo that relies on Django 4.x and repo A depends on Django 2.x, then there will be errors. This same type of problem may occur with other dependencies. I've thought of two "solutions": Converge towards a single set of dependencies for all repos. In order to get this to work, however, each customer … -
How to solve the problem django.db.utils.OperationalError: no such column
enter image description here I just wanna add other attribute to model class BookCardsModel(models.Model): class Meta: verbose_name = 'Card Books' verbose_name_plural = 'Card Books' book_cover = models.ImageField() book_name = models.CharField(max_length=100) book_subtitle = models.CharField(max_length=100) book_description = models.TextField(max_length=300) full_description = models.TextField(max_length=700) book_quantity = models.IntegerField(default=0) book_color = models.CharField(max_length=100, blank=True) book_size = models.CharField(max_length=100, blank=True) digital = models.BooleanField(default=False,null=True,blank=False) -
My dropdown menu that I created with django-mptt and bootstrap 5.3 is not showed up on my template , how can I fix it?
My dropdown menu that I created with django-mptt and bootstrap 5.3 is not showed up on my template , how can I fix it??? I tried a lot to fix this but I can't, can anyone help please ? This is my template code : div class="dropdown"> <ul class="dropdown-menu"> {% recursetree categories %} <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ node.name }} </button> <li {% if not node.is_leaf_node %}class="dropdown-submenu"{% endif %}> <a class="dropdown-item {% if not node.is_leaf_node %}dropdown-toggle{% endif %}" href="{% if node.is_leaf_node %}{{ node.get_absolute_url }}{% endif %}" {% if not node.is_leaf_node %}role="button" data-bs-toggle="dropdown" aria-expanded="false"{% endif %}> {{ node.name }} {% if not node.is_leaf_node %}<span class="dropdown-caret"></span>{% endif %} </a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> And this is my views.py class HomePage(View): def get(self, request, ): postss = Post.objects.all() categories = Category.objects.all() form = CategoryForm() return render(request, 'home/index.html', {'postss': postss, 'categories': categories, 'form': form}) And this is a js code for this dropdown document.addEventListener('DOMContentLoaded', function() { var dropdownSubmenus = [].slice.call(document.querySelectorAll('.dropdown-submenu')); dropdownSubmenus.forEach(function(submenu) { submenu.addEventListener('mouseenter', function() { this.querySelector('.dropdown-menu').classList.add('show'); }); submenu.addEventListener('mouseleave', function() { this.querySelector('.dropdown-menu').classList.remove('show'); }); }); }); It's just not work idk why It's showing up the dropdown codes … -
Cannot make a connection from django in docker container to other services in docker compose
I am trying to send a post request from my Django server in a docker container to another service in a container initiated by docker-compose which are both in the same network. The API I am trying to connect and the Django API are working fine in the development environment locally(not in Docker). The API service that I am trying to connect from the Django server is working fine in the docker container too when I try to access it separately through url. But when I try to call that API through my Django server I am getting this error. aipbpk_server_container | http://localhost/rapi/predkmaxcsv aipbpk_server_container | Internal Server Error: /v1/api/aipbpk/predKmaxRserver aipbpk_server_container | Traceback (most recent call last): aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/connection.py", line 174, in _new_conn aipbpk_server_container | conn = connection.create_connection( aipbpk-nginx-1 | 172.28.0.1 - - [21/Aug/2023:21:19:28 +0000] "POST /api/v1/api/aipbpk/predKmaxRserver HTTP/1.1" 500 193790 "-" "PostmanRuntime/7.32.3" "-" aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/util/connection.py", line 95, in create_connection aipbpk_server_container | raise err aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/util/connection.py", line 85, in create_connection aipbpk_server_container | sock.connect(sa) aipbpk_server_container | ConnectionRefusedError: [Errno 111] Connection refused aipbpk_server_container | aipbpk_server_container | During handling of the above exception, another exception occurred: aipbpk_server_container | aipbpk_server_container | Traceback (most recent call last): aipbpk_server_container | File "/usr/local/lib/python3.9/site-packages/urllib3/connectionpool.py", …