Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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") -
I want to make sure that if the user answers the question correctly, then points are added to him, and the total number of points is saved in the db
I want to make sure that if the user answers the question correctly, then points are added to him, and the total number of points is saved in the db, but the problem is that the wrong type is constantly or something else is wrong It's a model, but it's probably not needed. class Task(models.Model): title_task = models.CharField(verbose_name="Заголовок", max_length=128) description_task = models.TextField(verbose_name="Задание") created_at_task = models.DateTimeField(auto_now_add=True) update_at_task = models.DateTimeField(auto_now=True) user = models.ForeignKey(to=User, verbose_name="Пользователь", on_delete=models.CASCADE) image_task = models.ImageField(verbose_name="Обложка", upload_to="advertisements/", blank=True, null=True) right_answer = models.CharField(verbose_name="Верный ответ",default=1, max_length=128) class Meta: db_table = 'tasks' def __str__(self): return f"task(id = {self.id}, title = {self.title_task})" @admin.display(description="дата создания") def created_date_task(self): if self.created_at_task.date() == timezone.now().date(): created_time_task = self.created_at_task.time().strftime("%H:%M") return format_html("<span style = 'color:blue;'>Сегодня в {} </span>",created_time_task) else: return self.created_at_task.strftime("%d:%m%y в %H:%M") @admin.display(description="дата обновления") def update_date_task(self): if self.update_at_task.date() == timezone.now().date(): update_time_task = self.update_at_task.time().strftime("%H:%M") return format_html("<span style = 'color:blue;'>Сегодня в {} </span>", update_time_task) else: return self.update_at_task.strftime("%d:%m%y в %H:%M") @admin.display(description="Изображение") def image_mini_task(self): if self.image_task: return format_html("<img src='{}' style = 'width:40px;'>", self.image_task.url) def get_absolute_url(self): return reverse('task', kwargs={"pk": self.pk}) another model, but it is already available to users class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) points = models.IntegerField(verbose_name="Баллы", default=0) viev.py @login_required(login_url=reverse_lazy("login")) def task(request, pk): answer = request.POST.get("answer") points = int(Profile.objects.values_list("points", flat=True).get(pk = )) tasks = … -
Facing an issue to update an existing object in Django 4
I'm working with a Diagnostic tool, I'm trying to update an existing instance of the database, I'm rendering a group of data corresponding to the device which being repaired, I have a second section of my render which shows a group of fields which must be updated by the Diagnosticador, those are the fields which will be updated. For some reason I keep getting orden_de_diagnosticoDiagnostico with this Orden de diagnóstico already exists.. Which is kinda obvious, since I'm looking to update an existing object. Can't find the reason for this to turn the form into invalid. Have tried multiple approaches, get, get_or_create, defining hidden fields emulating another page which already works in a similar way and nothing works. Looking forward to go over this form is invalid error due an object already existing. Models class Diagnostico(models.Model): orden_de_trabajo = models.ForeignKey(Cargaseries, on_delete=models.CASCADE, default=None, to_field='orden_de_trabajo', verbose_name='Orden de Trabajo', null=True) orden_de_diagnostico = models.CharField(db_column='orden_de_diagnostico',max_length=5, verbose_name='Orden de diagnóstico', primary_key=True, unique=True) # Field name made lowercase. Field renamed to remove unsuitable characters. numero_de_serie = models.CharField(db_column='numero_de_serie', max_length=45, verbose_name='S/N', null=True) diagnosticador = models.CharField(max_length=45, verbose_name='Diagnosticador', null=True) condicion_caja = models.ForeignKey('Condicioncaja', db_column='condicion_caja_id',on_delete=models.CASCADE, to_field='condicion_caja', verbose_name='Condicion Caja', default='Elige el estado de la caja', null=True) marca_cargador = models.CharField(verbose_name='marca_cargador', max_length=45, null=True) # Field name made lowercase. … -
Python-Streamlit Security
I'm using Streamlit for a web app. I built a system authenticator with streamlit_authenticator. When users log in, they can view specific data. I made a connection between Streamlit and MySQL. In this database, there are usernames and passwords, as well as specific data for users. Is this approach safe for deployment on the internet? Do you know other ways? For example, I tried with Django, but its difficult to integrate this with Streamlit. -
Django: My context variable with a zip list only works with one for loop. If I want to use the same variable in a different loop it doesn't work
In views.py I have the variable mylist = zip(set1,set2,set3) In templates I do {% for val1, val2, val3 in mylist%} {% endfor %} It works fine. However, if I duplicate the condition it fails. Is it normal? Let's say I have the following: # this is my page some text {% for val1, val2, val3 in mylist %} {{forloop.counter}} {% endfor %} more text {% for val1, val2, val3 in mylist %} {{forloop.counter}} {% endfor %} more text # final text of page The first loop will work, and the second one will be empty. It seems as though I can only use once mylist. I didn't experience this issue with simple lists (as far as I remember) -
Django: default value for select element in django form
Let's say I have a model and a form: class Industry(models.Model): title = models.CharField(max_length=100) class SelectIndustryForm(ModelForm): industry = ModelChoiceField(label='Industry', required=True, queryset=Industry.objects.all(), widget=forms.Select(attrs={'class': 'form-select', 'name': 'industry'})) I created a bunch of objects of the Industry class, and among them there is an object with the title "Unspecified". Is it possible to make this option a default value in the HTML select element (the one where you need to choose an option in the drop-down list) when the form loads? -
Django Abstractuser login fuction problem
I am trying to use Django AbstractUser model to create my own user model, Everything seems to be working fine but my single login/register form seems to be having a problem and that is the Register function works fine and registers the users but they are not getting logged in. my account Model file is as below : class MyUserManager(BaseUserManager): def create_user(self, shenase, password=None, **other_fields): if not shenase: raise ValueError("shenase is required...!") user = self.model(shenase=shenase, **other_fields) user.set_password(password) user.save() return user def create_superuser(self, shenase, password=None, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser muse have is_staff=True') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser muse have is_superuser=True') return self.create_user(shenase, password, **other_fields) def random_string(): return str(random.randint(1000000, 9999999)) class MyUser(AbstractUser): username = None shenase = models.CharField(max_length=11, unique=True) eshterak = models.CharField(max_length=7,default=random_string, null=True, blank=True, unique=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) objects = MyUserManager() USERNAME_FIELD = 'shenase' REQUIRED_FIELDS = [] backend = 'account.mybackend.ModelBackend' and my views file is : def register_view(request): form = forms.RegisterForm if request.method == "POST": try: if "shenase" in request.POST: shenase = request.POST.get('shenase') user = MyUser.objects.get(shenase=shenase) user.save() request.session['user_shenase'] = user.shenase return HttpResponseRedirect(reverse('account:welcome')) except MyUser.DoesNotExist: form = forms.RegisterForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() request.session['user_shenase'] = … -
Can you please tell me how createview is working here ? I mean there is no link in action in form. the how clicking submit is not causing any error?
I am learining how to make a blog app using django. my doubt is createview is inserting data in the database but how does clciking on save button is not rasiing any error there is no link in actio= .enter image description here i have previously made some websites with falsk. so we should provide a link for action so that form data is sent on that link and behind my code has some logic to insert taht recived data in databse. but here no link in action? so how does createview does this? -
Django isn't showing my form error messages
I have a problem when I'm trying to show messages: When I submit the form and use the is_valid(), the only error that show me is password mismatch error (even when the problem isn't the password) here is my code: Form: from django.contrib.auth import forms class Create_user_form(forms.UserCreationForm): error_css_class = "is-invalid" required_css_class = "required-field" class Meta: model = User error_messages = { "dni": { "unique": ("Documento ya registrado."), }, "username": { "unique": ("CUIT/CUIL ya registrado."), }, } fields = ("username", "nombre", "apellido", "dni", "edad") Models : class Datos_Adicionales(models.Model): nombre = models.CharField( unique=False, null=True, default="", max_length=32, ) apellido = models.CharField( unique=False, null=True, default="", max_length=32, ) dni = models.CharField( unique=True, null=False, default="", max_length=32, ) edad = models.IntegerField( unique=False, null=False, default=-1, ) class Meta: abstract = True class User(AbstractUser, Datos_Adicionales): username: models.CharField( unique=True, null=False, verbose_name= "Nombre de Usuario", max_length=32, ) password: models.CharField( unique=True, null=False, max_length=32, ) class Meta: db_table = "usuario" verbose_name = 'Usuario' verbose_name_plural = ' Usuarios' ordering = ['id'] Django => 4.2.7 Sorry but I don't know what more to say... Sorry but I don't know what more to say... Sorry but I don't know what more to say... Sorry but I don't know what more to say... -
How to define public permissions in the base class of django model and generate different codename for each subclass
django-4.2.6+python3.10 This is my base model class: from django.db import models class BaseModel(models.Model): class Meta: abstract = True permissions = [ ("restore", "Restore deleted obj"), ] This is my subclass: class One(BaseModel): name = models.CharField("name for you", max_length=200) class Two(BaseModel): name = models.CharField("name for you", max_length=200) After I executed python manage.py makemigrations and python manage.py migrate It generates such records in the auth_permission table of the database: auth_permission This is not what I want, because their codename is the same, which will lead to confusion. Because I have many such subclasses, all with the same type of permissions, but for different models, I don't want to repeat the definition in each subclass I hope that after running those two commands, it can generate different codename for each model in the database, such as: Generate a permission with the codename restore_one for the one model, and generate a permission with the codename restore_two for the two model. expected I tried to find the answer in the official documentation of django, but I got nothing. Perhaps we can start with the python manage.py makemigrations command. Can anyone tell me how to do it? -
Trouble Using Django Rest Framework 3.0 with Django 3.2 and Python 3.9
I am currently working on an assigmnet that requires working with specific versions of Django, DRF, and Python. Django Rest Framework (DRF) version >3.0 Django version >3.2 Python version >3.9 However, when attepting to use DRF version 3.0, I encountered the following error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No module named 'django.core.urlresolvers' I found that upgrading DRF to a version beyond 3.0 resolves this issue. However, the assignment specifically mandates using DRF 3.0. Could you please provide guidance or suggestions on how to address this error while ensuring compliance with DRF 3.0? Any help or insights would be greatly appreciated. Thank you! -
Code 1011 in django website Websockets connection
I have been working on a django chatting application (https://aniconnect.org) which uses daphne (django-channels) for the websocket functionality which allows users to chat with each other. Every time I open a chatroom, the websocket connection opens and closes instantly. Upon doing some debugging, I found out the error code was 1011. The following is consumers.py which handles websocket backend logic: from channels.generic.websocket import AsyncWebsocketConsumer import json from django.contrib.auth.models import User from .models import ChatRoom, Message, Profile #from channels.db import database_sync_to_async from asgiref.sync import sync_to_async @sync_to_async def save_message_to_database(chatroom_name, username, message): try: chatroom = ChatRoom.objects.get(name=chatroom_name) user = User.objects.get(username=username) user_profile = Profile.objects.get(user=user) new_message = Message.objects.create(chat_room=chatroom, sender=user_profile, content=message) print("Message saved to DB:", new_message) except ChatRoom.DoesNotExist: print(f"Chatroom with name '{chatroom_name}' does not exist.") except Profile.DoesNotExist: print(f"User profile with username '{username}' does not exist.") except Exception as e: print(f"Error occurred while saving the message: {e}") @sync_to_async def get_chatroom_by_name(name): try: return ChatRoom.objects.get(name=name) except ChatRoom.DoesNotExist: return None @sync_to_async def get_messages_for_chatroom(chatroom): return list(Message.objects.filter(chat_room=chatroom).order_by('timestamp')) class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() print(f"WebSocket connection opened for room: {self.room_name}") chatroom = await get_chatroom_by_name(self.room_name) if chatroom: print(f"Chatroom: {chatroom.name}") else: print(f"Chatroom '{self.room_name}' not found.") messages = await get_messages_for_chatroom(chatroom) for message in … -
How can I add a MultipleChoiceField field to ConfigForm (djconfig library)?
I have a form that I'm trying to add a MultipleChoiceField to. class BasicConfigForm(ConfigForm): site_name = forms.CharField(initial="Spirit", label=_("site name")) site_description = forms.CharField( initial="", label=_("site description"), max_length=75, required=False) site_wiki = forms.URLField( initial="", label=_("Wiki link"), required=False, widget=forms.URLInput(), help_text=( "Insert wiki link here")) bug_report_url = forms.URLField( initial="", label=_("Your bug report link"), required=False, widget=forms.URLInput(), help_text=( "Insert bug report link here (don't post anything if there is no link.)")) enabled_languages = forms.MultipleChoiceField( label='Enabled Languages', choices=base.LANGUAGES, widget=forms.CheckboxSelectMultiple, required=False, ) comments_per_page = forms.IntegerField( initial=20, label=_("comments per page"), min_value=1, max_value=100) topics_per_page = forms.IntegerField( initial=20, label=_("topics per page"), min_value=1, max_value=100) This field appears and displays fine, but when I try to save this form, everything except this field is saved. How can I make sure it is saved? my views: User = get_user_model() @administrator_required def config_basic(request): form = BasicConfigForm(data=post_data(request)) if is_post(request) and form.is_valid(): enabled_languages = form.cleaned_data['enabled_languages'] form.enabled_languages = enabled_languages form.save() messages.info(request, _("Settings updated!")) return safe_redirect(request, "next", request.get_full_path()) print() return render( request=request, template_name='spirit/admin/config_basic.html', context={'form': form}) I tried to override save() in BasicConfigForm, but I think I did it wrong. def save_enabled_languages(self): self.enabled_languages = self.cleaned_data['enabled_languages'] def save(self): self.save_enabled_languages() super(BasicConfigForm, self).save() -
I have react django app, and the problem while refresh page - opens API page
I have react django app, and the problem while refresh page - opens API page. All works good, but when page is refreshed suddenly opens Api page with many fields of django model, how to avoid that? Index.js file: ` import React from 'react'; import ReactDOM from 'react-dom/client'; import { createBrowserRouter, RouterProvider } from 'react-router-dom'; import { BrowserRouter as Router, Route, Routes } from 'react-router-dom'; import App from './App'; import Lesson from './lessons/Lesson1'; import AllLessons from './pages/AllLessons'; import FormikLogin from './pages/FormikLogin'; import Home from './pages/Home'; import ErrorPage from './pages/Home' import LessonCreate from './pages/LessonCreate'; import LessonsByCategory from './pages/LessonsByCategory'; import LessonUpdate from './pages/LessonUpdate'; import RegisterFormik from './pages/RegisterFormik'; const router = createBrowserRouter([ { path: "/", element: <App />, errorElement: <ErrorPage />, children: [ {index: true, element: <Home />}, {path: "/api/users/login", element: <FormikLogin />}, {path: "/api/users/register", element: <RegisterFormik />}, {path: "/api/lesson/:pk", element: <Lesson />}, {path: "/api/create/lesson", element: <LessonCreate />}, {path: "/api/update/lesson/:pk", element: <LessonUpdate />}, {path: "/api/lessons/list", element: <AllLessons />}, // categories of lessons {path: "/api/lessons/:slug", element: <LessonsByCategory />}, // lessons by category ] } ]) const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <RouterProvider router={router} /> </React.StrictMode> ); ` urls.py file: ` from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from … -
The view account.views.user_login didn't return an HttpResponse object. It returned None instead
Cannot register or login account.views didn't return http response # accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, UserLoginForm def register(request): context = {} if request.POST: form = RegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') password = form.cleaned_data.get('password1') account = authenticate(username=username, email=email, password=password) login(request, account) return redirect('home') # Redirect to your home page else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'accounts/register.html', context) def logout_view(request): logout(request) return redirect('home') def user_login(request): context = {} user = request.user if user.is_authenticated: return redirect("home") if request.POST: form = UserLoginForm(request.POST) if form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: user_login(request, user) return redirect('home') else: form = UserLoginForm() context['login_form'] = form return render(request, 'accounts/login.html', context) I tried to register users but its telling me that my account.views is not returning an Http response but the users account will be updated in my django admin and if try to log in it still show the same error -
How to pass optional parameters to a view in Django?
I have a view that takes two optional keyword arguments: team and year_month def monthly_data_list(request, year_month:str=None, team=None): From the template, I want to call different combinations with either one of these 2 parameters, or both. Django docs gives this example of implementing this: path('monthly/list/', views.monthly_data_list, {'team':None, 'year_month'=None },name='monthly-data-list'), However, calling this URL from the template with one or both arguments gives me a NoReverseMatch error: hx-get="{% url 'drivers:monthly-data-list' team=None year_month=current_year_month %}" I found a workaround suggested here, which is to define paths for all combinations of parameters. This works with 2 parameters, but gets complicated on more. How do you correctly implement multiple optional parameters? -
social-auth-app-django. Associate a social account by custom field in UserModel
I have a custom user model: class Profile(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... telegram_id = models.BigIntegerField(verbose_name='телеграм ID', unique=True, blank=True, null=True) ... I have configured authorization via Telegram, Google, VK. After authorization via Telegram where do I get extra_data: {"id": ["123"], "first_name": ["123"], "last_name": ["123"], "username": ["123"], "photo_url": ["https://t.me/i/userpic/320/123"], "auth_date": ["123"], "hash": ["123"]} An instance Profile and social_auth_usersocialauth records is created. I want to do the following: If the user is new when logging in via Telegram it is checked whether a Profile exists, where Profile.telegram_id == extra_data["id"] If such a profile exists: Associate the record social_auth_usersocialauth with this Profile If not: Create a record Profile as standard I have the following social auth pipelines settings: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) I suppose I need to create my own pipeline where all the logic will take place, but I don't quite understand how to do it correctly so as not to break the logic of other backends. -
"How does quantum computing influence machine learning optimization, and are there practical implementations or case studies?" [closed]
The question delves into the intersection of quantum computing and machine learning optimization. It seeks information on the impact of quantum computing on the optimization of machine learning algorithms. Additionally, it asks for insights into practical implementations or case studies that showcase the application of quantum computing in enhancing machine learning optimization. This topic is at the forefront of technological advancements, exploring the potential of quantum computing in revolutionizing traditional machine learning approaches. -
Export enums with drf-yasg to Swagger: Works in responses serializers but not in query_serializer
I have a viewset with a method with this swagger_auto_schema decorator: @swagger_auto_schema( responses={200: MyResponseSerializer(many=True)}, query_serializer=MyQuerySerializer ) When I define serializers.ChoiceField(choices=...) in MyResponseSerializer, the enum for the choices are outputted to Swagger schema. When I use ChoiceField in MyQuerySerializer, this is not outputted. Is this by design? Is there a straightforward way of exporting choices enums for query_serializers, too? -
COSR error in react and drf website but no error in django website?
I have two websites one completely in django and another uses django rest framework and react, I am trying to redirect a to a particular URl and it works fine for the django application but I get error for the react application. Both uses this return HttpResponseRedirect(next_url). What is the reason for it? -
Where to place raw custom SQL queries in Django?
I have a simple views.py file from django.db import connection from rest_framework.views import APIView from rest_framework.response import Response class UsersView(APIView): def get(self, request): with connection.cursor() as cursor: cursor.execute("SELECT * FROM users") users_data = cursor.fetchall() return Response(users_data) def post(self, request): """ {"username": "Ivan", "bio": "Hi I am Ivan"} """ data = request.data username = data.get('username') bio = data.get('bio') with connection.cursor() as cursor: cursor.execute("INSERT INTO users (username, bio) VALUES (%s, %s)", [username, bio]) return Response("Ok") I am wondering how to organize my code when using raw SQL queries. I understand that the functionality demonstrated in my code can be easily achieved using the Django ORM; this is just an illustration. Should I concentrate all query logic within the serializers.py file, or would it be preferable to create a separate file for this purpose? Could you guide me or provide a resource that explains how to organize this? Here what is ChatGPT saying about this: *"When using raw SQL queries in Django, organizing the code is crucial for maintainability and clarity. It's recommended to separate concerns and maintain a clean structure. Consider these approaches: Services/Managers: Create separate modules like services.py or managers.py to contain functions that handle raw SQL queries. These modules encapsulate … -
Text input in list choice django form
I have two model in my project: Viaggio and Cliente. Viaggio has a Foreign Key of Cliente, so the basic structure is: class Viaggio(models.Model): nome = models.CharField(max_length=255, unique=True) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True, blank=True, related_name='viaggi_cliente') class Cliente(models.Model): nome = models.CharField(max_length=255, unique=True) In the form of Viaggio i see the list of Cliente's values but i want that the user has the possibility to write for searching the value he wants. I have no idea how to achieve this. -
Logging a diff of updated model in Django Admin
Our team is trying to implement a logging solution for Django's Admin, where we would know not just which fields have been changed in latest CRUD operation on a specific model, but also the values that have changed - in short, along history we would also like a diff. We tried the post_save hook/override the save method, but that requires the overriding on every single model. EDIT: Forgot an important detail, we require this only for actions done via Django's Admin, not the rest of the code/API, ... -
Ngnix not connecting to Django/Gunicon container
I have a backend on DigitalOcean and i get a 502 when connecting to it The Ngnix error: 2023/12/01 10:05:43 [error] 31#31: *507 upstream timed out (110: Connection timed out) while connecting to upstream, client: 141.101.98.150, server: mydomaine.com, request: "GET / HTTP/1.1", upstream: "http://172.27.0.7:5001/", host: "mydomaine.com" Nginx config for dev container: server { listen 80; listen [::]:80; server_name mydomaine.com; return 301 https://$host$request_uri; } server { listen 443 ssl; listen [::]:443 ssl; server_name mydomaine.com; ssl_certificate /etc/nginx/ssl/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/privkey.pem; access_log /var/log/nginx/dev_access.log; error_log /var/log/nginx/dev_error.log; location / { proxy_pass http://dev:5001; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Docker compose file: version: "3.7" services: webserver: image: nginx:1.22.0 container_name: webserver restart: always ports: - 80:80 - 443:443 volumes: - ./logs/nginx/:/var/log/nginx/ - ./nginx/ssl/:/etc/nginx/ssl/:ro - ./nginx/configs/:/etc/nginx/sites-enabled/:ro - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro networks: - backend db_prod: image: postgres:15 container_name: db_prod restart: always ports: - "${POSTGRES_PROD_PORT}:5432" volumes: - db_prod:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_DB: ${POSTGRES_DB} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ENGINE: ${POSTGRES_ENGINE} # profiles: #TODO: fix Unsupported config option for services.{service_name}: 'profiles' # - prod networks: - backend db_dev: image: postgres:15 container_name: db_dev restart: always ports: - "${POSTGRES_DEV_PORT}:5433" volumes: - db:/var/lib/postgresql/data environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_DB: ${POSTGRES_DB} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_ENGINE: ${POSTGRES_ENGINE} # profiles: # - dev networks: - backend prod: build: ./src command: ["./start.sh"] …