Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django put save button
I would like to change the data that is in this column from a form but I can't display the data and save them and also add a delete button. anyone have a solution. models.py class Employe(models.Model): Matricule = models.CharField(max_length=10, null=False) Prenom = models.CharField(max_length=40, null=True) Nom = models.CharField(max_length=40, null=True) Tel = models.CharField(max_length=20, null=True) Adresse = models.CharField(max_length=100, null=True) Courriel = models.CharField(max_length=100, null=True) Horaire = models.CharField(max_length=50, null=True) Date_embauche = models.CharField(max_length=100, null=True) UtilisateurOSP = models.CharField(max_length=100, null=True) MotdepasseOSP = models.CharField(max_length=50, null=True) Anciennete = models.CharField(max_length=10, null=True) data_created = models.DateTimeField(auto_now_add=True, null=True) class Disciplinaire(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Avis_verbal = models.CharField(max_length=300, null=True) Avis_ecrit = models.CharField(max_length=300, null=True) Avis_ecrit2 = models.CharField(max_length=300, null=True) Suspension = models.CharField(max_length=300, null=True) Fin_emploie = models.CharField(max_length=300, null=True) data_created = models.DateTimeField(auto_now_add=True, null=True) forms.py class disciplinaireForm(ModelForm): class Meta: model = Disciplinaire fields = '__all__' views.py def updateDisciplinaire(request, id): emp = Disciplinaire.filter() forms = disciplinaireForm(instance=emp) if request.method == 'POST': forms = disciplinaireForm(request.POST, instance=emp) if forms.is_valid(): forms.save() return redirect('/') context = {'forms':forms} return render(request, 'accounts/updateDisciplinaire.html', context) page.html <th scope="col">Avis Verbal</th> <th scope="col">1er Avis Écrit</th> <th scope="col">2e Avis Écrit</th> <th scope="col">Suspension</th> <th scope="col">Fin d'emploi</th> <th scope="col">Action</th> </tr> {% for j in disci %} <tr> <td>{{j.Avis_verbal}}</td> <td>{{j.Avis_ecrit}}</td> <td>{{j.Avis_ecrit2}}</td> <td>{{j.Suspension}}</td> <td>{{j.Fin_emploie}}</td> <td><a class="btn btn-outline-info" href="{% url 'updateDisciplinaire' j.id %}">Modifier</a> </tr> {% endfor … -
Best way to integrate existing Python tools with Django?
I have number of Python tools that I run, mostly for scraping websites or pulling data from various web APIs. Currently they are all run from bash with the parameters passed as command line arguments e.g. $ python my_tool.py -arg1 -arg2 --output foobar.json I want to move away from using the command line and instead run the tools via a web interface. My aim is to have a setup where a user can authenticate to the website, enter the arguments via a web form, click to run the tools, and have the returned json data to a database for later analysis. I've chosen Django as a framework for the web interface and db since I already have experience with Python. However I'm seeking advice as to best practice for integrating the Python tools I already have with Django. Am I best to integrate the tools directly as Django apps, or keep them separate but with a means to communicate with Django? I'd be grateful for the advice and experience of others on this one. -
Django - Object of type FloatField is not JSON serializable
I have a service in django, and I am trying to get the list of all vital signs, but when I run it, it throws me the following error. This is the model "SignoVital". from django.db import models from .paciente import Paciente class SignoVital(models.Model): oximetria = models.FloatField() frecuenciaRespiratoria = models.FloatField() frecuenciaCardiaca = models.FloatField() temperatura = models.FloatField() presionArterial = models.FloatField() glicemia = models.FloatField(), paciente = models.ForeignKey( Paciente, on_delete=models.CASCADE, unique=False, blank=True, null=True ) This is serializer "SignoVitalSerializer". from rest_framework import serializers from hospiApp.models.signoVital import SignoVital class SignoVitalSerializer(serializers.ModelSerializer): class Meta: model = SignoVital fields = ['oximetria', 'frecuenciaRespiratoria', 'frecuenciaCardiaca', 'temperatura', 'presionArterial', 'glicemia', 'paciente'] This is View "SignoVitalTodosView". from rest_framework import generics,status, views from rest_framework.response import Response from rest_framework.views import APIView from hospiApp.models.signoVital import SignoVital from hospiApp.serializers.signoVitalSerializer import SignoVitalSerializer class SignoVitalTodosView(generics.ListCreateAPIView): queryset = SignoVital.objects.all() serializer_class = SignoVitalSerializer def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) This is urls.py from django.contrib import admin from django.urls import path from hospiApp import views urlpatterns = [ path('admin/', admin.site.urls), path('signoVitalTodos/', views.SignoVitalTodosView.as_view()), ] -
Django only returns last row of dict in template
I am trying to return the values from a Dict in Django. My views.py prints the the correct data in the terminal when doing a GET-request to my page, however, in my template I only get the last line of the dictionary. I have tried looping the dict in my template and all sorts of combinations but I can't seem to make it work. Am I missing something? For instance, in the template below I print the entire dict. But it still only prints the last row somehow. views.py fruits = [ 'Apple', 'Banana', 'Orange'] for fruit in fruits: price_change = historical_prices['price_change'][::-1] low_price = 0 for day in price_change: if day < -0.1: low_price += 1 else: break if low_price >= 0: ls_dict = {'fruit': fruit, 'low_price': low_price} print(ls_dict) return render(request, "prices/index.html", { "ls_dict": ls_dict, }) Template <p>{{ ls_dict }}</p> Template output {'fruit': 'Orange', 'low_price': 1} Correct print which views.py produces {'fruit': 'Apple', 'low_price': 1} {'fruit': 'Banana', 'low_price': 3} {'fruit': 'Orange', 'low_price': 1} -
def __str__(self): return str(self.name) in model
Here is my models.py. def str(self):return str(self.name) still won't change Product object (1) to the product name. from cgi import print_exception from django.db import models from django.contrib.auth.models import User # Create your models here. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) # image = category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.name) -
fastapi python throw Exception in ASGI application
i have script that on my linux server working with fastapi it worked but after while of testing its throwing back this error and i am lost with finding why. this is my code that worked @app.get("/") async def root(request: Request): client_host = request.client.host client_port = request.client.port return(f'{client_host}:{client_port}- NEW') @app.get("/Search") async def read_item(request: Request,query:str, gl: str|None): client_host = request.client.host if str(client_host) not in WHITELIST: return(f'What Are you doing here: {client_host}') return await Google(query=query,gl=gl,use_proxy=True) this is the throwback that came from nowhere :/ [2022-09-02 17:08:42 +0000] [864] [ERROR] Exception in ASGI application Traceback (most recent call last): File "/home/fastapi/venv/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 404, in run_asgi result = await app( # type: ignore[func-returns-value] File "/home/fastapi/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/fastapi/applications.py", line 269, in __call__ await super().__call__(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/exceptions.py", line 93, in __call__ raise exc File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/exceptions.py", line 82, in __call__ await self.app(scope, receive, sender) File "/home/fastapi/venv/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__ raise e File "/home/fastapi/venv/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__ await self.app(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/routing.py", line 670, in __call__ … -
django admin - when adding a model, restrict foreignkey that belong to current user
I have two models in my app. Each model has a foreignkey to the user and the two models are also related through a foreignkey. I want to use the django admin to add new objects for a model. The add_view page gives me a drop down to pick the foreignkey field, but I want to restrict these choices to the current user. models.py class Notebook(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=20) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) entry = models.CharField(max_length=500) notebook = models.ForeignKey(Notebook, on_delete=models.CASCADE) So when I am in the admin and click to add a new post, I want to choose from notebooks that only belong to me. I see all the notebooks in the dropdown (I am logged in as admin with superuser permissions). -
django assign User to a model
I want to assign a User to a Model in django, I created a custom User model and sign-up/sign-in Forms but now I want to Assign a User model to another model named Customer whenever a new user is Created Here he the Customer model class Customer(models.Model): id = models.AutoField(primary_key=True) User = models.OneToOneField( Account, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, default='0', null=True, blank=True) address = models.CharField( max_length=200, default=' ', null=True, blank=True) city = models.CharField(max_length=200, default=' ', null=True, blank=True) def __str__(self): if self.name == None: return "ERROR-CUSTOMER NAME IS NULL" return self.name Note: I can assign the User manually in the Database and It lists All the Users but I want it to do it itself when a new user is created -
Django manipulate / modify date in template
Is it possible to make an input that changes the date.today for the whole template ? my template {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} {% endfor %} the filter then would show those <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> instead of the first ones when the date is modified, I tried to use javascript but I guess it dont work bc of python objects -
Invalid object name 'table'
I have a few bases in my project. Hence I need to redefine methods which get some information from base. Everything had worked fine until I decided to authorize via active directory. Finally I get this: authorization works (default database), requests to database that is not default fails. Authorization info is stored in PostgreSQL database. Data is stored in MSSQL database. Django-ajax-datatable is response for render data from MSSQL database. Environment: Request Method: GET Request URL: http://localhost:8000/admin/app/table/ Django Version: 3.2.14 Python Version: 3.10.5 Installed Applications: ['app.apps.CrmConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'django_filters', 'bootstrap3', 'ajax_datatable'] Installed Middleware: ['debug_toolbar.middleware.Debu gToolbarMiddleware', 'django.middleware.security.Se curityMiddleware', 'django.contrib.sessions.middl eware.SessionMiddleware', 'django.middleware.common.Comm onMiddleware', 'django.middleware.csrf.CsrfVi ewMiddleware', 'django.contrib.auth.middlewar e.AuthenticationMiddleware', 'django.contrib.messages.middl eware.MessageMiddleware', 'django.middleware.clickjackin g.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.10/site-packages/mssql/base.py", line 598, in execute return self.cursor.execute(sql, params) The above exception (('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'table'. (208) (SQLExecDirectW)")) was the direct cause of the following exception: File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(vie w)(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = … -
Django - Retrieve a session value to a form
I have a Django aplication and need to get a value from the session and put it in a HiddenInput. I have this code in my view: @login_required(redirect_field_name='login') def obra_open_view(request, obra_id): obra = get_object_or_404(Obra, pk=obra_id) if obra: request.session['obra_aberta_id'] = obra.id request.session['obra_aberta_name'] = obra.nome return redirect('obra_detail_url') else: request.session['obra_aberta_id'] = 0 request.session['obra_aberta_name'] = "" return redirect('obra_lista_url') When I have some value on 'obra_aberta_id' I need to put this value on a HiddenInput: class FormCarga(ModelForm): class Meta: model = Carga fields = ('__all__') widgets = { 'tag': forms.TextInput(attrs={'class': 'form-control'}), 'nome': forms.TextInput(attrs={'class': 'form-control'}), 'descricao': forms.Textarea(attrs={'class': 'form-control'}), 'potencia': forms.TextInput(attrs={'class': 'form-control'}), 'unidade_medida_potencia': forms.Select(attrs={'class': 'form-control'}), 'area': forms.Select(attrs={'class': 'form-control'}), 'tensao': forms.Select(attrs={'class': 'form-control'}), 'fonte': forms.Select(attrs={'class': 'form-control'}), 'atividade': forms.Select(attrs={'class': 'form-control'}), 'fator_potencia': forms.Select(attrs={'class': 'form-control'}), 'condutores_carregados': forms.Select(attrs={'class': 'form-control'}), 'obra': forms.HiddenInput(attrs={'class': 'form-control','initial' : request.session['obra_aberta_id']}), } But I'm getting an error on 'request': name 'request' is not defined How can I get a value from the session e set os this HiddenInput? I don't know if the models will help, but there it is anyway: class Carga(models.Model): tag = models.CharField(max_length=10) nome = models.CharField(max_length=100) descricao = models.TextField(blank=True, verbose_name='Descrição') potencia = models.CharField(blank=True, max_length=10, verbose_name='Potência') unidade_medida_potencia = models.ForeignKey(UnidadeMedidaPotencia, on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name='Unidade de Medida') area = models.ForeignKey(Area, on_delete=models.DO_NOTHING, null=True, verbose_name='Área') tensao = models.ForeignKey(Tensao, on_delete=models.DO_NOTHING, null=True, verbose_name='Tensão') fonte … -
Django 3.2 Admin FK Inline with edit
I am pretty new to Django. I have two models: Service, and ServiceBlock. I want to be able to have many ServiceBlock objects on the edit page for a Service in the Django Admin. Models.py from django.db import models class ServiceBlock(models.Model): title = models.CharField(max_length=200) subtitle = models.CharField(max_length=200) content = models.CharField(max_length=500) image = models.ImageField(upload_to='serviceBlocks', blank=True, null=True) class Service(models.Model): title = models.CharField(max_length=200) subtitle = models.CharField(max_length=200) image = models.ImageField(upload_to='service', blank=True, null=True) serviceBlocks = models.ManyToManyField(ServiceBlock, related_name="serviceserviceblocks") admin.py from django.contrib import admin from .models import * class ServicesServiceBlocksInline(admin.TabularInline): model = Service.serviceBlocks.through class ServicesAdmin(admin.ModelAdmin): inlines = [ ServicesServiceBlocksInline, ] admin.site.register(Service, ServicesAdmin) I understand why I am seeing what I am seeing in the screenshot below. What I want is to have many ServiceBlock objects but with the ability to edit/create new ServiceBlocks inline. What am I doing wrong? -
success url not redirecting to the page i want
I have a CreateView class where i set the success url like this class ListCreateView(CreateView): model = List fields = "_all_" success_url = "list" after submitting the form Its going to http://127.0.0.1:8000/home/create_list/list which doesnt exist I want it to go to http://127.0.0.1:8000/home/list can anyone help with some suggestions? I tried reverselazy but that brings up another big error. and im a noob. -
Django vs Tensorflow Serving
I have a Tensorflow model that I would like to deploy as a RESTful API. I'm thinking of deploying it either using Django or Tensorflow Serving. I'm very familiar with Django since I've been working with it for a few years but I heard that Tensorflow Serving is also a good choice for deploying Tensorflow models. Which option should I go for? Should I use Django or Tensorflow Serving to deploy my model? P/S: I'm leaning more towards Django because it has more flexibilities (i.e. I can deploy a Pytorch model on the same server as well) but I would really like to get more opinions on this. Thanks in advance! :) -
Get_context_detail wont return images in django
Im trying to give context to this detail view so i can show a picture in it, but when i load the page it wont show anything. Cheking on the page itself it says the source of the img is unkown. No errors so far. I changed the indexing to see if its that, still nothing views.py class Detalle_usuarios(LoginRequiredMixin, DetailView): model = User def get_context_detail(self, **kwargs): avatar = Avatar.objects.filter(user=user.id) ab = -1 for a in avatar: ab += 1 context = super(Detalle_usuarios, self).get_context_data(**kwargs) context = {"url":avatar[ab].imagen.url} return context template_name = 'Appfinal/usuario_detalle.html' template {% extends "Appfinal/template_logueado.html" %} {% load static %} {% block B %} <h1> {{user.username}} </h1> <img height = "80px" src="{{url}}"> <a href="/Appfinal/agregaravatar">Cambiar foto de perfil</a> <br> <a href="{% url 'usuarioInicio' %}">Inicio</a> {% endblock %} -
Django drf serialiser map non pk field to object of model
I have Language model like this class Language(models.Model): name = models.CharField() class Post(models.Model) title = models.CharField() language = models.ForeignKey(Language, models.SET_DEFAULT, default=1) class PostSerializer(serializers.ModelSerializer): language = serializers.CharField(source='language.name') class PostCreateAPIView(generics.ListCreateAPIView): serializer_class = serializers.PostSerializer Post payload { "title":"title_1", "language": "en" // instead of primary key } I wanted to map language name into object without using pk in payload. -
Fatal error in launcher: Unable to create process using "Path","Path" The system cannot find the file specified while using Uvicorn --reload
It's my first time with FastAPI and i'm trying to run my application, I used Uvicorn book:app --reload and my virtual environment is activated but I found this Error Fatal error in launcher: Unable to create process using '"S:\Fastapi\fastapienv\Scripts\python.exe" "S:\Fastapi\FastAPI\fastapienv\Scripts\uvicorn.exe" books:app --reload': The system cannot find the file specified. -
Docker - Build a service after the dependant service is up and running
I have a docker-compose file for a Django application. Below is the structure of my docker-compose.yml services: private-pypi-server: .... django-backend: build: context: ./backend dockerfile: Dockerfile depends_on: - private-pypi-server nginx: depends_on: - django-backend Django app is dependent on a couple of private packages hosted on the private-pypi-server without which the app won't run. I created a separate dockerfile for django-backend alone which install packages of requirements.txt and the packages from private-pypi-server. But the dockerfile of django-backend service is running even before the private pypi server is running. If I move the installation of private packages to docker-compose command code, then it works fine. Here the issue is that, if the backend is running and I want to run some commands in django-backend(./manage.py migrat) then it says that the private packages are not installed. Im not sure how to proceed with this, it would be really helpful If i can get all these services running at once by just running the command docker-compose up --build -d -
Django modify the datetime for the whole template / modify or change date time from server
I got this template {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Leitung_der_Klasse}}</td> <td>{{Ansicht.Funktion}}</td> <td>{{Ansicht.Nname}}</td> <td>{{Ansicht.Vname}}</td> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} the _FK is a foreingkey and it can be filtered by date to show me the right result if I hard code it like that {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Leitung_der_Klasse}}</td> <td>{{Ansicht.Funktion}}</td> <td>{{Ansicht.Nname}}</td> <td>{{Ansicht.Vname}}</td> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK.DATEFUNCTION %} #just to name it <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} I need an input field like that <form method="GET"> <input type="date" class="form-control" id="date" value="{{something|date:'Y-m-d' }}"> <input type="submit"> </form> to filter the events by date like Prognose_FK shows when date is above or below and it goes on for the rest how can accomplish that if I use this from my models @property def DATEFUNCTION(self): return date.today() <= self.von_Datum it works perfect but I need to have this property dynamic for the user input hope someone find a solution -
Django sorting by date returns wrong sorting order
I have a query like this: Pedido.objects.filter(...).aggregate(...).values('dia_pedido').annotate(...).order_by('dia_pedido') The field 'dia_pedido' is of Date type. Data is not being displayed in the correct order: (...) 25/08/2022 26/08/2022 30/08/2022 01/09/2022 02/09/2022 28/06/2022 30/06/2022 01/07/2022 The last 3 lines above shouldn't be there, as June and July come before August and September. What could be happening? I'm using Django 4.0.1 and MySQL 8.0.30. -
Add a variable in a .env file in python
I have a .env file in my application and Im trying to run a script in docker. When docker reaches the entrypoint.sh it runs python manage.py runscript tryouts getting a count and then it goes like this (jwt_token is generated earlier in the script): ChirpStackURL = os.environ['CHIRPSTACK'] def checkNetworks(jwt_token): url = ChirpStackURL + '/api/network-servers?limit=10' res = requests.get(url, headers = {"Authorization": jwt_token}) count = res.json()['totalCount'] if count == '1' : return res.json()['result'][0]['id'] else: return False and then on my function i want to add the result as an enviromental variable so i can access it later on new requests. networkServerID = checkNetworks(jwt_token) if not networkServerID: print('success') else: 'export to .env file' 'NETWORK_ID = networkServerID' sample = os.environ['NETWORK_ID'] How do i do that ? -
Django queryset opposite of contains filter
here is my "Project" Model : class Project(models.Model): name = models.CharField(max_length=200, verbose_name="Project name", default="") I know how to use QuerySets to filter all the Project objects who contains "result" in their name (like this) : projects = Project.objects.filter(name__contains=result) (if I have three projects named "Hello", "Hello_World" and "Hi" and I do this : hello_projects = Project.objects.filter(name__contains="Hello") my QuerySet "hello_projects" will contains the projects named "Hello" and "Hello_World") I want to do it in the opposite way, and filter the projects who have their name in my result. For example, if "result" is "Hello_World_Its_Me", I want to get all projects who have their names inside result, so "Hello", and "Hello_World" Is there a way to do it ? -
how to connect auth0 database to django database with drf
So i'm trying auth0 with the django rest framework and in the documentation of connecting it with drf it only shows how to validate it but I couldnt find how to connect it to the django database. Dose anyone know how to do this -
Unable to get graphql's datetime in tenant's timezone
We are working on a multi tenant django app that needs to display datetimes in tenant's timezone. We achieve multitenancy using django-tenants, it separates tenants via Posgresql different schemas. We are using graphql through graphene to expose our APIs, and we would like to make this implementation transparent to it, thus avoiding to manipulate every datetime we receive in input with timezone.localtime(received_datetime). We've written a middleware that should do the job but graphene queries keep displaying the naive datetimes, to our understanding this is because django, while timezone aware, manage datetimes timezone only at forms and template levels, as per docs: https://docs.djangoproject.com/en/4.1/topics/i18n/timezones/ When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms. By looking at timezone.now and timezone.localtime(timezone.now) values we get the correct results, but every date we get from graphql is both aware and with django "from settings" timezone (UTC), instead of tenant's timezone: timezone.now(). # prints 2022-09-02 13:38:46.658864+00:00 timezone.localtime(timezone.now()) # prints 2022-09-02 22:56:16.620355+09:00 Querying graphql api instead outputs: "edges”: [ { “node”: { “id”: “UG9saWN5Tm9kZToxNQ==“, “createdAt”: “2022-09-01T13:55:04.542763+00:00" # in UTC timezone, instead of tenant's … -
Django - unable to test; "no such column"
I'm facing a weird issue that appeared out of the blue. My app works fine, all migrations are up to date and applied, and I am able to runserver. However, I noticed that when I try to run any tests, this is what happens (backend) samuelebonini@Samueles-MacBook-Pro-2 backend % ./manage.py test courses/tests Found 40 test(s). Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: error in index django_celery_results_taskresult_hidden_cd77412f after drop column: no such column: hidden The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/test/runner.py", line 1045, in run_tests old_config = self.setup_databases( File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/test/runner.py", line 941, in setup_databases return _setup_databases( File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/test/utils.py", line 220, in setup_databases connection.creation.create_test_db( File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/db/backends/base/creation.py", …