Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating entities, services, selectors, and usecase into Django DRF architecture
I'm working on a Django DRF project and am considering adopting two different approaches compared to the standard Django architecture. I'd like to incorporate some concepts from other frameworks and would appreciate the community's feedback on these ideas. Primary Objective: My main goal is to achieve a modular and replicable system. First approach: Services, Selectors, Usecase Base: I'm using the standard Django DRF architecture with models, views, and serializers. Services: These are specialized boxes where I group all actions related to data creation and updating. The idea is to have a clear separation of CRUD operations. Selectors: Here, I include all actions related to data retrieval and filtering. The goal is to clearly separate responsibilities and have a singular place for all queries and data retrieval operations. Usecase: This is the core of the architecture. In this box, I encapsulate all the business logic. The idea is to have a central point where all complex logic and business rules are managed. So, the flow would be: the user calls the API, the view validates input and output data, and then calls the execute of the usecase. Within the usecase, I incorporate various actions taken from services and selectors. Second approach: … -
How can I save all the request/response in django
I have a project with multi tenancy functionality in Django. I have various apps doing different works. I have a requirement where i need to save all the request/response from any app to any url into a separate directory with each client code as different different directories inside. all the request/response can be saved as <REQ_NAME>_.json Do we have a way or some kind of middleware which can help me achieve this? -
Docker-compose ERROR [internal] booting buildkit, http: invalid Host header while deploy Django
I'm using docker compose to create a Django server, MySQL database and Django Q on a Ubuntu 22.04.3. But when I run docker-compose -f ./docker-compose.yml up, I have the following error: [+] Building 38.8s (1/1) FINISHED => ERROR [internal] booting buildkit 38.8s => => pulling image moby/buildkit:buildx-stable-1 20.4s => => creating container buildx_buildkit_default 18.5s ------ > [internal] booting buildkit: #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="using host network as the deftime="2023-10-13T13:02:28Z" level=warning msg="using host network as the default" #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="skipping containerd worker, as \"/run/containerd/containerd.sock\" does not exist" #0 38.84 dtime="2023-10-13T13:02:28Z" level=info msg="found 1 workers, default=\"abfxoy5dnaaz4694avydedw1g\"" #0 38.84 `time="2023-10-13T13:02:28Z" level=warning msg="currently, only the default worker can be used." #0 38.84 \time="2023-10-13T13:02:28Z" level=info msg="running server on /run/buildkit/buildkitd.sock" #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="skipping containerd worker, as \"/run/containerd/containerd.sock\" does not exist" #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="currently, only the default worker can be used." #0 38.84 time="2023-10-13T13:02:28Z" level=warning msg="currently, only the default worker can be used." #0 38.84 ------ http: invalid Host header My Docker info: Client: Context: default Debug Mode: false Plugins: buildx: Docker Buildx (Docker Inc., v0.10.4) compose: Docker Compose (Docker Inc., v2.17.2) Server: Containers: 1 Running: 1 Paused: 0 Stopped: 0 Images: 4 Server Version: 20.10.24 Storage Driver: zfs Zpool: rpool … -
TemplateDoesNotExist when rendering an email message with Celery in Django
I am developing an API for a forum website and have a classed-based view that sends an email message to a user in order to make his email confirmed. I have a celery task, that sends email and in the task I render data to string (email template). But when I call the task in my APIView, I get error that template does not exist. However, when I call it just as a regular function, without delay method it works as expected. Also it seems that there is no problem with Celery itself because I can run other tasks successfully. Here is the code of the view. class RequestEmailToConfirmAPIView(GenericAPIView): permission_classes = [IsAuthenticated, EmailIsNotConfirmed] success_message = 'The message has just been delivered.' serializer_class = DummySerializer def get(self, request): current_url = get_current_site(request, path='email-confirmation-result') user = request.user token = EmailConfirmationToken.objects.create(user=user) send_confirmation_email.delay( template_name='email/confirm_email.txt', current_url=current_url, email=user.email, token_id=token.id, user_id=user.id ) return Response(data={"message": self.success_message}, status=status.HTTP_201_CREATED) note: get_current_site function returns the current url including protocol (http) in order to create the url for a user to click and confirm his email the code of send_confirmation_email task: @shared_task def send_confirmation_email(template_name: str, current_url: str, email: str, token_id: int, user_id: int): """ Отправляет письмо для подтверждения определенных действий. """ data = … -
Django - AllAuth How to style the email.html template?
Quick question. I'm beefing up the authentication for my Django application. I would like to have users change and verify their emails with Allauth but I can't figure out how to style a template. Is there a way how we can style the email.html template? I tried to add {{ form.as_p }} but I only get an email field. I don't know how to add everything else. I tried looking at the Github for allauth as well for the email.html page and I don't understand it because there's a bunch of template code. I don't know what to strip out or keep. Below is what the page looks like without styling. Any help is gladly appreciated! Thanks! -
wagtail login page is endlessly looping into login page
I had a dockerised setup for a python web application with wagtail as cms which was deployed in EKS. Everything on the web page seems fine, every error seems fine but I'm unable to login to wagtail portal when I'm trying doman.com/admin. Stack I use Requirements.txt djangorestframework==3.11.0 Django>=2.1,<2.2 wagtail==2.5.1 # ***************************************************************************** django_compressor==2.2 django-libsass==0.7 django-multiselectfield django-csp django-storages[google] elasticsearch>=5.0.0,<6.0.0 # choose mariadb or postgresql (should also be set in Dockerfile).. mysqlclient==1.3.13 cssutils python-dateutil>=2.7.3,<2.8 untangle==1.1.1 puput==1.0.5 # = = = = = = = = = = = = = = = = = = = = = = = = ## puput requirements.. django-el-pagination>=3.2.4 django-social-share==1.4.0 django-colorful>=1.3 ## puput wp2pupt (WordPress importer) requirements.. lxml>=4.2.5,<4.3 # = = = = = = = = = = = = = = = = = = = = = = = = uWSGI==2.0.17 boto3==1.26.125 boto wagtailmenus==3.1.2 Please let me know if you need more info, THANKS IN ADVANCE Explained wagtail login issue and expecting some issue with code or versions i'm using -
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