Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python django broken pipe from 127.0.0.1 (cmd) [duplicate]
iI am currently following the Django website tutorial, but I keep encountering 'broken pipe from 127.0.0.1' errors, and I'm unsure why. Whenever this occurs, my website stops functioning. You can view the logs here. I've noticed that this issue is quite common, especially when I attempt to use the admin panel. I'm not sure why this is happening. -
Mocking does not work as expected (Django)
I have this code: // app1.service.py database = { 1: "Alice", 2: "Bob", 3: "Charlie" } def get_user_from_db(user_id): return database.get(user_id) // app1.tests.test_service.py import pytest from unittest import mock from app1.service import get_user_from_db @mock.patch("app1.service.get_user_from_db") def test_get_user_from_db(mock_get_user_from_db): mock_get_user_from_db.return_value = "Mocked Alice" username = get_user_from_db(1) # If I change it to mock_get_user_from_db(1) everything works fine assert username == "Mocked Alice" When i run 'pytest' in the command line, I get this: E AssertionError: assert 'Alice' == 'Mocked Alice' E - Mocked Alice E + Alice In the tutorial I am watching, get_user_from_db(1) returns "Mocked Alice", but in my local machine it returns just "Alice". It works fine when I use username = mock_get_user_from_db(1) instead of the username = get_user_from_db(1) Question: It this the expected behaviour that username = get_user_from*db(1) returns "Alice" in my case? (in the youtube video it returns "Mocked Alice") or am I just doing something wrong? -
In django rest famework serializer, how to change unique validator queryset dynamically
I'm using multiple databases. And every database has the same models. for example there is a concrete model A class AModel(models.Model): name = models.CharField("A name", max_length=10, unique=True) and a drf ModelSerializer class AModelSerializer(serilaizers.ModelSerializer): class Meta: model = AModel # from above fields = ['name'] And a proxy model which has a custom manager which uses a specific database class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().using("test") class ProxyModel(AModel): objects = CustomManager() class Meta: proxy = True and even if I dynamically change ModelSerializer's Meta.model to ProxyModel in init, name field's UniqueValidator queryset still refers to A.objects.all() not A.objects.using('test') What I figured out is ModelSerializer only refers concrete model fields, the model it is defined and their model's default manager, which in turn AModel.name, AModel and AModel's default manager in this case. Actually I solved it before using defining concrete models from an abstract model for each databases. and then set ModelSerializer model to abstract class, and then change ModelSerializer's Meta.model to a concrete model. So as I told it refers correct concrete model. but it seems error prone cause some of the code should be hard coded. and I hope to solve this problem more generically. Give me any idea. and if … -
Django Performance improvisation with async views
I am relatively new to django! In my django project i had lot of views and every view had database I/O operation and also had chat application in the same project using django channels (it don't had any database I/O). Now i am using wsgi application with gunicorn and only django channels part( web socket requests) with asgi using daphne. I referred lot of documentations and I realized that Database I/O operations should be performed in async for effective utilization of resources and django had added async support recently. So should I change all the views to async views, remove gunicorn and use only asgi server like daphne or uvicorn for the complete project? I don't have any idea about async implementation for ORM and views, If this sync to async migration make a lot of difference then i will learn and migrate, if not then i will leave as it is, So can someone please suggest me what shall i do now? -
I have an error when migrating manager.py on Hostmidia
File "/home/interlog/virtualenv/sistema_interlogrs/3.9/lib/python3.9/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) File "/home/interlog/virtualenv/sistema_interlogrs/3.9/lib64/python3.9/site-packages/psycopg2/init.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server at "localhost" (::1), port 5432 failed: FATAL: no pg_hba.conf entry for host "::1", user "interlog_user", database "interlog_site", SSL off -
How to handle authentication with Telegram Bot in Django-rest-framework
I've reviewed all related questions, but I'm currently facing a problem for which I'm uncertain about the best approach. I have a web application built with Django and django-allauth. Telegram Bot login has been successfully implemented, and everything is functioning well. In addition, I have a Django Rest API within the same project. Here are my Authentication Backends: AUTHENTICATION_BACKENDS = ( 'registration.authenticate_backend.EmailOrUsernameModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', "rest_framework_simplejwt.authentication.JWTAuthentication",]} What I aim to achieve is as follows: Users join my TelegramBot, and through it, they should be able to manage their accounts and retrieve information via my Django Rest API. However, I'm unsure about how to handle authentication for these requests. Currently, I've implemented a solution by extracting the user_id from the messages that Telegram sends to me and directly using Django ORM. Nonetheless, I would prefer to leverage my API for this purpose. Thank you! -
I want to validate my Google Map Address Before submission in Django
I have a JavaScript code that autoload the address in my HTML and everything is working fine but whenever the person type the address which is not in google API my application shows error because it was able to calculate the distance I set. $(document).ready(function () { google.maps.event.addDomListener(window, 'load', initialize); }); // This example displays an address form, using the autocomplete feature // of the Google Places API to help users fill in the information. var placeSearch, autocomplete; var componentForm = { street_number: 'short_name', route: 'long_name', locality: 'long_name', administrative_area_level_1: 'short_name', country: 'long_name', postal_code: 'short_name' }; function initAutocomplete() { // Create the autocomplete object, restricting the search to geographical // location types. autocomplete = new google.maps.places.Autocomplete( /** @type {!HTMLInputElement} */ (document.getElementById('id_shipping_address'))); // When the user selects an address from the dropdown, populate the address // fields in the form. autocomplete.addListener('place_changed', function() { fillInAddress(autocomplete, ""); }); } function fillInAddress(autocomplete, unique) { // Get the place details from the autocomplete object. var place = autocomplete.getPlace(); for (var component in componentForm) { if (!!document.getElementById(component + unique)) { document.getElementById(component + unique).value = ''; document.getElementById(component + unique).disabled = false; } } // Get each component of the address from the place details // and fill the … -
django form.modelchoicefield get selected value
How to display the "PS1 Failure" instead of value "4" in html template ? with below code form: class FailureCodeForm(forms.ModelForm): failure_name = forms.ModelChoiceField(queryset=FailureCodeModel.objects.all().order_by('failure_name'), label='Failure Code') class Meta: model = FailureCodeModel fields = ['failure_name'] view: if request.method == 'POST': TarFormField1 = FailureCodeForm(request.POST) if TarFormField1.is_valid(): FailureCode = TarFormField1.cleaned_data['failure_name'] template: {{ TarFormField1.failure_name.label_tag }} : {{ failure_name.value }} output: Failure Code: 4 -----> how to output the selected "PS1 failure" and not the value? printed html code: --------- No Boot PS1 Failure PrbsTest TrafficTest -
Table artifacts from django forms.Charfield
I'm using a CharField in a forms.Form subclass: search_term = forms.CharField(widget=forms.CharField()) It seems to render and work fine but I see table artifacts <tr>,<th>,<td> in the resulting html: <form method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="xxxx"> <tr> <th><label for="id_search_term">Search term:</label></th> <td> <input type="text" name="search_term" value="" required id="id_search_term"> </td> </tr> I'm hoping to clean the html up a bit. All ideas welcome! -
How to connect my mysql and mongoDB database in my django using web-scraping to populate my databases as a part of my backend?
Background: I'm working on a Django project where I need to populate my database with information about clubs, such as names, addresses, and contact information. The database models are already set up in Django. Models: I have models for City, Club, Event, UserProfile, Review, and Booking. The Club model includes fields for city (ForeignKey), name, address, contact info, and type. Objective: I want to scrape club data from a website (e.g., Goya Social Club) and populate my MySQL database using Django's ORM. Problem: I'm unsure how to effectively scrape the required data and map it to my Django models. I need advice on parsing HTML content and inserting the data into MySQL. -
Can't connect my django backend with Postgrsql
In my dockerized project, I'm trying to connect my Django app with Postgresql but it keeps giving me this error: File "/home/cr_user/.local/lib/python3.9/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution My compose.yml version: '3.9' services: db: container_name: db image: postgres:13 ports: - '5432:5432' env_file: - ./server/.env volumes: - dbdata:/var/lib/postgresql/data/ networks: - cr_nginx_network cr_api: container_name: cr_api build: context: ./server dockerfile: Dockerfile command: python manage.py runserver 0.0.0.0:5000 ports: - "5000:5000" volumes: - ./server:/cr_server depends_on: - db volumes: dbdata: pgadmin_data: networks: cr_nginx_network: driver: bridge My settings.py DEBUG = True ALLOWED_HOSTS = ["*"] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("POSTGRES_NAME"), 'USER': os.environ.get("POSTGRES_USER"), 'PASSWORD': os.environ.get("POSTGRES_PASSWORD"), 'HOST': 'db', 'PORT': 5432 } } The postgres container is running without a problem but I can't see causing the issue. -
NoReverseMatch: Reverse for '<data>' with arguments <args> not found. 1 pattern(s) tried
Extremely new Django learner here. I am working on a personal project and got this error. views.py def download_video(request): ... return redirect(reverse('download_status', args=[True, None, str(name)])) def download_status(request, download_success, download_error=None, video_id=None): ... context = { 'download_success': download_success, 'download_error': download_error, 'new_filename': video_id, 'entries_page': paginated_subs, 'video_id': video_id } return render(request, 'download_status.html', context) Basically, it is a request from download_video method to redirect to another page that will display the subs list in a paginated manner. urls.py urlpatterns = [ path('download/', views.download_video, name='download_video'), path('data/<video_id>/', views.download_status, name='download_status'), ] download_status.html {% load static %} <!-- displayer.html --> ... pagination support code ... I have tried the pagination code and it works, but for the current organization of code, it is giving me this error: ERROR:django.request:Internal Server Error: /video_downloader/download/ Traceback (most recent call last): File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Academics\video_downloader\views.py", line 105, in download_video return redirect(reverse('download_status', args=[True, None, str(name)])) File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\base.py", line 88, in reverse return resolver._reverse_with_prefix(view, prefix, *args, **kwargs) File "C:\Users\leofi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 828, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'download_status' with arguments '(True, None, '480OGItLZNo')' not found. 1 pattern(s) tried: ['video_downloader/data/(?P<video_id>[^/]+)/\\Z'] I have tried looking at the docs and … -
How to solve this blog problems?
I made this blog which has some major problems I list them down below I appreciate it if you'd help me with either one you know the solution for if I need to add any other codes please let me know 1- when I login as different users and write a post it always mentions only one of my accounts as the author it doesn't write the current user's username as the author and I can see and delete all the other users posts when I login only one of the accounts 2-when I write a post the spaces between the lines and all that is correct but when I post it it all just displays beneath each other with no space 3- I cannot make this footer stretch to the width of the webpage and when I include it in my base.html it changes the styling of the other parts I think due to its CSS 4- when I go to my detail page the buttons on the navbar stretch down base.html {% load static %} <!DOCTYPE html> <html> <head> <title> {% block title %}{% endblock %} </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> … -
how to use google identity services with django-react
ive really read a hundreds outdated questions and blog posts but still cant seem to find a way. i tried using django-social-auth, django-all-auth and so much tutorials. on react im using https://www.npmjs.com/package/@react-oauth/google and i still dont understand alot of things: like does oauth2 work with the jwt token sent from google and from react. how am i supposed to get the data of a jwt token if it was signed by a google secret key that i dont know (or perhaps its the client secret?) and how am i supposed to have a password for user using a user model, unless a 3rd party packages helps with that -
"First question displaying twice consecutively in a Django form; subsequent questions work as expected"
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Personality Test</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> {% load static %} <style> html { height: 100%; background-image: url('{% static questions.0.background_image_path %}'); /* Use the background image of the first question or adjust as needed */ background-size: cover; background-position: center; background-repeat: no-repeat; } .question label { font-family: '楷体', 'Microsoft YaHei', Arial, sans-serif !important; margin-top: 10px; display: block; background-color: #403f3f; /* Dark grey background color for options */ border-radius: 8px; padding: 10px; cursor: pointer; color: #fff; /* Text color for options */ } body { margin: 0; padding: 0; font-family: Arial, sans-serif; } .question-container { /* Remove background color */ padding: 40px; border-radius: 10px; margin: px; display: flex; flex-direction: column; align-items: center; } .question { margin-bottom: 40px; display: none; text-align: center; position: relative; background-image: url('{{ question.background_image_path }}'); background-size: cover; background-position: center; background-repeat: no-repeat; } .text-box { margin-bottom: 10px; background-color: white; border-radius: 8px; padding: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); /* Optional: Add a subtle shadow */ } .tick-mark { opacity: 0; visibility: hidden; transition: opacity 0.5s ease-in-out; } img { max-width: 80%; /* Ensure images don't exceed their container width */ height: auto; /* Maintain image aspect ratio */ border-radius: 8px; … -
The value disappears but still save in database
I have a registration form for a Python/Django project that uses Vue.js. I save the form correctly, but when trying to edit, I can see that the value is loaded properly, but it disappears very quickly, as if Vue.js/JavaScript is erasing it. When inspecting the field, I can see that its value receives the correct value from the registration, but the field becomes blank. <script> function capitalizeWords(string) { if (!string) return string; const words = string.split(' '); const capitalizedWords = words.map((word) => { if (word.length > 1) { return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); } else { return word.toUpperCase(); } }); return capitalizedWords.join(' '); } var app = new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { street: '', district: '', city: '', state: '', country: '', cnpj: '', name: '', trade_name: '', cnae: '', opening_date: '', selectedBank: '', bank: '', bank_code: '', nameInBankAccount: '', cnpjInBankAccount: '', postal_code: '', isLoading: false, isPostalCodeFound: true, isCNPJFound: true, display_form_address: false, display_form_bank: false, hasError: '{{ error }}' }, beforeMount: function () { this.street = this.$el.querySelector('#id_address-0-street').value this.district = this.$el.querySelector('#id_address-0-district').value this.city = this.$el.querySelector('#id_address-0-city').value this.state = this.$el.querySelector('#id_address-0-state').value this.country = this.$el.querySelector('#id_address-0-country').value this.cnpj = this.$el.querySelector('#id_company-cnpj').value this.name = this.$el.querySelector('#id_company-name').value this.trade_name = this.$el.querySelector('#id_company-trade_name').value this.cnae = this.$el.querySelector('#id_company-cnae').value this.opening_date = this.$el.querySelector('#id_company-opening_date').value this.getError(); }, watch: { … -
How can I add entries to my Model in Django, that are linked to a user using Firebase?
I am using React with FireBase to create users account on my Frontend. I am creating a table to track a users weight and it appears like this, from django.db import models from django.utils.translation import gettext_lazy as _ class Units(models.TextChoices): KILOGRAM = 'kg', _('Kilogram') POUND = 'lbs', _('Pound') class WeightTracking(models.Model): date = models.DateField() weight = models.IntegerField() units = models.CharField(choices=Units.choices, max_length=3) def _str_(self): return f'On {self.date}, you weighed {self.weight}{self.units}' The problem is, I have no idea how to track this to a user that is logged in. How can I add an entry that is linked to a user. FireBase gives me a UID for the user which I can send to the django backend, but doesn't Django have a default id column? How can I customize it or what is the best approach to linking an entry to a user for my future queries. Thanks! -
Django server does not accept cookies
When I try to send a POST request to the DJANGO app hosted on the server, with included credentials in the Axios request or with a Postman app, I cannot access cookies in the app, because cookies are never sent. Axios config looks like this: export function genericApiHost(host: string) { const headers = { "Content-Type": "application/json", Accept: "application/json", // "Access-Control-Allow-Origin": true, }; return axios.create({ baseURL: `${host}`, headers: headers, withCredentials: true, }); } If I include the allow origin header I get a CORS error, otherwise, cookies are not sent. This is part of the Django app settings: CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False CSRF_TRUSTED_ORIGINS = ['*'] ALLOWED_HOSTS = ["*"] With the settings I listed here, the application works correctly locally, but when the code is uploaded to the nginx server, it doesn't work -
Django - How to solve error "SIGPIPE: writing to closed pipe/socket/fd"
My web app sends out an email to users utilizing a standard format per django.core.mail.message.EmailMessage. It is received fine by most ISPs and browsers---but with one ISP, the emails are not being received by the users and these 2 related error messages are appearing on the PythonAnywhere server that I use: SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request [a specific URL in your web app] uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during [a specific URL in your web app] My research suggests it could be a server time-out issue related to nginx and uwsgi--but I don't think I have either installed; this is a wsgi application. My gut suggests it could be this specific ISP blocking my emails because I've been testing so much and it considers them spam. Is that plausible? Any thoughts on the likely cause of these errors or how I could resolve? -
Django primary key AutoField does not update when creating an object with explicit id
Suppose I have a model A in Django that uses the default primary key AutoField. Due to a transition process, I have created some objects of A with an explicit id, using A.objects.create(id=legacy_id). Coincidentally, these legacy ids start from 1. Then, when trying to create new objects without setting an explicit id, Django gives the error django.db.utils.IntegrityError: duplicate key value violates unique constraint "topics_reply_pkey" . It seems it is trying to create the object from id=1. If I added 20 objects with ids from 1 to 20, I expect that when using A.objects.create without an explicit pk, it would create the object with id 21. Why is this problem happening, and how can I solve it? -
Using DRF and django-tenants together in the same project
I'm currently building a multi tenancy app with django-tenants. However I also want to run my REST API in the same project as django-tenants. This is where the problem arises, if I were to make my API a shared tenants app every tenant subdomain ends up having their own API. For example, all registered tenants adopt the API routes as part of their subdomain: tenant1.example.com/api, tenant2.example.com/api, etc. I don't want my API to be underneath each tenant, I want to just run it on one domain, preferably api.example.com Does anyone have any advice on how to set this up? How are other people handling this in their projects? -
ManyToOne dropdown in Django admin inline
I have a Django project for keeping track of computers and parts. I have several different models set up for various types of parts, and they have a foreign key pointing to a model for a built computer. As it stands I can only assign a computer to a part, but I would like to do the opposite. Given something like the following: models.py class Computer(models.Model): pass class PartType1(models.Model): name = models.CharField(max_length=200) installed_in = models.ForeignKey(Computer, on_delete=models.SET_NULL, null=True) class PartType2(models.Model): name = models.CharField(max_length=200) installed_in = models.ForeignKey(Computer, on_delete=models.SET_NULL, null=True) I created some inlines hoping that would work: admin.py class PartType1Inline(admin.StackedInline): model = PartType1 class PartType2Inline(admin.StackedInline): model = PartType2 @admin.register(Computer) class ComputerAdmin(admin.ModelAdmin): inlines = (PartType1Inline, PartType2Inline, ) But this only allows me to create new parts from the Computer page. Because a computer can have an arbitrary number of a specific type of part (RAM modules as an example) I can't add the foreign keys to the Computer class. I've tried using OneToOne fields on the Computer class, but that requires adding a bunch of fields that usually end up going unused, and is not as flexible. What I would really like is a simple dropdown allowing me choose existing objects from PartType1, … -
dj-rest-auth verification email give me wrong url
I implemented the email authentication function using dj rest auth, but it worked fine locally, but when I deployed it, the authentication email URL came out strangely. I registered my backend domain in admin's site>site. this is my settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = "587" EMAIL_HOST_USER = "my_email@gmail.com" EMAIL_HOST_PASSWORD = "app_password" EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER STATIC_URL = "/static/" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = ( "/" ) ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_SUBJECT_PREFIX = "WowYouToo" and this is my accounts/views.py class ConfirmEmailView(APIView): permission_classes = [AllowAny] def get(self, *args, **kwargs): self.object = confirmation = self.get_object() confirmation.confirm(self.request) return HttpResponseRedirect("accounts/") def get_object(self, queryset=None): key = self.kwargs["key"] email_confirmation = EmailConfirmationHMAC.from_key(key) if not email_confirmation: if queryset is None: queryset = self.get_queryset() try: email_confirmation = queryset.get(key=key.lower()) except EmailConfirmation.DoesNotExist: return HttpResponseRedirect("accounts/") return email_confirmation def get_queryset(self): qs = EmailConfirmation.objects.all_valid() qs = qs.select_related("email_address__user") return qs class CustomRegisterView(RegisterView): serializer_class = CustomRegisterSerializer permission_classes = [permissions.AllowAny] class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer the url in verification email is 'http://backend/accounts/confirm-email/Mzk:1r99pa:fG8rVgPl5q4WBQzs3saCYGKeVsquqwlvcFtwPvys3Wg/' I tried to add URL_FRONT in settings.py and changed every HttpResponseRedirect urls...I also changed domain using shell but that 'http://backend/' never changed. -
GENERATED ALWAYS AS at MariaDB in Django
I have a column in mariadb called operator_tax_info, with the following structure, CREATE TABLE `operator_tax_info` ( `id` int(11) NOT NULL AUTO_INCREMENT, `created` datetime(6) NOT NULL, `modified` datetime(6) NOT NULL, `visible` tinyint(1) NOT NULL, `operator_id` int(11) DEFAULT NULL, `geolocation` point NOT NULL, `data` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL CHECK (json_valid(`data`)), `fiscal_number` varchar(255) GENERATED ALWAYS AS (json_unquote(json_extract(`data`,'$.fiscal_number'))) STORED, PRIMARY KEY (`id`), KEY `operator_tax_info_operator_id_0c173d85_fk_companies_operator_id` (`operator_id`), SPATIAL KEY `operator_tax_info_geolocation_id` (`geolocation`), KEY `fiscal_number` (`fiscal_number`), CONSTRAINT `operator_tax_info_operator_id_0c173d85_fk_companies_operator_id` FOREIGN KEY (`operator_id`) REFERENCES `companies_operator` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=639 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci as you can see the column fiscal_number is a generated column from data column which is a json field, that column was recently added, to get fiscal_number from the json, and also as backend we use Django 3.2 as our ORM, with the following Model definition: class OperatorTaxInfo(BaseModel, SoftDeletionModel): operator = models.ForeignKey( 'companies.Operator', related_name='operator_tax_info_operator', on_delete=models.DO_NOTHING, null=True) data = JSONField(default=dict) geolocation = geomod.PointField('Geo_localizacion', default=Point(0, 0)) class Meta: db_table = 'operator_tax_info' So my question is there a way to map this column from mariadb to Django, or how to generate this column from Django using migrations and indexes, without losing speed from db, because I have trying using a @property decorator to map and annotate this … -
URL Appending instead of redirecting
When I click the link on my HTML page, instead of redirecting to the clicked url it appends to the current one and displays an error (404). How can I solve this and redirect to the correct url? HTML Table where the link is displayed: {% for acesso in acessos_medicos %} <tr class="linha-tabela"> <td>{{acesso.identificacao}}</td> <td>{{acesso.status}}</td> <td><a href="{{acesso.url}}">{{acesso.url}}</a></td> </tr> {% endfor %} models.py: @property def url(self): return f'http:127.0.0.1:8000/exames/acesso_medico/{self.token}' path in urls.py: path('acesso_medico/<str:token>', views.acesso_medico, name="acesso_medico")