Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to set CSRF token in nextjs for django
Noob in need. I'm building an app that takes an image on nextjs and send its to a django backend. I'm currently stuck on this error WARNING:django.security.csrf:Forbidden (CSRF cookie not set.) The problem is I'm not sure how to set the cookies in the header request. I'm especially confused about whether to do in on the nextjs frontend or nextjs backend. I have a page.tsx (/src/app/capture/page.tsx) file loaded on /capture route. (pastebin: https://pastebin.com/cceX0CEV ) When the picture is uploaded, it is sent to the nextjs route /api/capture route ( /src/app/api/capture/route.ts). (pastebin: https://pastebin.com/8M5ezzA2 ) You can see here I already have functionality to fetch the CSRF cookie from django and I'm trying to add it to the request header but that doesn't work. Here, the file is now sent to the django backend: localhost:8000 here's the relevant django backend function in my views.py (pastebin: https://pastebin.com/PPj9NR3k ) and the relevant settings in my settings.py (pastebin: https://pastebin.com/UVyMQvYR ) I came across this but it didn't change much (you can see parts of it in my route.ts) Please, any help here will be appreciated. How do I set the cookie in the header? (previous iteration of this question here. hoping to get better luck … -
How to debug memory leak on DigitalOcean App Platform
My Django application run perfectly fine on my local machine, memory usage fluctuate between 700MB and 800MB, but when I execute the exact same code on DigitalOcean App Platform the memory usage is constantly increasing until it reach 100%. Then the application reboot. What could cause the issue and how to find the root cause ? I have tried to isolate the problem with memory_profiler and the @profile decorator, but the memory increase isn't associated with any line of my code. I track memory usage like this : total = memory_usage()[0] logger.info(f"Memory used : {total} MiB") -
Nested transaction.atomic loops with locks
With a Django 5.0.2 and PostgreSQL 14 (Azure Database Flexible Server) setup, I have this piece of code which, basically, translates to: with transaction.atomic(): objects = ObjectModel.objects.all(): for object in objects: with transaction.atomic(): another_object = AnotherObjectModel.objects.select_for_update().get(id=1000) # ... I've been having quite a few crashes in my database and this has proven to be the point where the bottleneck happens. As it's legacy code (and forgive me the blame game) and I cannot trace any documentation or testimony as to why it was implemented like this, would anyone have a point of view of how this could or could not be a cause for the crash? Please forgive me if this is not too explicit or not compliant to the forum's rules, I'll be more than happy to try to elaborate. I have not tried anything so far, I'm afraid. -
How to create a user profile for; 'RelatedObjectDoesNotExist: User has no userprofile' in Django
I need to create agents for my leads but I'm facing a challenge. When I execute my code it works, but when I want to create an agent this error pop's up. leads.models.User.userprofile.RelatedObjectDoesNotExist: User has no userprofile This is my agents apps views.py from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import reverse from leads.models import Agent from .forms import AgentModelForm class AgentListView(LoginRequiredMixin, generic.ListView): template_name = "agents/agent_list.html" def get_queryset(self): return Agent.objects.all() class AgentCreateView(LoginRequiredMixin, generic.CreateView): template_name = "agents/agent_create.html" form_class = AgentModelForm def get_success_url(self): return reverse("agents:agent-list") def form_valid(self, form): agent = form.save(commit = False) agent.organisation = self.request.user.userprofile agent.save() return super(AgentCreateView, self).form_valid(form) The 3rd line from the bottom is what I believe brings the error message. This is the full error message Internal Server Error: /agents/create Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\auth\mixins.py", line 73, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 143, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\edit.py", line 182, in post return super().post(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\edit.py", line 151, … -
CSS file not getting linked in Django project
I'm a beginner in the Django framework. I created a very simple page with one heading and tried to link the CSS with it. However, I'm not able to link it. I have seen tutorials also but no luck. [enter image descenter image description hereription here](https://i.stack.imgur.com/ZTr0c.png)enter image description here I was trying to just create a web page with some text on it -
How to create two postgres database when docker-compose up?
Dockerfile: FROM python:3.9 ENV PYTHONUNBUFFERED=1 RUN apt-get update && apt-get upgrade -y \ && apt-get install -y gcc gunicorn3 libcurl4-gnutls-dev librtmp-dev libnss3 libnss3-dev wget \ && apt-get clean \ && apt -f install -y WORKDIR /App COPY requirements.txt /App/ RUN pip install -r requirements.txt COPY . /App/ >! RUN pip install django~=4.1.1 RUN mkdir -p /App/data/db/ RUN chown -R 1000:1000 /App/data/db/ EXPOSE 7000 EXPOSE 8001 ` I have base-compose file that contain database image, here is file content: version: '3.3' networks: shared_network: driver: bridge services: testdb: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=develop_db - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" networks: - shared_network volumes: postgres_data: Here is my docker-compose file: version: '3.3' include: - ./base-compose.yml services: test_develop: container_name: test_develop build: . command: python manage.py runserver 0.0.0.0:7000 ports: - "7000:7000" env_file: - ./environments/.env.develop depends_on: - testdb networks: - shared_network links: - testdb Here is my docker-compose-prod.yml file: version: '3.3' include: - ./base-compose.yml services: test_production: container_name: test_production build: . command: python manage.py runserver 0.0.0.0:8001 ports: - "8001:8001" env_file: - ./environments/.env.prod depends_on: - testdb networks: - shared_network links: - testdb when i run the docker-compose up --build it create develop_db but i want to create prod_db too. I try to create two … -
Code not working on IIS server but working on localhost - Exception Type: KeyError at / Exception Value: '_auth_user_backend'
I am struggling with the below error : Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'xx.middleware.LDAPAuthMiddleware', 'xx.middleware.UserLogMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware'] Traceback (most recent call last): File "C:\xx\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\utils\deprecation.py", line 133, in __call__ response = self.process_request(request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\contrib\auth\middleware.py", line 71, in process_request if request.user.get_username() == self.clean_username(username, request): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\contrib\auth\middleware.py", line 92, in clean_username backend_str = request.session[auth.BACKEND_SESSION_KEY] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\xx\venv\Lib\site-packages\django\contrib\sessions\backends\base.py", line 53, in __getitem__ return self._session[key] ^^^^^^^^^^^^^^^^^^ Exception Type: KeyError at / Exception Value: '_auth_user_backend' I don't really understand when this error is triggered and why. Working on localhost does not trigger the error but when trying to use the site on IIS it does trigger this error, so this is quite hard to debug. Below is my middleware : def get_client_user(self,request): username = request.META.get('REMOTE_USER') if username is None: username = request.META.get('HTTP_REMOTE_USER') if username is None: username = 'Anonymous' return username def __call__(self, request): auth = LDAPBackend() My_User_Test = self.get_client_user(request) My_User_ip = self.get_client_ip(request) username = My_User_Test.replace("MC-DOMAIN\\","") if not request.user.is_authenticated: print(username) user = auth.populate_user(username) request.user = user else: user = request.user context = {'metadata_user': username, 'request_user': My_User_Test, 'request_ip': My_User_ip,} if user is None: print("User not authenticated: ", username) return render(request, 'Not_Authorized.html',context) else: … -
Read the Docs compile failure
I want to compile the documentation of my Django project I made with Sphinx. Every things seems ok, I create the file with the command "make html", push to my github repository and finally connect Read the docs to this repository. I request the compilation which failed. I got this log that doesn't really help me to understand: Read the Docs build information Build id: 23529747 Project: python-p13 Version: latest Commit: None Date: 2024-02-22T16:16:57.891284Z State: finished Success: False [rtd-command-info] start-time: 2024-02-22T16:16:58.554108Z, end-time: 2024-02-22T16:17:00.943549Z, duration: 2, exit-code: 0 git clone --depth 1 https://github.com/th3x4v/Python_P13.git . Cloning into '.'... [rtd-command-info] start-time: 2024-02-22T16:17:00.980730Z, end-time: 2024-02-22T16:17:01.411216Z, duration: 0, exit-code: 0 git fetch origin --force --prune --prune-tags --depth 50 refs/heads/master:refs/remotes/origin/master [rtd-command-info] start-time: 2024-02-22T16:17:01.502170Z, end-time: 2024-02-22T16:17:02.569231Z, duration: 1, exit-code: 0 git checkout --force origin/master Note: switching to 'origin/master'. You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can discard any commits you make in this state without impacting any branches by switching back to a branch. If you want to create a new branch to retain commits you create, you may do so (now or later) by using -c with the switch command. Example: git switch -c Or … -
Django / SendGrid - Password Reset - "The from address does not match a verified Sender Identity. "
I started integrating SendGrid into a django project. The integration seems to work, as when a user registers a welcome email is sent to the user with email@domain-name.com as the from_email However, if a user request a new password, this produces a 500 error: "The from address does not match a verified Sender Identity." The sender identify is obvioulsy verified because the other email signals work. Questionning SendGrid on the question, they say that the email is blocked because its coming from webmaster@localhost. Which I find a bit odd. I am confused, where in Django this default email address could be? Here is my current settings.py for email: EMAIL_FROM = "email@domain-name.com" EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.sendgrid.net" EMAIL_HOST_USER = "apikey EMAIL_HOST_PASSWORD = config('SENDGRID_API_KEY', default='') EMAIL_PORT = 587 EMAIL_USE_TLS = True I dont have a specific view setup for password change except the following: class PasswordsChangeView(PasswordChangeView): form_class = PasswordChangingForm success_url = reverse_lazy('home') and, just in case this is an example of of the signals.py that triggers the welcome email: @receiver(post_save, sender=UserProfile) def created_user_profile(sender, instance, created, **kwargs): if created: subject = "title" message = render_to_string("main/email/welcome_email.html",{ 'username':instance.user, 'email': instance.user.email, }) from_email = settings.EMAIL_FROM print(f'from_email - {from_email} ') to_email = [instance.user.email] print(f'to_email - {to_email} … -
The way to build Stream API using Python and OpenAI
Now I am building my own server with Django and OpenAI 4.0 model. when I send my audio, that need to transcript immediately. and then, transcripted text send to my frontend with stream(in other chunked). btw, I don't know the way to build the stream API well. If there are devs to know this tech, please let me know. Thank you! I try to implement the celery and asyncio and redis. -
Custom query for select field in Djnago admin
is it possible to make custom query for that field? I have many users, I need to filter if by group to reduce the number of choices. admin panel - select input I didn't find anything except making custom query for whole models. -
Questions about django rest framework for project
I'm a final year CS student and i opted to do my project using flutter and Django and MySQL. I'm making a texting app that allows users to send messages(texts and images) make audio and video calls. Being my first project in Django I'm unsure how to proceed. to give more precise questions: -should everything be an API that the flutter consumes? Im currently working on user auth and registration, should the messages (plan to use websockets/socket.io) and the calls and the other features be all made as restful API's? The project has a 3.5 months duration, i plan to spend the first month familiarizing myself with the API creation and consumption. This is my first post on this website even though i always use it for solutions so im unsure if a general question like this is valid, however im grateful for any input -
DRF bulk insert crashes on serializer.data: too many values to unpack (expected 2)
I have two serializers and I use list_serializer_class for bulk inserts. I use viewset and in my viewset @action(methods=['post'], detail=False, url_path='bulk') def bulk_create(self, request): serializer = self.get_serializer(data=reusables, many=True) ......... self.perform_create(serializer) The data is successfully inserted into the database but when I try to get the data from the serializer headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) I get the error: too many values to unpack (expected 2) probably beucase it's trying to decode the data using the first serializer and not the list_serializer_class These are my serializers: class ItemsSerializer(object, serializers.ListSerializer, serializers.ModelSerializer): name = serializers.CharField(source='display_name', max_length=90) def update(self, instance, validated_data): pass def create(self, validated_data): items = [Item(**item) for item in validated_data] return Item.objects.bulk_create(items) class Meta: model = Item fields = ('id', 'displayName', 'content', 'creationDate', 'modificationDate', 'ownerName', 'site', 'lastEditorName', 'uuid') class ItemSerializer(object, serializers.ModelSerializer): name = serializers.CharField(source='display_name', max_length=90) class Meta: list_serializer_class = ItemsSerializer model = ReusableBlock fields = ('id', 'name') -
How to resolve: ModuleNotFoundError: No module named 'leadsagents' in Django
I know the is a lot of similar questions but I've tried different solutions from stack overflow, the web and YouTube. This happened after making migrations to my db.sqlite3 file it worked until I tried adding new agents. Any help will be appreciated. Also I don't even know which files to upload because the is no module names leadsagent in my project. Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\USER\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'leadsagents'``` Will be happy to share requested files you might need to help me solve my error. -
How to connect django allauth socials to frontend?
I managed to setup allauth for github authentication but I dont know how to connect it properly to my frontend so I can login through frontend and fetch needed data for displayment. I tried many things. Currently I have managed to make it so when I login, I get redirected to a json page full of login data needed for frontend but still cant find a proper way to connect it. -
Tpye hints for mixins that reference attributes of a third-party base class
I'm trying to add type hints to a mixin class that is to be used alongside an external, third-party class. That is, the mixin relies on members of the third-party class. For example, a mixin for a Django form: # mixin_typing.py from django import forms class SuffixFormMixin: suffix: str def add_suffix(self, field_name: str) -> str: # prefix is an attribute of forms.Form return f"{self.prefix}__{field_name}__{self.suffix}" class SuffixForm(SuffixFormMixin, forms.Form): pass Understandably, mypy will complain about the add_suffix method: "SuffixFormMixin" has no attribute "prefix" IDE (PyCharm) will also throw a warning: Unresolved attribute reference 'prefix' for class 'SuffixFormMixin' Question: Is there any "easy" solution that lets the mixin understand that self contains attributes/methods of forms.Form? Here is a github issue that addresses this, but sadly didn't go anywhere: https://github.com/python/typing/issues/246 Maybe some kind of typing object or other mypy-fu that acts as a promise to the mixin class that the future "partner class" has the members that the mixin is using? Attempted solutions The suggestions I have found so far all have drawbacks: Type-hinting self to the partner class (works for mypy: ✅, doesn't work for IDE: ❌) I have seen suggestions to type hint self to the class that the mixin will later … -
Why are multiple bootstrap modals being rendered after HTMX hx-get?
I have a Django page using HTMX to populate some bootstrap styled tabs (Members, Events and Contacts). 'hx-get' is used to load the desired page content into the DOM. On the Members page, I have a button that opens a bootstrap modal form when clicked for the user to add a member. The issue is that the number of times the modal is rendered to the DOM when the button is clicked corresponds to the number of times the Members content is loaded. If the Members page is rendered twice (navigating from Members tab to Events tab, then back to Members), two modals appear in the DOM and so on. I initially thought it may be caused by the modal form also being rendered with hx-get. However, I've replaced the modal form with a basic modal on the same page and the issue persists. Why is only the modal being rendered multiple times? The members page is only being rendered once. Tabs code: <div class="container"> <div class="row"> <div class="nav flex-column nav-pills me-3 col" role="tablist" aria-orientation="vertical" id="tabs" hx-target="#tab-contents" _="on htmx:afterOnLoad take .active for event.target"> <button type="button" id="members-btn" role="tab" aria-controls="tab-contents" aria- selected="true" hx-get="{% url 'members' %}" class="nav-link active"> Members </button> <button type="button" … -
django "import excel to database" libraries
I need to do "import excel to database" using django. I know that some of the libraries that help are "django-import-export", "openpyxl", and others are "pandas", "xlrd", etc. What is the difference between these libraries? Which library is right for what I'm trying to do? -
Django CSRF protection for cross site post requests
I am using react as frontend and using django for backend. When I host both the frontend and backend on localhost, everything works fine and X-CSRFTOKEN is sent perfectly. const instance = axios.create({ withCredentials: true, withXSRFToken: true, xsrfHeaderName : 'X-CSRFTOKEN', xsrfCookieName : 'csrftoken' }); My DJango settings are (taken from this answer Django - check cookies's "SameSite" attribute): CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = "None" SESSION_COOKIE_SAMESITE = "None" but when my frontend (firebase )and backend(eks aws) are hosted on different subdomains, I receive a 403 Forbidden Error. It should return a 201 ccreated response but instead it is returning a 403 error, CSRF verification failed. Request aborted. -
'Serverless Function Exceeded 250 MB' Error on Vercel Django Deployment?
I have this issue (" A Serverless Function has exceeded the unzipped maximum size of 250 MB. : https://vercel.link/serverless-function-size") when i'm trying to deploy to Vercel, I tried to remove as much as possible of non-needed packages but nothing changed, this is my installed packages from vercel: Successfully installed Django-4.2.3 MarkupPy-1.14 MarkupSafe-2.1.3 Pillow-10.0.0 PyJWT-2.8.0 PyYAML-6.0.1 Pygments-2.15.1 Unidecode-1.3.6 Werkzeug-2.3.6 amqp-5.1.1 asgiref-3.7.2 asttokens-2.2.1 backcall-0.2.0 billiard-4.1.0 certifi-2023.5.7 cffi-1.15.1 chardet-3.0.4 charset-normalizer-3.2.0 click-8.1.6 click-didyoumean-0.3.0 click-plugins-1.1.1 click-repl-0.3.0 colorama-0.4.6 crispy-bootstrap5-0.7 cryptography-41.0.2 cssselect2-0.7.0 decorator-5.1.1 defusedxml-0.7.1 diff-match-patch-20230430 django-admin-honeypot-1.1.0 django-allauth-0.54.0 django-appconf-1.0.5 django-bulk-update-or-create-0.3.0 django-categories-1.9.2 django-ckeditor-6.6.1 django-components-0.35 django-compressor-4.4 django-constance-2.9.1 django-crispy-forms-2.0 django-debug-toolbar-4.1.0 django-decorator-include-3.0 django-etc-1.4.0 django-filer-3.0.4 django-filter-23.2 django-grip-3.4.0 django-hitcount-1.3.5 django-htmx-1.16.0 django-import-export-3.2.0 django-ipware-5.0.0 django-jazzmin-2.6.0 django-js-asset-2.1.0 django-maintenance-mode-0.18.0 django-modeltranslation-0.18.11 django-mptt-0.14.0 django-ninja-0.22.2 django-picklefield-3.1 django-polymorphic-3.1.0 django-qsstats-magic-1.1.0 django-robots-5.0 django-rosetta-0.9.9 django-select2-8.1.2 django-shortcuts-1.6 django-split-settings-1.2.0 django-sql-explorer-3.2.1 django-widget-tweaks-1.4.12 easy-thumbnails-2.8.5 et-xmlfile-1.1.0 executing-1.2.0 gripcontrol-4.2.0 gunicorn-21.2.0 h11-0.9.0 h2-3.2.0 hpack-3.0.0 hstspreload-2023.1.1 html2text-2020.1.16 httpcore-0.9.1 httpx-0.13.3 hyperframe-5.2.0 idna-2.10 install-1.3.5 ipython-8.12.2 jedi-0.18.2 kombu-5.3.1 ldif3-3.1.1 lxml-4.9.3 matplotlib-inline-0.1.6 oauthlib-3.2.2 odfpy-1.4.1 openpyxl-3.1.2 packaging-23.2 parso-0.8.3 pexpect-4.9.0 pickleshare-0.7.5 polib-1.2.0 prompt-toolkit-3.0.39 psycopg2-binary-2.9.9 ptyprocess-0.7.0 pubcontrol-3.5.0 pure-eval-0.2.2 pycparser-2.21 pydantic-1.10.11 python-card-me-0.9.3 python-dateutil-2.8.2 python-dotenv-1.0.1 python-fsutil-0.10.0 python3-openid-3.2.0 pytz-2023.3 rcssmin-1.1.1 reportlab-4.0.4 requests-2.31.0 requests-oauthlib-1.3.1 rfc3986-1.5.0 rjsmin-1.2.1 six-1.16.0 sniffio-1.3.0 sorl-thumbnail-12.9.0 sqlparse-0.4.4 stack-data-0.6.2 svglib-1.5.1 tablib-3.5.0 tinycss2-1.2.1 toposort-1.10 traitlets-5.9.0 typing_extensions-4.7.1 tzdata-2023.3 tzlocal-5.0.1 ua-parser-0.18.0 unicode-slugify-0.1.5 unicodecsv-0.14.1 urllib3-1.26.6 user-agents-2.2.0 vine-5.0.0 wcwidth-0.2.6 webencodings-0.5.1 whitenoise-6.6.0 xlrd-2.0.1 xlwt-1.3.0 I removed as much as possible of non-needed packages but nothing changed, i also … -
How to properly use get_or_create in a django serializer and avoid 'already exists' error?
I have the following django models, serializer and viewset. class Article(AbstractBaseModel): manufacturer = models.ForeignKey( Manufacturer, on_delete=models.CASCADE, null=True, blank=True ) provider1 = models.ForeignKey( Provider, on_delete=models.CASCADE, null=True, blank=True, ) def get_absolute_url(self): return reverse( "smt_management_app:article-detail", kwargs={"name": self.name} ) class Manufacturer(models.Model): name = models.CharField( primary_key=True, max_length=50, null=False, blank=False ) def get_absolute_url(self): return reverse( "smt_management_app:manufacturer-detail", kwargs={"name": self.name} ) class Provider(models.Model): name = models.CharField( primary_key=True, max_length=50, null=False, blank=False ) def get_absolute_url(self): return reverse("smt_management_app:provider-detail", kwargs={"name": self.name}) class ArticleSerializer(serializers.ModelSerializer): manufacturer = ManufacturerSerializer(required=False, allow_null=True) provider1 = ProviderSerializer(required=False, allow_null=True) class Meta: model = Article fields = [ "name", "manufacturer", "provider1", ] def create(self, validated_data): manufacturer_data = validated_data.pop("manufacturer", None) if manufacturer_data: manufacturer, _ = Manufacturer.objects.get_or_create( name=manufacturer_data["name"] ) validated_data["manufacturer"] = manufacturer provider1_data = validated_data.pop("provider1", None) if provider1_data: provider1, _= Provider.objects.get_or_create( name=provider1_data["name"] ) validated_data["provider1"] = provider1 article = Article.objects.create(**validated_data) return article class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer filter_backends = ( django_filters.rest_framework.DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, ) filterset_class = ArticleFilter ordering_fields = "__all__" When posting a new article I encounter an unexpected behavior. The manufacturer and provider in the following example do both exist but only the provider causes an error. POST body: {"name":"article1","manufacturer":{"name":"123"},"provider1":{"name":"abc"}} ERROR body: {"provider1":{"name":["provider with this name already exists."]}} Why does it happen if everything is exactly the same for Manufacturer … -
Problem with redis/celery, why do some tasks triggers an Errno 111 but others don't?
I am currently building a web app with django. I am using redis and celery to send emails for various purposes. I have a background worker checking my db for mails to send every 5s (very short for testing purposes),if it finds mails flagged as unsent, then it sends them, this part works as intended. However when I call the same method directly from one of my views (to send an email for account creation), I have an Errno 111. Here's my celery.py file: import os from celery import Celery from celery.signals import after_setup_logger import logging.config from inscriptionsIff import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inscriptionsIff.settings') app = Celery('inscriptionsIff') app.config_from_object('django.conf:settings', namespace='CELERY') @after_setup_logger.connect def setup_loggers(logger, *args, **kwargs): logging.config.dictConfig(settings.LOGGING) app.conf.beat_schedule = { 'send-emails-every-x-seconds': { 'task': 'inscriptionsIff.tasks.process_and_send_emails', 'schedule': 5, # Replace 'x' with the number of seconds }, } app.autodiscover_tasks() Here's my tasks.py file: from celery import shared_task from django.core.mail import send_mail from .models import Submission from django.urls import reverse from django.contrib.sites.shortcuts import get_current_site import hashlib from django.conf import settings @shared_task def send_email_task(email, subject, message): send_mail( subject, message, 'yourgmailaddress@gmail.com', [email], fail_silently=False, ) def hash_input(input_to_hash): # Use Django's SECRET_KEY to add a layer of unpredictability to the hash salted_id = str(input_to_hash) + settings.SECRET_KEY return hashlib.sha256(salted_id.encode()).hexdigest() @shared_task def process_and_send_emails(): … -
Errors in form with ModelForm
I'm not good in English I want to have a login page, I use ModelForm and LoginView. when I want to see the page I got this error: BaseModelForm.__init__() got an unexpected keyword argument 'request' and when I don't use the Form, always return to the same page. I checked the request.method, it's GET! here is my form: class LoginForm(ModelForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) class Meta: model = User fields = ['username', 'password'] view: class Login(LoginView): form_class = LoginForm template_name = 'account/login.html' def get_success_url(self): return reverse_lazy('account:home') and login.html <form action="{% url 'account:home' %}" method="post"> {% csrf_token %} <div class="input-group mb-3"> <input id="username" type="text" class="form-control" placeholder="Username"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-user"></span> </div> </div> </div> <div class="input-group mb-3"> <input id="password" type="password" class="form-control" placeholder="Password"> <div class="input-group-append"> <div class="input-group-text"> <span class="fas fa-lock"></span> </div> </div> </div> <div class="row"> <!-- /.col --> <div class="col-12"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div> <!-- /.col --> </div> </form> when I use my form(with function view), my browser don't suggest my saved logins. -
How to define extra dynamic field based on Foreign Key model field in django
I am trying to make extra display field in form that used to take value based on changing the related table field. suppose model.py # Create model.py class MyModel(models.Model): name = models.CharField() model2 = models.ForeignKey(MyModel2) class MyModel2(models.Model): name = models.CharField() description = models.CharField() forms.py # Create forms.py class MyForm(forms.ModelForm): extraField = forms.CharField(disabled=True) class Meta: model = MyModel field = '__all__' In this particular extraField. I need to related this field with model2.description value. Is there any way to do this. -
Errno 111 Connection refused: Issue with rendering PDF with xhtml2pdf in Django on a Linux server with static files images
I've successfully deployed my Django project on a Linux server, but I'm encountering an issue when trying to print PDF reports. The images located in the static folder are causing errors during the rendering process. <img class="logo" src="http://{{host}}/static/logo_1.jpeg"> enter image description here It's worth noting that I can access these images through their respective URLs, but I'm getting a connection refused error with xhtml2pdf. I'm curious if there might be some Apache2 configuration settings that I may have overlooked that could be causing this connection issue in the context of xhtml2pdf. Any insights or guidance on potential Apache2 configurations would be greatly appreciated. My goal is to determine if there's any permission or configuration issue with Django URLs that I might have overlooked. What doesn't make much sense to me is that I can view the images through the URL, but they can't be rendered in a PDF. Does this library use a different type of connection when importing images for PDF rendering?