Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Django does not be deployed easily?
I have been learning Django for a long time, and I always find difficulties in deploying my projects, I often deploy my projects on AWS, and it takes a lot of money, also, the other platforms take a lot of fees to make your Django project deployed on their platforms, After that I decided to move to PHP here I found a difference, -and the difference is in the amount of time, that you need to deploy your project (which is a lot shorter than Django), -and the amount of fees that you need to pay to the platform to deploy your project on (it is 100%100 cheaper than Django), -and there are a lot of platforms for PHP, while Django there are few platforms to deploy your project on, -and PHP is much easier to deploy, there are platforms that just you take your project and drag it then drop it to them, and this is everything. my questions are : 1- Why sometimes you have to take a cloud computer service then you have to install python , and everything in python , then you upload the Django project, it is like you are using it on your … -
TinyMCE style working in Django admin, but not working in Angular frontend
I have django backend admin template, with TinyMCE textfield. In the textfield I add inline CSS style to the HTML. It's working correctly. <ol style="color: blue; font-weight: bold;"> <li><span style="color: black; font-weight: normal;">L&aacute;togasson el a szolg&aacute;ltat&oacute; oldal&aacute;ra: </span></li> <li><span style="color: black; font-weight: normal;">Adja meg a regisztr&aacute;ci&oacute;hoz sz&uuml;ks&eacute;ges adatokat (a partnersz&aacute;mot &eacute;s a sz&aacute;ml&aacute;n szereplő nevet kiemelt&uuml;k).</span></li> <li><span style="color: black; font-weight: normal;">Jegyezze fel a regisztr&aacute;ci&oacute; sor&aacute;n megadott e-mail c&iacute;met &eacute;s jelsz&oacute;t (k&eacute;sőbb sz&uuml;ks&eacute;g lesz r&aacute;).</span></li> <li><span style="color: black; font-weight: normal;">Sikeres vagy sikertelen regisztr&aacute;ci&oacute; ut&aacute;n kattintson a Tov&aacute;bb gombra.</span></li> </ol> But on the frontend (with innerHTML), the styling is not working. I get the data correctly from the JSON, but in the html doesnt show the css, just the html. -
Advanced Search feature for E-commerce Website using Django
I am working for a ecommerce platform for which I have to make an advance, fast, error handling Search bar, we have thousands of products, many categories, many variants! I want to build a very fast search bar that have features like: dynamic Auto-suggestion fuzzy word handling suggestions for usage of open source services suggestions on python libraries like whoosh to make it faster applying caching and all, like using Redis and all Handling no product found and all I want help with what i should use what not and also, any models i should update like for user what they have searched in past, should i store that, and all, Please help me, I am asked to research and work on this, but I am confused and reached no where yet!!!!!! -
UnboundLocalErrorat /aauth/request-reset-email/
[enter image description here](https://i.sstatic.net/QsavU8an.png) I an having an [UnboundLocalError at /aauth/request-reset-email/ cannot access local variable 'email_subject' where it is not associated with a value] error. I have been trying to sort this out but all to no avail...have checked all my configurations too. please anyone with similar probblem or solution should help out. Thank! -
Error loading css and js files in django project
here is the github repository: https://github.com/RobertmPevec/business-flow whenever I load the page on my local server I get the following errors: enter image description here If anyone could help I am kinda lost here and am new to programming so any advice to fix this would be helpful, thanks. Went through settings.py and base.html to try to confirm everything was configured properly and fix any mistakes I made although nothing I tried resolved the issue -
Design User class in Django
I use the AbstractUser class to extend my User class. In my User class, there are currently 3 roles: Admin, Lecturer and Alumni. I can use is_superuser, is_staff to solve the problem, however, in the future there may be more roles appearing and if I use the above method it will not be possible to add more roles better. But if I use the additional field role = models.IntegerField(choices=Role.choices, default=Role.ALUMNI) it looks fine. But when using superuser, is_superuser = True and the user's role is Alumni. By the way, I'm working on a project using django, rest_framework. I want Users with the role of Lecturer to be created by the Admin and set a default password, and after 24 hours from the time of account creation, if the Lecturer does not change the password, the account will be locked and the Admin will have to reopen for Lecturer. I wrote two functions save and check_password_expiry but I'm not sure if it works as I want. Can someone solve my current problem, please? class User(AbstractUser): class Role(models.IntegerChoices): ADMIN = 1, "Admin" LECTURER = 2, "Lecturer" ALUMNI = 3, "Alumni" avatar = CloudinaryField(null=True) cover = CloudinaryField(null=True) role = models.IntegerField(choices=Role.choices, default=Role.ALUMNI) alumni = … -
How can we get custom token from dj-rest-auth while authentication?
We are trying to use dj_rest_auth to make social authentication, starting with Google auth, work on a site / app using JWT token pair (access & refresh). Our attempted solution is as follows: Goal: We are modifying the register & login API endpoints provided by dj_rest_auth to return our JWT custom token pair (as returned by the api/token endpoint), instead of the session key. Possible options: Option 1: Extend dj_rest_auth.registration.views.RegisterView with a CustomRegisterView, modifying the perform_create method to return the JWT token pair. Option 2: Let dj_rest_auth.registration.views.RegisterView return the session key & token be in the cookie, but modify the token in the cookie to add the logic in our custom token serializer to add additional fields. The above approaches will apply to Loginview as well. Our questions: Which of the above is better? Our preference is for approach 1 - more consistent with our maintenance & use of tokens before social auth. Is there any concern with the above option 1 - ie having register & login endpoints return the JWT token pair? Assuming Option 1 - what is the best way to do it? We are trying to extend the RegisterView - but it’s unclear which method to … -
Is there a boilerplate template for a TDD approach in Django-Python
I’m working on a side a project while trying to discipline myself to get accustomed to the TDD approach in Django. I'm not sure why I’m running into this failed test (venv) osahenru@osahenru ~/D/q-4> pytest -k test_can_post_questions ============================= test session starts ============================== platform linux -- Python 3.10.12, pytest-8.1.1, pluggy-1.5.0 django: version: 5.0.4, settings: config.settings (from ini) rootdir: /home/osahenru/Documents/q-4 configfile: pytest.ini plugins: django-4.8.0 collected 5 items / 4 deselected / 1 selected app/tests/test_views.py F [100%] =================================== FAILURES =================================== ______________________ TestEvent.test_can_post_questions _______________________ self = <test_views.TestEvent testMethod=test_can_post_questions> def test_can_post_questions(self): event = Event.objects.create(name='Python Ghana') data = { 'text': 'how are you?', } response = self.client.post(reverse('questions', kwargs={'pk': event.id}), data) > self.assertIsInstance(response.context['form'], QuestionCreateForm) E TypeError: 'NoneType' object is not subscriptable app/tests/test_views.py:52: TypeError =========================== short test summary info ============================ FAILED app/tests/test_views.py::TestEvent::test_can_post_questions - TypeError: 'NoneType' object is not subscriptable ======================= 1 failed, 4 deselected in 0.53s ======================== (venv) osahenru@osahenru ~/D/q-4 [0|1]> here is the test causing the error message def test_can_post_questions(self): event = Event.objects.create(name='Python Ghana') data = { 'text': 'how are you?', } response = self.client.post(reverse('questions', kwargs={'pk': event.id}), data) self.assertIsInstance(response.context['form'], QuestionCreateForm) self.assertEqual(response.status_code, 302) and here is the view function def questions(request, pk): event = Event.objects.get(id=pk) questions = Question.objects.filter(event=event) form = QuestionCreateForm() if request.method == 'POST': form = QuestionCreateForm(request.POST) … -
Why does Sentry catch my local host errors but not my errors for my prod url in Django?
I have this in my settings. I have my debug to False, did I miss something. I never messed with anything in my app urls.py. sentry_sdk.init( dsn="***", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. traces_sample_rate=1.0, # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. profiles_sample_rate=1.0, ) -
Flask as a back-end web programming framework
I'm currently working on a simple project that I wanted it to be my introduction to python web programming. I've wrote a python code of what I needed and I'm working on the interface that I wanted to be a web based one. I choose to work with flask. I wanted to know whether I have to modify the code to be suitable with the framework? and how to manipulate the database since I was working with csv files in my initial code? So basically the code consists of different search algorithms in artificial intelligence (BFS, DFS, A* and hill climbing) that return a path in a map. I wanted to used html, css, js and flask to implement an interface that gives the user option to choose starting and goal states and represent that resulting path in a map. -
Adding the django-parler to admin page in Django admin
I'm working on my Django project and I added django-parler to my Django project. I have added parler in my models.py and that looks like this: class Category(TranslatableModel): translations = TranslatedFields( category_name=models.CharField(max_length=255, verbose_name="Category name"), ) parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(max_length=200, unique=True, editable=False, default='') def clean(self): if self.parent: if self.parent.parent: raise ValidationError("A category that already has a parent cannot be set as the parent of another category.") def save(self, *args, **kwargs): if not self.slug: base_slug = slugify(self.safe_translation_getter('category_name', self.category_name)) # Ensure uniqueness of the slug slug = base_slug counter = 1 while Category.objects.filter(slug=slug).exists(): slug = f"{base_slug}-{counter}" counter += 1 self.slug = slug super(Category, self).save(*args, **kwargs) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['category_name'] def __str__(self): return self.safe_translation_getter('category_name', self.category_name) Tricky part is that I want slug to be translated not just category name. Also, in admin.py I did it like this: admin.site.register(Category, TranslatableAdmin) And I got it like on images below. I'm happy with the result. What you see on first image, is when you click on categories on admin side, and if I have multiple translations it makes entry for every language. On second image you see how it looks like when you are adding … -
How to Prefetch a group concat field in Django
my question is the following : I have a view table mapped to the Django ORM, with a group_concat field using MariaDB. Is it possible to fetch IDs from this: This view stores data for operators, and each operator can be associated with multiple companies Class OperatorsView(models.Model): id = models.IntegerField(primary_key=True, db_index=True) # fleet_operator_id fleet_operator = models.ForeignKey( "companies.FleetOperator", on_delete=models.DO_NOTHING, null=True ) user = models.ForeignKey( "accounts.MobileUser", on_delete=models.DO_NOTHING, null=True ) operator = models.ForeignKey( "companies.Operator", on_delete=models.DO_NOTHING, null=True ) companies_shared_str = models.CharField( db_column="companies_shared_id", null=True, max_length=4000 ) So I would like to know if the companies_shared_str field is possible to be used in OperatorsView to prefetch in advance, not using a @property because this will lead to N + 1 queries. Any suggestions would be greatly appreciated -
Docker image is not updating on Azure container registry via gitlab
I am having an issue with my docker images which are uploaded on the Azure container registry via gitlab, but they seem not to be updating the current code, but locally they work. What could be a problem to my .gitlab-ci.yml file ? image: name: docker/compose:1.25.4 entrypoint: [""] services: - docker:dind variables: DOCKER_HOST: tcp://docker:2375 DOCKER_DRIVER: overlay2 stages: - develop build-dev: stage: develop before_script: - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME - apk add --no-cache --upgrade bash script: - apk add --no-cache bash - chmod +x ./setup_env.sh - bash ./setup_env.sh - docker login $AZ_REGISTRY_IMAGE -u $AZ_USERNAME_REGISTRY -p $AZ_PASSWORD_REGISTRY - docker pull $AZ_REGISTRY_IMAGE/proj:tag || true - docker-compose build --no-cache - docker tag $AZ_REGISTRY_IMAGE/proj:tag $AZ_REGISTRY_IMAGE/pixsar:$(date +%Y%m%d%H%M) - docker push $AZ_REGISTRY_IMAGE/proj:$(date +%Y%m%d%H%M) - docker system prune -af only: - develop - fix-docker-1 -
I have a problem with send email by django
I have a problem with send_email by django I tryed gmail and hotmail and email private , all of them return the same error code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.privateemail.com' EMAIL_HOST_USER = 'info@bajco-sa.com' EMAIL_HOST_PASSWORD = 'admeralGXG1986' EMAIL_USE_TLS = False EMAIL_PORT = 465 Error console: ` File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 398, in getreply line = self.file.readline(_MAXLINE + 1) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/socket.py", line 707, in readinto return self._sock.recv_into(b) ^^^^^^^^^^^^^^^^^^^^^^^ ConnectionResetError: [Errno 54] Connection reset by peer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/handlers/exception.py", line 56, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/blog/views.py", line 64, in post_share send_mail(subject, message, 'gxgxxxx@gmail.com', [cd['to']]) File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/init.py", line 87, in send_mail return mail.send() ^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/backends/smtp.py", line 124, in send_messages new_conn_created = self.open() ^^^^^^^^^^^ File "/Volumes/mac-etended/pytonDjango/django-example-4/blog/venv/lib/python3.12/site-packages/django/core/mail/backends/smtp.py", line 80, in open self.connection = self.connection_class( ^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 255, in init (code, msg) = self.connect(host, port) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 343, in connect (code, msg) = self.getreply() ^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/smtplib.py", line 401, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed: " smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [Errno 54] Connection reset … -
forbidden (403) CSRF was not verified. The request was cancelled
I am logogin with super admin in django project and want to change some properties of users but when i clicked at save button it shows an error as below: forbidden (403) CSRF was not verified. The request was cancelled. Help Reason given for failure: Origin checking failed - https://somedomain.com does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because the token is rotated after a login. You’re seeing the help section of this page … -
'Failed to establish a new connection: [Errno 111] Connection refused'
I am trying to run a django application with a postgres db on docker-compose. I can run it perfectly but as soon as I do a post request, I get this error: FAILED tests/test_email.py::TestUser::test_list_to - requests.exceptions.ConnectionError: HTTPConnectionPool(host='172.17.0.1', port=8080): Max retries exceeded with url: /api/v1/customers/516c7146-afc0-463b-be0e-7df01e8a86f6/emails (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7ff6544eada0>: Failed to establish a new connection: [Errno 111] Connection refused')) This is my docker-compose file: version: "3" services: db: image: postgres:latest restart: always environment: POSTGRES_PASSWORD: verySecretPassword POSTGRES_USER: administrator POSTGRES_DB: project volumes: - ./data/db:/var/lib/postgresql/data web: build: . restart: always ports: - "8080:8080" depends_on: - db environment: DATABASE_URL: postgresql://administrator:verySecretPassword@db:5432/project volumes: - .:/app this is my Dockerfile: # Use the official Python image as a base image FROM python:3.10 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set the working directory WORKDIR /app # Install Django and Django REST Framework RUN pip install --no-cache-dir django djangorestframework # Install system dependencies for psycopg2 (PostgreSQL client) RUN apt-get update && \ apt-get install -y postgresql-client # Copy the requirements file and install dependencies COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt # Copy the Django project files to the container COPY . /app/ # Install system dependencies for psycopg2 (if necessary) … -
401 (Unauthorized) between my API Django_Rest_Framework and React.js
I have created API with django_rest_framework and I manage user autorisation with jwt_token, I use react.js app for my frontend. In development all request are working, but in production, all my request are coming back with 401 (Unauthorized), except sometimes when I refresh my page many times I can have an ok response. I have two differences between development and production. firstly in development I use sqlite while in production I use postgreSQL. Moreover, in production I have configured my django settings like this : SECURE_HSTS_SECONDS = 31536000 SECURE_CONTENT_TYPE_NOSNIFF = True X_FRAME_OPTIONS = 'DENY' SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_PRELOAD = True SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_NAME = 'sessionid' SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = 3600 # Durée de vie du cookie de session : 1 heure SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRATION_DATE = datetime.now() + timedelta(days=30) With my react.js app I can see my token refresh and my token access and they are correctly refreshed. Also, my database work good because I can register new user. I have read a lot of error file like gunicorn, nginx or my django app but I don't really know what happened. Also, I have problem with my admin api, … -
Django static files 404 errors just for one folder and all images
I'm integrating a theme into my project. Some of the static files are found, but I get two types 404 errors. I'd appreciate any help. The first type (all images): For the line <img class="rounded-circle" src="{% static 'sleek-bootstrap/source/assets/img/user/u6.jpg" alt="Image' %}"> I get the error "GET /static/sleek-bootstrap/source/assets/img/user/u6.jpg%22%20alt%3D%22Image 404 1958 The file /static/sleek-bootstrap/source/assets/img/user/u6.jpg does exist, but somehow Django adds %22%20alt%3D%22Image to the name, so of course it can't find it. It does this for all the image files in the template The second type (one folder): for the line <script src="{% static 'sleek-bootstrap/source/assets/plugins/daterangepicker/moment.min.js' %}"> ></script> I get the error "GET /static/sleek-bootstrap/source/assets/plugins/daterangepicker/moment.min.js HTTP/1.1" HTTP/1.1" 404 1958 Django finds all the files in the path /static/sleek-bootstrap/source/assets/plugins/, except those in the daterangepicker plugin folder. -
Practices for Using Virtual Environments in Python Development
Could someone please explain the following: What are some best practices for using virtual environments effectively in Python projects? Are there any common pitfalls or misconceptions to watch out for when working with virtual environments? Does python devlopers use virtual environment in their works ? And how does this help them? -
how to check that the bot is running in telethon
i tried Redis before it, still not working i want to get informations from bot and send them to web page. i want check the bot its running or not, checking that in another file. this is my simple code, help me to complete it from telethon.sync import TelegramClient, events import cfg api_id = cfg.API_ID api_hash = cfg.API_HASH bot = TelegramClient('bot', api_id, api_hash) bot.start() @bot.on(events.NewMessage) async def my_event_handler(event): if 'hello' in event.raw_text: await event.reply('hi!') bot.run_until_disconnected() -
Django crispy-form, data from the form is not saved in the database
I'm just starting my adventure with Django. I wrote a small application in which, of course, there is a form that collects data from the user. This form in the standard version of Django doesn't look nice. I found information about crispy-form on the Internet and added it to my project. I managed to create a form that I like, but there is a problem. I cannot save the data retrieved from the form to the database. Previously, when I had a Django form, in the views.py file, the function handling this form saved the retrieved data to the database. Now that it's crispy-form I don't want to save. My knowledge is too little to be able to do it, hence my request to you for help. Can you take a look at the codes below and tell me what I'm doing wrong? forms.py from django.forms import ModelForm from crispy_forms.helper import FormHelper from .models import Firma, DaneKsiegowe from django import forms from django.urls import reverse from crispy_forms.bootstrap import Field, TabHolder, Tab from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset class FormNowaFirma(forms.Form): nazwa = forms.CharField(required=True, max_length=120) typ_ksiegowosc = forms.ChoiceField( choices=(("ryczałt ewidencjonowany","ryczałt ewidencjonowany"),("ryczałt ewidencjonowany bez VAT","ryczałt ewidencjonowany bez VAT"), ("KPiR … -
RoutablePageMixin working locally but not on Heroku
I'm in the process of gradually upgrading an old Wagtail CMS website. I've just upgraded from Wagtail V2.13.5 to 2.15.6, including upgrading from Django 3.1 to 3.2, and Python from 3.8 to 3.10. The website is working 100% fine on my local dev copy (Win10), and 95% fine on my Heroku staging environment. However, the parts of the site that uses RoutablePageMixin are not working on my Heroku staging environment (Heroku-22 stack). The website is a fairly basic blog, with an index page ('/explore/') below the homepage, and I'm using RoutablePageMixin to create a 'latest' page ('/explore/latest/') to display the 5 most recent posts below that. This '/explore/' and '/explore/latest/' pages work fine locally, but on my Heroku staging environment '/explore/' is fine but '/explore/latest/' just displays a 404 error ('rasied by wagtail.core.views.serve)'. There's nothing in the Heroku logs to explain why this is, it's just not recognising the @route(r'^latest/$') at all. from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.db import models from django.shortcuts import render, redirect from modelcluster.fields import ParentalKey, ParentalManyToManyField from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.api import APIField from wagtail.core.models import Page, Orderable from wagtail.contrib.routable_page.models import RoutablePageMixin, route # Location Index Page class LocationIndexPage(RoutablePageMixin,Page): … -
How to have multiple versions of website (with different type of content)?
I need a little bit of help. I'm working on a Django project, it's like a blog. I have implemented localization and added couple languages. Now I would like to develop a customized content for specific regions. Current set up it like this: http://127.0.0.1:8000/en/ I have one content and 3 languages: content - en (English) - http://127.0.0.1:8000/en/ - de (German) - http://127.0.0.1:8000/de/ - ar (Arabic) - http://127.0.0.1:8000/ar/ I used django-parler so every article can be provided in all 3 languages. Now I'd like to have more content - let's say content specific to specific region, it would look like this: Global content - en (English) - http://127.0.0.1:8000/en/glo/ (content on English for global readers) - de (German) - http://127.0.0.1:8000/de/glo/ (content German for global readers) - ar (Arabic) - http://127.0.0.1:8000/ar/glo/ (content on Arabic for global readers) German content - en (English) - http://127.0.0.1:8000/en/de/ (content on English for German region) - de (German) - http://127.0.0.1:8000/de/de/ (content German for German region) - ar (Arabic) - http://127.0.0.1:8000/ar/de/ (content on Arabic for German region) Middle East content - en (English) - http://127.0.0.1:8000/en/me/ (content on English for Middle East readers) - de (German) - http://127.0.0.1:8000/de/me/ (content German for Middle East readers) - ar (Arabic) - http://127.0.0.1:8000/ar/me/ (content … -
How to override the internal read query of class or method in django
I wan't to override the internal read query present inside my class or method. I wan't to write generalised solution so that it should work on the class or method where I wan't to modify the read queries. I am trying to do using decorators, middleware and metaclasses but I am unable to access the internal read query of function. I just wan't to modify it to take it from read replica. but I can't do this to all read query. I can only modify read query to take it from read replica for few class or method. master_models.CarTransmission.objects.filter( # pylint: disable=E1101 variant_id__in=self.variant_ids ).values_list(*self.specifications, named=True) modify this to- master_models.CarTransmission.objects.using('replica').filter( # pylint: disable=E1101 variant_id__in=self.variant_ids ).values_list(*self.specifications, named=True) original- model = get_object_or_404(master_models.Model,slug=slug) modify this to - model = get_object_or_404(master_models.Model.objects.using('replica'),slug=slug) The logic that I am expecting should be specific to class and method. I f i apply that on class all the method present should modify all the internal read query. Is it possible or I should go to all query and write .using('replica') pleaser don't provide solution which work for some specific app like using routing to move it to redirect to replica as they will be going to work on whole project … -
AssertionError when the serializer does not find an object in Django Login
I'm creating an app in django with custom registration and login that behave like forms, but when I log in with wrong credentials, the program returns an AssertionError. . views.py ... def post(self, request): serializer = LoginSerializer(data=request.data) if serializer.is_valid(): email = serializer.validated_data['email'] password = serializer.validated_data['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect('/') else: return Response({'erro': 'user nao encontrado'}) serializers.py class LoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(required=True) password = serializers.CharField(write_only=True, style={'input_type': 'password'}) class Meta: model = Profile fields = ['email', 'password'] def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') if email and password: user = authenticate(email=email, password=password) if not user: raise serializers.ValidationError('O usuário não existe') attrs['user'] = user return attrs I've already tried a try and except, as well as adding a Response if the user doesn't exist, but still, nothing works.