Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to save 2 or more related models in one view? in Django?
I don’t know how to save multiple linked models in django, I’m trying to override get_success_url but I’m at a dead end(. I'm trying to make sure that when saving a form, a model with basic information is saved, associated with the model with a phone number, and that is associated with the client's name. This is all so that you can save several numbers for one client; in the future, I also want to connect the client with the client’s address, because there can be several addresses. Here's the code: views.py from .models import Orders, Person, Phone from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import OrdersForms, AuthUserForm, RegisterUserForm from django.urls import reverse, reverse_lazy from django.contrib import messages from django.contrib.auth.views import LoginView, LogoutView from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect class OrderCreateView(CustomSuccessMessageMixin, CreateView): model = Orders template_name = 'create.html' form_class = OrdersForms success_url = reverse_lazy('data_base') success_msg = 'Заявка дабавлена' def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return super().form_valid(form) def get_success_url(self): # phone_number = self.request.POST.get('phones') name = self.request.POST.get('client_name') phone_number = self.request.POST.get('phones') id = self.request.POST.get('id') # ?? Person.objects.create(client_name=name) Phone.objects.create(phone=phone_number, contact=id) # I don’t know what to … -
IntegrityError NOT caught during Unit Test but other DB errors are caught
I'm using Python 3.7 and Django 3.0.3 I have a unit test that looks like this: class MaintenenceEndpointTest(APITestCase): """Maintenence Endpoint tests """ def test_reset_cost_center_throws_error_if_sales_profile_is_not_in_database(self): """Ensure the database throws an error and the endpoint returns 500 if the sales_profile is not in database""" response = self.client.post('/maintenance/reset_cost_center/', data={"cost_center_code": "test_cost_center_code", "sales_profile": "Fronter SMIA NOT PRESENT"}, format='json', HTTP_ACCEPT='application/json') self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR) and inside the Django endpoint code that gets called by the test, I have this: try: # Call the Database with an Update using the field(s) chosen by the caller (in kwargs now) CostCenter.objects.filter(cost_center_code=cost_center_code).update(**kwargs) except Exception as e: logging.error( f' CostCenterUpdateProfileAndRole:post failed with errors. Failed in updating {cost_center_code} with {kwargs} ' f'Unexpected error! Error is: [ {e} ]') return Response( data={'Error': f'Unexpected error! Error is: [ {e} ]', }, status=500) logging.info( f' CostCenterUpdateProfileAndRole:post successfully called. Set the field(s) {kwargs} for cost_center_code {cost_center_code}') return Response(status=200, data={f'Success': f'Provided cost_center_code {cost_center_code} was changed to {kwargs}'}) When I run this code under normal circumstances and pass in a non-existing Sales Profile in the JSON, the IntegrityError is ALWAYS caught by the try/except and it passes back the 500. When I run the Unit Test the IntegrityError is NEVER caught by the try/except and the code under test returns … -
Problems configuring my Django project to upload static and media files to DigitalOcean Spaces
I have created a social media app using Django and Vue. My frontend is hosted on Vercel (which is working just fine) and my backend is hosted on DigitalOcean's App Platform (I am NOT using a droplet) and connected to my Github repo. Everything about my app is functioning perfectly well except for my user-uploaded media files. I am using django-storages (S3Boto3Storage) for this purpose and have followed all of the instructions in several tutorials (such as this one, this one, and the documentation). I have even gotten my static files up on DigitalOcean Spaces using this process (as in, when I check my bucket, the correct files appear to be there), but every time I try to deploy, it fails at python manage.py collectstatic. I've tried changing literally every single element of my settings.py file pertaining to static and media variables, creating a new Spaces bucket, messing with STATICFILES_DIRS and STATIC_ROOT, and updating/changing my App-level environment variables in the DigitalOcean App Platform UI. However, I keep getting a few different errors that I've been having trouble debugging. Sometimes I get this error: ?: (staticfiles.W004) The directory '/workspace/backend/static' in the STATICFILES_DIRS setting And other times I get this error: botocore.exceptions.ClientError: … -
Websocket message from Django backend to javascript frontend
So I have correctly setup the Django consumer and routing for my websocket communication with DJango channel. The consumers.py and routing.py are in the same app where I want to use the ws = create_connection("ws://127.0.0.1:8080/notifications") My issue is that, if I set a message from the backend with ws = create_connection("ws://127.0.0.1:8080/notifications") ws.send(json.dumps({"message": "Ricevuto"})) ws.close() The frontend which is correctly connected to the same websocket with var socket = new WebSocket("ws://127.0.0.1:8080/notifications") // Creating a new Web Socket Connection // Socket On receive message Functionality socket.onmessage = function(e){ console.log('message', e) console.log(e.data) // Access the notification data } // Socket Connet Functionality socket.onopen = function(e){ console.log('open', e) } seems to no receive the message even if the consumer on DJango correctly receive it consumer.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(text_data=json.dumps({"message": "Benvenuto"})) def disconnect(self, close_code): pass def receive(self, text_data): print(text_data) text_data_json = json.loads(text_data) message = text_data_json["message"] self.send(text_data=json.dumps({"message": message})) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"notifications", consumers.ChatConsumer.as_asgi()), ] asgi.py application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)) ), } ) -
Can't upload image Django REST
I am trying to upload image through django rest framework api but I am not getting the form properly. models.py in my 'core' app: def office_image_file_path(instance, filename): ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/office/', filename) class Office(models.Model): # Other fields... image = models.ImageField(null=True, upload_to=office_image_file_path) serializer.py in 'office' app: class OfficeSerializer(serializers.ModelSerializer): class Meta: """Meta class for OfficeSerializer.""" model = Office fields = "__all__" views.py in 'office' app: class OfficeViewSet(viewsets.ModelViewSet): """ API endpoint that allows offices to be viewed or edited if authenticated. """ queryset = Office.objects.all() serializer_class = OfficeSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): """ Retrive offices for authenticated users. """ return self.queryset.filter(user=self.request.user) def get_serializer_class(self): if self.action == 'upload_image': return OfficeImageSerializer return OfficeSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) @action(methods=['POST'], detail=True, url_path='upload-image') def upload_image(self, request, pk=None): office = self.get_object() print(request.data) # Debug: Print the request data serializer = self.get_serializer( office, data=request.data ) if serializer.is_valid(): serializer.save() return Response( serializer.data, status=status.HTTP_200_OK ) return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) In Swagger when I try to upload the image via /office/office/{id}/upload-image/, I do not get the "Choose file" button. Instead I get a string($uri) field and I can't execute the file upload. I have already set MEDIA_URL and MEDIA_ROOT in my setting.py file. -
How to create single log file in uwsgi?
I’m using below uwsgi logging config file for Django application. Its creating two log files: access_log-2023-10-13.log app_log-2023-10-13.log Now I want to create one more log file named all_logs-2023-10-13.log which will have both access + app log file data. Is there any way to create this? [uwsgi] master = true http-socket = xyz_port memory-report = true module = demo_app.wsgi ... ... ... log-date = %%d/%%m/%%Y %%H:%%M:%%S %%Z logformat-strftime = true logger = stdio log-format = %(addr) - %(user) [%(ftime)] "%(method) %(uri) %(proto)" %(status) %(size) %(referer) %(uagent) %(pid) req-logger = file:/var/log/demo_app/access_log-@(exec://date +%%Y-%%m-%%d).log logger = file:/var/log/demo_app/app_log-@(exec://date +%%Y-%%m-%%d).log log-reopen = true -
How to configure Django and Nginx to allow access of static files with docker?
I'm trying to run a docker-compose container with Django and nginx but I can't access any static html or css even if lookin at the containers' app log all seems fine. I'm probably messing up with paths and permissions and I don't know where is the issue. Here is my settings.py file splitted in images because stackoverflow flagged the post as spam: InstalledApps Middleware_templates database_auth staticurl_staticroot Here is my docker compose.yml: `# Specifies Docker compose version version: "3.9" services: djangoapp: build: context: . restart: always volumes: - static-data:/vol/web environment: - DB_HOST=db - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} - SECRET_KEY=${DJANGO_SECRET_KEY} - ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS} - OPENAI_KEY=${OPENAI_KEY} depends_on: - db db: image: postgres:13-alpine restart: always volumes: - postgres-data:/var/lib/postgresql/data environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASS} proxy: build: # project folder name context: ./proxy restart: always depends_on: - djangoapp ports: - 80:8000 volumes: - static-data:/vol/static volumes: postgres-data: static-data:` My proxy dockerfile: `FROM nginxinc/nginx-unprivileged:latest LABEL maintainer="londonappdeveloper.com" COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=djangoapp ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"]` My default.conf.tpl file : … -
ModuleNotFoundError: No module named 'kafka.vendor.six.moves' in Dockerized Django Application
I am facing an issue with my Dockerized Django application. I am using the following Dockerfile to build my application: FROM python:alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DJANGO_SUPERUSER_PASSWORD datahub RUN mkdir app WORKDIR /app COPY ./app . RUN mkdir -p volumes RUN apk update RUN apk add --no-cache gcc python3-dev musl-dev mariadb-dev RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt RUN apk del gcc python3-dev musl-dev CMD python3 manage.py makemigrations --noinput &&\ while ! python3 manage.py migrate --noinput; do sleep 1; done && \ python3 manage.py collectstatic --noinput &&\ python3 manage.py createsuperuser --user datahub --email admin@localhost --noinput;\ python manage.py runserver 0.0.0.0:8000 In my requirements.txt file: kafka-python==2.0.2 When I run my application inside the Docker container, I encounter the following error: ModuleNotFoundError: No module named 'kafka.vendor.six.moves' I have already tried updating the Kafka package, checking dependencies, and installing the six package manually. However, the issue still persists. Can anyone provide insights on how to resolve this error? Thank you in advance for your help! -
Django ORM group by on primary key mysql
In the django ORM it's easy to group by when using an aggregate function like this: from django.contrib.auth.models import User User.objects.values('id').annotate(Count('id')) However if I want to group by without an aggregation function (in case of a join for example) User.objects.filter(groups__name='foo') You can use distinct function, but it will distinct on all columns. Which is painfully slow. In some other DB you can do DISTINCT ON but not on mariadb/mysql. Is there a way to group by a specific column with the django ORM or do I have to write RawSQL ? -
LOGIN FORM: I need Login for from the blow User Mode
user_type=[(1, "manager"), (2, "registeror"), (3, "Engineer"),] class Users(AbstractBaseUser): user_id=models.CharField(max_length=50,primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.EmailField(max_length=50,unique=1) pass_word= models.CharField(max_length=15) user_type = models.IntegerField(choices=user_type,default=3) is_active=models.BooleanField(auto_created=True,default=True) is_staff = models.BooleanField(default=False,null=True,auto_created=True,blank=True) is_superuser = models.BooleanField(default=False,auto_created=True,null=True,blank=True) USERNAME_FIELD = "user_name" def __str__(self) -> str: return f"{self.first_name.upper()} {self.last_name.upper()}" user_type=[(1, "manager"), (2, "registeror"), (3, "Engineer"),] class Users(AbstractBaseUser): user_id=models.CharField(max_length=50,primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) user_name = models.EmailField(max_length=50,unique=1) pass_word= models.CharField(max_length=15) user_type = models.IntegerField(choices=user_type,default=3) is_active=models.BooleanField(auto_created=True,default=True) is_staff = models.BooleanField(default=False,null=True,auto_created=True,blank=True) is_superuser = models.BooleanField(default=False,auto_created=True,null=True,blank=True) USERNAME_FIELD = "user_name" def __str__(self) -> str: return f"{self.first_name.upper()} {self.last_name.upper()}" LOGIN FORM: I need Login for from the blow User Mode Login Functionality Is not work .I need some guide to Implement Login and Authantication LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode LOGIN FORM: I need Login for from the blow User Mode -
How to use celery with django duration field
I have model Banner with duration field. I wanna update value of status field of banner after end of duration. For example, I'm creating object with hour duration, and I need to create task which will change value of status field after hour. How can I do this celery? # models.py class AdvertisementModelMixin(models.Model): class Statuses(models.TextChoices): ACTIVE = "active", _("Active") HIDDEN = "hidden", _("Hidden") DELETED = "deleted", _("Deleted") TEST = "test", _("Test") link = models.URLField() view_count = models.PositiveIntegerField(default=0) age_from = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MaxValueValidator(80)]) age_to = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MaxValueValidator(80)]) devices = models.ManyToManyField(Device, verbose_name="platforms",) duration = models.DurationField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=30, choices=Statuses.choices, default=Statuses.ACTIVE) -
Life Cycle of Daemon thread and Non Daemon Thread in Django
I'm trying to execute a long-running process (sending mail to around 600 people) using threading module. My Django view and email processing function goes like this: def daily_wap(request): context = { } if request.method == 'POST': file = request.FILES.get('dailywap', None) if file: try: wap = pd.read_excel(file, header = [0,1], engine='openpyxl').dropna(how = 'all') t = threading.Thread(target= daily_wap_automailer, kwargs={'wap': wap}, daemon = True) t.start() messages.success(request , "Task Scheduled") return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) except Exception as e: messages.error(request, 'Error occured: {0}'.format(e)) return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) else: messages.error(request, 'File not provided') return HttpResponseRedirect(reverse('usermanagement:daily_wap_automailer')) return render(request, "wap_automailer.html", context) def daily_wap_automailer(wap): ### In send_mail, im iterating over each mail ids and sending the mail, ### which then returns total mail successfully sent(count) and total no users (total) count , total = send_mail(wap=wap) return (count , total) I'm executing the function daily_wap_automailer using the daemon thread. As per the online documenation and resources, daemon thread gets terminated as soon as the main/parent thread gets terminated provided it does not have any non-daemon thread to execute. The main thread (HTTP request response cycle) typically takes less than a sec to complete(sending the message "Task Scheduled" to Client), does it mean that the daemon thread which executes func daily_wap_automailer won't have sufficient time … -
How can I add a telegram bot in Django application
I have a Django application (store) and I want to receive notifications about new users who have registered in the store. I also want to receive messages via telegram bot if any user has logged in. I've never written telegram bots before. I will be glad of any information and support. The most important thing I want to know is how to connect bot and django. Does the bot need private server? Any links or tutorials will be helpful. -
I don't understand this TemplateDoesNotExist error
I am very new to Django. Currently following the book django for beginners (https://djangoforbeginners.com/) and all was fine and dandy until chapter 4. I get the following error: TemplateDoesNotExist at / home.html, posts/post_list.html I don't know where this comes from. Why is Django looking for the posts/post_list.html file? I am not referring to that file anywhere afaik. I get this error message: Request Method: GET Request URL: serverurl Django Version: 2.1 Exception Type: TemplateDoesNotExist Exception Value: home.html, posts/post_list.html Exception Location: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/template/loader.py in select_template, line 47 Python Executable: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/bin/python3 Python Version: 3.10.12 Python Path: ['/home/tang/LinuxServ/message_board_django', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages'] Server time: Fri, 13 Oct 2023 10:31:52 +0000 Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/tang/LinuxServ/message_board_django/templates/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/admin/templates/home.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/auth/templates/home.html (Source does not exist) Using engine django: django.template.loaders.filesystem.Loader: /home/tang/LinuxServ/message_board_django/templates/posts/post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/admin/templates/posts/post_list.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/tang/.local/share/virtualenvs/message_board_django-jJcCRH2C/lib/python3.10/site-packages/django/contrib/auth/templates/posts/post_list.html (Source does not exist) Does it come from my file structure? #posts/view.py from django.views.generic import ListView from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' <!-- templates/home.html --> <h1>Message board homepage</h1> <ul> {% for post in object_list %} <li>{{ post }}</li> {% endfor %} </ul> … -
Django breaking css after using if statement
I'm trying to add a dropdown list into my navbar that i created using bootstrap but whenever i put the dropdown menu into the if statement to loop categories into a list, the css breaks. without if statement(only for loop) <nav class="navbar navbar-expand-lg navbar-dark nav-color fixed-top"> <a class="navbar-brand" href="{% url 'home' %}" ><b>Lorem Ipsum</b></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown"> <a class="nav-link active dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="true"> Categories </a> <ul class="dropdown-menu"> {% for item in cat_menu %} <li><a class="dropdown-item" href="{% url 'category' item|slugify %}">{{ item }}</a></li> {% endfor %} </ul> </li> {% if user.is_authenticated %} <li class="nav-item active"> <a href="{% url 'blogposts'%}" class="nav-link" id="hover-change">Blog Posts <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a href="{% url 'personalinfo'%}" class="nav-link">About Me <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'create-post'%}">Create Post <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'create-category'%}">Create Category <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="{% url 'logout'%}">Logout <span class="sr-only">(current)</span></a> </li> {% else %} <li class="nav-item active"> <a href="{% url 'blogposts'%}" class="nav-link" id="hover-change">Blog Posts <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a href="{% url 'personalinfo'%}" class="nav-link">About Me <span class="sr-only">(current)</span></a> </li> … -
How can i solve the error ("storages.backends.s3boto3" does not define a "S3StaticStorage")?
when i putted the configurations: # Amazon S3 Configuration AWS_ACCESS_KEY_ID = "*******************" # AWS_SECRET_ACCESS_KEY = "****************" # AWS_STORAGE_BUCKET_NAME = 'karafeta-bucket' # # Django > 4.2 STORAGES = {"staticfiles": {"BACKEND": "storages.backends.s3boto3.S3StaticStorage"}} # Django < 4.2 #STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False in settings.py in my django project i got an error sayes : django.core.files.storage.handler.InvalidStorageError: Could not find backend 'storages.backends.s3boto3.S3StaticStorage': Module "storages.backends.s3boto3" does not define a "S3StaticStorage" attribute/class the whole error : python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). October 13, 2023 - 13:16:16 Django version 4.2.3, using settings 'karafeta.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Internal Server Error: / Traceback (most recent call last): File "C:\Python3-10-2\lib\site-packages\django\core\files\storage\handler.py", line 35, in __getitem__ return self._storages[alias] KeyError: 'staticfiles' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python3-10-2\lib\site-packages\django\utils\module_loading.py", line 30, in import_string return cached_import(module_path, class_name) File "C:\Python3-10-2\lib\site-packages\django\utils\module_loading.py", line 15, in cached_import module = import_module(module_path) File "C:\Python3-10-2\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", … -
Handling "No color selected" and "No size selected" Messages in Django Form Submission
I'm working on a Django project where I have a form that allows users to select a color and size before adding a product to their cart. However, I'm encountering an issue when users submit the form without making selections. I receive the following messages: "No color selected" and "No size selected in terminal." look at add_to_cart function home.html <form method="POST" action="{% url 'add_to_cart' products.id %}"> <div> <select name="colors" class="border border-gray-200 focus:outline-none "> {% for color in Colors.all %} <option value="{{color.color}}">{{color.color|capfirst}}</option> {% endfor %} </select> <select name="sizes" class="border border-gray-200 focus:outline-none "> {% for size in Sizes.all %} <option value="{{ size.size }}">{{ size.size }}</option> {% endfor %} </select> </div> </form> views.py from django.shortcuts import render,redirect from .models import * def home(request): product = Product.objects.all() sizes = Sizes.objects.all() colors = Colors.objects.all() return render(request , 'home.html' , {'Product':product , 'Sizes':sizes , 'Colors':colors}) def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) cart = request.session.get('cart', []) if request.method == 'POST': selected_color = request.POST.get('colors') selected_size = request.POST.get('sizes') cart_item = { 'product_id': product.id, 'color': selected_color, 'size': selected_size, } print(cart_item['product_id']) if selected_color is not None: print(cart_item['color']) else: print("No color selected") if selected_size is not None: print(cart_item['size']) else: print("No size selected") cart.append(product.id) request.session['cart'] = cart return redirect('home') def view_cart(request): # Retrieve … -
Connexion python pywin32 au Sage100c cloud Object Model
Qui peux m'aider car je ne sais plus : J'ai toujour cette erreur : Erreur de connexion au sage 100c: (-2147221008, 'CoInitialize n’a pas été appelé.', None, None) ``import logging import os import pythoncom import win32com from win32com.client import Dispatch from utils.logs import write_log Initialise COM au début du script pythoncom.CoInitialize() def connect_to_sage_100c(name_gcm, username_sage, password_sage, types): try: # Obtenir le chemin du fichier associé à l'objet FieldFile file_path = os.path.join('data', f'{name_gcm}') # Vérifier si le fichier existe if file_path == '': write_log("Le fichier Sage 100c n'existe pas.", logging.ERROR) print("Le fichier Sage 100c n'existe pas.") return conn = win32com.client.Dispatch("Objets100c.Cial.Stream") if types == 'gcm' else win32com.client.Dispatch( "Objets100c.Cpta.Stream") print('Conn ', conn) conn.Name = name_gcm conn.loggable.userName = username_sage conn.loggable.userPwd = password_sage conn.Open() if conn.IsOpen: write_log("Connexion à Sage 100c réussie.", logging.INFO) print("Connexion à Sage 100c réussie.") return conn else: write_log("Échec de la connexion à Sage 100c.", logging.ERROR) print("Échec de la connexion à Sage 100c.") return None except Exception as ex: write_log(f"Erreur de connexion au sage 100c: {str(ex)}") print(f"Erreur de connexion au sage 100c: {str(ex)}") return None finally: # Assurez-vous d'appeler CoUninitialize à la fin pythoncom.CoUninitialize() pass `` -
how to get output in python after click button in html
how to create a button and after clicking the button get the output show the same page input and output show same page and it's also getting some pop message show on title bar and some action on click on button. in html page divide two-part one part is button and second part is use for output and backend using django -
Cannot access admin if setting is set and cannot acces website if setting is not set
I have a Django website in production so DEBUG = False There is a setting: SESSION_COOKIE_SECURE = True If it is set to True then I can access the admin and log in, but then I cannot access the website itself and I get a bad gateway error. If the setting is missing or set to False then I can access the website fine but I cannot log into admin. A bit confusing Here are the settings related to domains and CSRF: ALLOWED_HOSTS = ["localhost","102.219.85.91","founderslooking.com","app.founderslooking.com"] CORS_ALLOWED_ORIGINS = [ "http://localhost", "http://127.0.0.1", "http://localhost:file", "http://app.founderslooking.com", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_DOMAIN = "founderslooking.com" SESSION_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ["http://localhost", "http://*.127.0.0.1", "http://app.founderslooking.com",] INTERNAL_IPS = [ "127.0.0.1", ] First time I deploy a Django site so not sure what the settings should be for production. Thanks -
How to run python script running when django server starts
How to run python script running when django server starts. For example, I have a python kafka script , this script should be running continously when django server starts. when i give two commands in Dockerfile like CMD ["python", "manage.py","runserver","0.0.0.0:8443"] CMD [ "python", "./consumer.py"] only the latest cmd it is picking up. Any idea how to start python script and django server using single cmd. how to start python script and django server using single cmd. -
Confused about details of oauth2 authorization and authentication after reading Django-salesforce documentation
I am trying to integrate Salesforce with a Django application, so users can login into my site and push data themselves into the salesforce database. I have read the django-salesforce github page, and I confirmed that I can make postman calls to the database with oauth2 tokens, but I have some questions which probably stems from my ignorance of this subject. If I hardcode my username and password-concat-token into the django salesforce database settings, then won't all new database entries be authorized under my account? Ideally, shouldn't users authenticate into my application with their salesforce account, and then make API calls under the authorization of their own account? Or does this not matter at all? Also, if I hardcode my username and password-concat-token like above, then do I need a separate authentication and authorization system? If I hardcode my token into the django database information like that, then theoretically any backend call would inject my account's oauth2 information to make API calls. I was hoping users could click on a "Sign in with Salesforce" button and be authenticated on my site that way, going 100% for the social login system and not make my own. Any clarifications on my misunderstandings … -
Is there a way to pass django value to python script?
The python script that I have written fetches ticker data and historical data for the stock. Currently the stock value is hardcoded as you can see below. if __name__ == "__main__": stock = 'TSLA' data = GetData() data.tickerData(stock = stock) data.getHistData(stock = stock, startDate = startDate, endDate = endDate) I would like to know whether it's possible to send the user inputted value [via django forms] to this main function and have this script executed. If someone has come across this scenario, please advise. -
How to use TimeZone in Django
In my django project use: TIME_ZONE = 'Asia/Ho_Chi_Minh' USE_I18N = True USE_L10N = True USE_TZ = True But when I add this field: dateOrder = models.DateTimeField(auto_now_add=True) into my Order object, when initializing and printing it using def getDateOrder(self) method: weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] return weekdays[self.dateOrder.weekday()] + ', ' + self.dateOrder.strftime("%d/%m/%Y, %H:%M") is still UTC format Looking forward to receiving feedback from everyone -
Django not loading static from nginx in docker container
I django server cannot load static files, however they are accessible directly through a URL. I have a django server that is served by gunicorn inside a docker container. My Django static sttings.py: STATICFILES_DIRS = [ (os.path.join(BASE_DIR, "static")), ] STATIC_URL = "/static/" STATIC_ROOT = os.path.abspath(os.path.join(BASE_DIR, "../static")) My Nginx conf: http { sendfile on; server { listen 80; server_name localhost; location / { proxy_pass http://gunicorn:8000; } location /static/ { autoindex on; alias /static/; } } } My nginx docker-compose configuration: nginx: image: nginx:1.19.6-alpine depends_on: - gunicorn ports: - "80:80" expose: - "80" - "443" volumes: - ./nginx.conf:/etc/nginx/nginx.conf - ./certs:/etc/nginx/certs - nginx_static:/static When i start the django server with debug mode on, the files load at localhost:8000 where the gunicorn container is, but they are not avaliable at localhost:80 where my nginx container is. When I start it with debug off, static files arent loaded at all. When I try to access a static file through nginx, e.g. localhost:80/static/my_static.css the file loads I think this may be an issue with my django settings as calling the static in a html template like: {% static 'img/logo.png' %} will load that image, however none of my other css files will load even though {% …