Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use django_filters to query a list that contains any item in query params
^^ I'm having a Django model that contains a JSON field to store a list, like so: class Movie(models.Model): tags = JSONField() As such, a movie mymovie contains a list of tags, such as: mymovie.tags = ["horror", "love", "adventure"]. And now, I want a query to fetch all movies having at least one tag of a list of tags, like so: GET /movies?tags=horror,cowboy In my previous example, the query will get mymovie, because it has horror in its tag, even if it doesn't have cowboy. Using *django_filters, I managed to do it with the following implementation: class CharInFilter(BaseInFilter, CharFilter): pass class MovieFilter(FilterSet): class Meta: model = Movie fields = ["tags"] tags = CharInFilter(method="tags_filter") def tags_filter(self, queryset, name, value): # value will contain a list of tags, and we want any movie that at least one of # its tag is in the list of provided tags query = Q() for tag in value: query |= Q( tags__icontains=tag ) if query: queryset = queryset.filter(query) return queryset It works, but it feels very hacky, and I won't be surprised if an ad hoc implementation of this exist. Can someone have a better idea ? Thank youuuu ^^ -
Populate stock predictions in django database with models
I have a code which outputs the prediction of stocks. I've been trying to figure out how to populate the predictions into the database. Every time the code runs, it should modify the database with the new predictions. This is my 'predictions.py': import yfinance as yf import numpy as np # Processing data as arrays import pandas as pd # Used to create a dataframe that holds all data from keras.models import load_model # Used to load existing models import datetime import joblib def models_loader(folder, name, days = [1, 5, 30]): model = [] for i in days: model.append(load_model(folder+'/'+ name + '_' + str(i) + '.h5')) return model days = [1,5,14,30,90] #Day intervals scaler = joblib.load('scaler.sav') models = models_loader('ML Model','Model', days) #Load models has_Run = False companies = ['TSLA', 'AAPL','SIRI','GGB','PLUG'] while True: print("Has started") time = datetime.datetime.today() schedule = datetime.time(17,0,0) if time.hour == schedule.hour and has_Run==False: #change second time hour to schedule hour last = datetime.date.today() td = datetime.timedelta(100) start = last - td for symbols in companies: print(symbols) predINV= [] data = yf.download(symbols,start = start, end = last) data = data.filter(['Close']) if len(data.index) > 59: INPUT = data.values INPUT = INPUT[-60:] scaled_input = scaler.fit_transform(INPUT) scaled_input = np.reshape(scaled_input, (-1,60,1)) for … -
Django deployment to Heroku error: python: can't open file '/app/backend.manage.py': [Errno 2] No such file or directory , is this a Procfile error?
I've once again come to beg stackoverflow for help. I am attempting to deploy a django project to Heroku and I'm getting slapped left and right with errors but hopefully this is the last one. 2022-03-07T22:03:09.363036+00:00 heroku[release.9772]: Starting process with command `/bin/sh -c 'if curl https://heroku-release-output.s3.amazonaws.com/log-stream?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAJ3LIQ2SWG7V76SVQ%2F20220307%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20220307T220304Z&X-Amz-Expires=900&X-Amz-SignedHeaders=host&X-Amz-Signature=ddb760b1c36e913b7c0cc984428e3b853cdac67755e4cfa6038cef77a37b6a25 --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2022-03-07T22:03:10.031451+00:00 heroku[release.9772]: State changed from starting to up 2022-03-07T22:03:10.527868+00:00 app[release.9772]: python: can't open file '/app/backend.manage.py': [Errno 2] No such file or directory 2022-03-07T22:03:10.706087+00:00 heroku[release.9772]: Process exited with status 2 2022-03-07T22:03:10.901301+00:00 heroku[release.9772]: State changed from up to complete 2022-03-07T22:02:37.000000+00:00 app[api]: Build started by user email@protonmail.com 2022-03-07T22:03:03.734406+00:00 app[api]: Deploy 922870fe by user email@protonmail.com 2022-03-07T22:03:03.734406+00:00 app[api]: Running release v26 commands by user email@protonmail.com 2022-03-07T22:03:05.039171+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2022-03-07T22:03:05.039171+00:00 app[api]: chmod u+x /tmp/log-stream 2022-03-07T22:03:05.039171+00:00 app[api]: /tmp/log-stream /bin/sh -c '"'"'python backend.manage.py makemigrations - - no-input'"'"' 2022-03-07T22:03:05.039171+00:00 app[api]: else 2022-03-07T22:03:05.039171+00:00 app[api]: python backend.manage.py makemigrations - - no-input 2022-03-07T22:03:05.039171+00:00 app[api]: fi'` by user email@protonmail.com 2022-03-07T22:03:12.919074+00:00 app[api]: Release v26 command failed by user email@protonmail.com 2022-03-07T22:03:15.000000+00:00 app[api]: Build succeeded And when I try to run the program in a virtual environment on my local machine using the command … -
django admin: best way to update ForeignKey field (using AutocompleteSelect) for multiple objects at once
I'm pretty new to django and having some trouble trying to update an admin autocomplete_field for multiple rows at once. In the list page of PrimaryModelAdmin, I'd like to find an efficient way to update the foreign_field to the same value for multiple PrimaryModel objects. It seems like the best way to achieve this is with a custom action that has an intermediary page. I'm just having real trouble on how to use the AutocompleteSelect widget on this page. Does anyone have any ideas or advice on whether I'm even going down the right path? Cheers # in models.py class PrimaryModel(models.Model): ... foreign_field = models.ForeignKey( ForiegnModel, null=True, blank=True, on_delete=models.RESTRICT ) class ForeignModel(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255, null=False) # in admin.py @admin.register(models.PrimaryModel) class PrimaryModelAdmin(admin.ModelAdmin): autocomplete_fields = ["foreign_model"] -
Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework
I use in my study project django rest framework.I get an error 403 Forbidden (CSRF token missing or incorrect, when I try to save using the POST method. Here is my code html <form id = "product_form" method = "post"> {% csrf_token %} <input type = "hidden" name = "id" id = "id"> <p>Назвние:<input name = "name" id = "name"></p> <p><input type = "reset" value = "Oчистить"></p> <input type = "submit" value = "Сохранить"> </form> Here is my code js: let productUpdater = new XMLHttpRequest(); productUpdater.addEventListener('readystatechange', () => { if (productUpdater.readyState == 4) { if ((productUpdater.status == 200) || (productUpdater.status == 201)) { listLoad(); name.form.reset(); id.value = ''; } else { window.alert(productUpdater.statusText) } } } ); name.form.addEventListener('submit', (evt) => { evt.preventDefault(); // let vid = id.value, url, method; let vid = id.value; if (vid) { url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/'; method = 'PUT'; } else { url = 'http://127.0.0.1:8000/books/api_category/'; method = 'POST'; } let data = JSON.stringify({id: vid,nameCategory: name.value}); productUpdater.open(method, url, true); productUpdater.setRequestHeader('Content-Type', 'application/json'); productUpdater.send(data); }) Here is my views.py: @api_view(['GET', 'POST']) def api_products(request): if request.method == 'GET': productsAll = CategoryMaskarad.objects.all() serializer = CategorySerializer(productsAll, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return … -
How to see Django admin panel elements reordered in another tabs?
I want to reorder my django models in admin panel. I found the django-modeladmin-reorder package and installed it. I did everything according to the documentation, but I still have a problem. Reordering elements are being shown only on the main page of the website, if I click on a model to add or edit I see the old reorder. How can I see the new reorders in other tabs ? Good order: https://i.imgur.com/69N1CRs.png Bad order: https://i.imgur.com/9UYLXbX.png This is the code in settings.py ADMIN_REORDER = ( # First group {'app': 'website', 'label': 'Postări', 'models': ('website.Article', 'website.Research', 'website.Reports', 'website.Advocacy', 'website.Document', 'website.Domain', 'website.News', ) }, # Second group: same app, but different label {'app': 'website', 'label': 'Categorii', 'models': ('website.ArticleTag', 'website.ResearchTag', 'website.ReportsTag', 'website.AdvocacyTag', 'website.DocumentTag', 'website.DomainTag', 'website.NewsTag', ) }, {'app': 'website', 'label': 'Video', 'models': ('website.Video', 'website.MainVideo', ) }, {'app': 'website', 'label': 'Rapoarte', 'models': ('website.Reports', ) }, ) -
Django rest_framework DefaultRouter() class vs normal url
I'm using REST in Django, And I couldn't understand what is the main difference between classic URL and instantiating DefaultRouter() for registering URL by ViewSet. Is it possible to use classic URL in URLS.py instead of instantiating the object for a ViewSet View ? I just know HTTP method in ViewSet translate methods to retrieve, list and etc... Thanks for your help. -
django how to hide url and show renamed value?
I am using django-tables2 and trying to hide url and rename it on field. for example, url link is www.youtube.com but on actual field, I want it to show as 'link' instead of revealing entire url link. how do I achieve this? tables.py class MyVideoTable(tables.Table): class Meta: model = PPVideo fields = ('title', 'url') models.py class PPVideo title = models.CharField('Title', max_length=100, null=True) url = models.URLField('URL', max_length=150, null=True) -
Django AWS tutorial working for tutorial but not for full project
I'm following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I follow the tutorial exactly, except use Django 4.0.3 and Python 3.8. It works for deploying a sample project, but when I make the settings.py exactly the same and try to put up my full project, I get the follow errors: health degraded 502 Bad Gateway nginx/1.20.0 failed (111: Connection refused) while connecting to upstream I tried to add gunicorn too but nothing was changing. But why would the same setup work for a simple sample project but not for my larger personal project? -
Python manage.py runserver is showing that python is not installed on my system
Whenever I run python manage.py runserver on my terminal I keep getting Python was not found, run without arguments to install from Microsoft -
How to add logic to a model getter that uses inheritance?
I have a model for a Task class Task(BaseTask): class Meta: db_table = 'task' verbose_name_plural = 'Tasks' def __str__(self): return f'Task {self.id}' def __unicode__(self): return f'Task {self.id}' that is inherited from BaseTask class BaseTask(BaseModel): class Meta: abstract = True task_status = models.CharField( choices=TASK_STATUS_CHOICES, blank=True, max_length=200, default=WAITING ) expiration_date = models.DateTimeField(blank=True, null=True, default=None) I want the task_status for Task to return FAILED if the current date is past the expiration date. I thought I could add a getter to Task like: def get_task_status(self): return FAILED if self.expiration_date and \ check_task_is_expired(self) else self.task_status but that doesn't seem to be working. How can I accomplish adding logic to task_status so it returns FAILED after the expiration date? I'm aware of @property but other models depend on BaseTask and Task so I don't want to change the field name. -
django-registration sending activation and reset emails
I am trying to send activation and reset email in Django, but I am facing some challenges and I would be grateful if someone could kindly help me out.onfigurations in settings.py file as below #setting.py EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST ='smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER ='email@gmail.com' EMAIL_HOST_PASSWORD ='gmailpasword' EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = ‘mail.mysite.com’ DEFAULT_FROM_EMAIL = 'noreply@mysite.com' EMAIL_HOST_USER = 'noreply@mysite.com' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_USE_TLS = True EMAIL_PORT = port The first configuration is with Gmail which work fine in development but in production (shared Linux server) it does not work at all. The second configuration with an email I set up on webmail(cPanel) which is not working in either development or production. -
Getting the length of a certain row Django ORM
I am trying to query how many loans had a funded_date in the year 2021 and the total amount of those loans then show it on a template. I think I have the total amount right but am struggling on how to query and display how many loans had a funded_date in the year 2021 Views.py from django.shortcuts import render from .models import Loan import datetime from django.db.models import Sum def index(request): branch_cc = Loan.objects.filter(funded_date__year=2021) sum = branch_cc.aggregate(Sum('branch_cc')) number = branch_cc context = { 'all_loans': Loan.objects.all(), 'sum': sum, "branch_cc": branch_cc } return render(request, 'index.html', context) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1> {{sum}} <br> </h1> </body> </html> models.py from django.db import models class Loan(models.Model): funded_date = models.DateTimeField(auto_now_add=False, blank=True) respa_date = models.DateTimeField(auto_now_add=False, blank=True) loan_amount = models.FloatField(null=True, blank=True, default=None) branch_cc = models.IntegerField(default=0, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Having issues converting api json stream into an array in Flutter
The django api I am working with has the following actions user api (url = website/user/): action: CREATE_USER necessary params: action, email_address, password note: action = 0 action: LOGIN necessary params: action, email_address, password note: action = 1 action: CHANGE_PASSWORD necessary params: action, email_address, password, new_password note: action = 2 action: DELETE_USER necessary params: action, email_address, password note: action = 3 entry api (url = website/entry/): action: MAIN_PAGE necessary params: action note: action = 0 action: SEARCH_KEYWORD necessary params: action, keyword note: action = 1 action: FILTER_YEAR necessary params: action, first_year, second_year note: action = 0 note: if filter is for 1 year, first_year and second_year should be equal archive api (url = website/archive/): action: CREATE_ARCHIVE necessary params: action, email_address, password, keyword, frequency note: action = 0 note: frequency has to be 'daily', 'week', 'biweek', or 'month' action: DISPLAY_USER_ARCHIVES necessary params: action, email_address, password note: action = 1 note: to return entries pulled from archive, use action SEARCH_KEYWORD using the keyword saved in the archive action: DELETE_ARCHIVE necessary params: action, email_address, password, keyword note: action = 2 action: UPDATE_FREQUENCY necessary params: action, email_address, password, keyword, new_frequency note: action = 3 note: frequency has to be 'daily', 'week', 'biweek', or 'month' … -
Reduce stock in the database with django
I created a stock for the coffee beans in the database, and want to decrease the stock whenever CoffePods are created indicating the decrease of the beans stock. How to reduce the CoffeBeans stock in the database each time I create CoffePods which is received as a query parameter from the URL and what is the best practice in this case? views.py class PodsViewSet(viewsets.ModelViewSet): queryset = CoffePods.objects.all().order_by('id') serializer_class = CoffePodsSerializer serializer_class = CoffeBeansSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filterset_fields = '__all__' def create(self, request, *args, **kwargs): print("Coffe Pod Created!") try: pods_pack_size = int(self.request.query_params.get('pack_size')) coffe_beans = CoffeBeans.objects.all()[0] if coffe_beans.capacity > 2.0 and coffe_beans.quantity > 4: if pods_pack_size == 1: coffe_beans.capacity -= 0.5 coffe_beans.quantity -= 1 coffe_beans.save() elif pods_pack_size == 2: coffe_beans.capacity -= 1.0 coffe_beans.quantity -= 2 coffe_beans.save() elif pods_pack_size == 3: coffe_beans.capacity -= 1.5 coffe_beans.quantity -= 3 coffe_beans.save() elif pods_pack_size == 4: coffe_beans.capacity -= 2.0 coffe_beans.quantity -= 4 coffe_beans.save() except Exception as e: raise e return Response(coffe_beans) models.py class CoffeBeans(models.Model): capacity = models.FloatField(validators=[MinValueValidator(0.0)], default=100) quantity = models.PositiveIntegerField(default=200) class Meta: verbose_name_plural = 'Coffe Beans' def __str__(self): return f"{self.capacity} KG - {self.quantity} Pack" -
DRF - How to concatanate serialized model with custom field
i need to concatanate serialized models with custom field = list[] i have a user_profile model and i want to know if particular user is "mine(active user's)" friend, in the users list (list_boolean = ["True", "False", "True"]) views.py class User_profile_view(APIView): def get(self, request): #this is example list which i need to link list_boolean = ["True", "False", "True"] query = User_profile.objects.all() User_profile.objects.filter(pk=1).delete() serializer_class = User_profile_serializer(query, many=True) return Response(serializer_class.data) models.py class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) age = models.CharField(max_length=100) city = models.CharField(max_length=100) serializer.py class User_profile_serializer(serializers.ModelSerializer): class Meta: model = User_profile exclude = ["id"] is here any way to link particular list, to objects? it might be inside of the object (which is better) or outside -
Why I can't log in with this django login code, the message says: "Authentication credentials were not provided"
This is my views.py LoginView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, request): if request.method == 'POST': email = request.data.get('email', None) print(email) password = request.data.get('password',None) print(password) user = authenticate(request, email= "email", password= "pasword") print(user) if user : login(request, user) print("punto1") return Response(status=status.HTTP_200_OK) return Response( status=status.HTTP_404_NOT_FOUND) The output is: 403 Forbiden { "detail": "Authentication credentials were not provided." } -
Getting a database error when using Djongo to connect Django with MongoDB
Here is the entire error I am getting. I have tried looking everywhere for an answer and I am just lost. I have been trying to deploy, but I have been stuck with this error for months now. Internal Server Error: /profile/1/ Traceback (most recent call last): File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 116, in __init__ super().__init__(*args) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 152, in parse self.where = WhereConverter(self, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__ self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/converters.py", line 119, in parse self.op = WhereOp( File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 475, in __init__ self._statement2ops() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 413, in _token2op raise SQLDecodeError djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('SELECT "post_app_screammodel"."id", "post_app_screammodel"."content", "post_app_screammodel"."posted_by_id", "post_app_screammodel"."creation_time" FROM "post_app_screammodel" WHERE "post_app_screammodel"."posted_by_id" = %(0)s OFFSET 3',) Params: ((1,),) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Heroku set-cookie header was blocked because its domain attribute was invalid with regards to the current host url
I have a django app using htmx for a form and it's hosted on Heroku with Gunicorn as application server. I am getting 403 forbidden when I try to submit the form and tried a few different settings from reading the Django 4 docs. The form works on my local but not on Heroku. What else should I try so I can submit my htmx form with https on Heroku? my template <form hx-post="{{ request.path }}" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' class="modal-content"> ... <script>document.body.addEventListener('htmx:configRequest', (event) => {event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';)</script> my settings.py CSRF_COOKIE_DOMAIN = '.herokuapp.com' CSRF_TRUSTED_ORIGINS = ['https://django-example.herokuapp.com','http://django-example.herokuapp.com'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Response headers csrftoken=GjeYwnfTwUGLzF7DSJWOoaJk1GHiSC3MffaLaornrd4ENDgKlokkHsyoIERTReB4; Domain=.herokuapp.com; expires=Mon, 06 Mar 2023 18:01:01 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure ! This attempt to set a cookie via a set-cookie header was blocked because its domain attribute was invalid with regards to the current host url Heroku logs 022-03-07T18:59:13.184551+00:00 app[web.1]: Starting server 2022-03-07T18:59:16.297718+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Starting gunicorn 20.1.0 2022-03-07T18:59:16.298014+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Listening at: http://0.0.0.0:28553 (10) 2022-03-07T18:59:16.298062+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Using worker: sync 2022-03-07T18:59:16.301273+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [12] [INFO] Booting worker with pid: 12 2022-03-07T18:59:16.704678+00:00 … -
Python + Django + Gunicorn on AWS: 2 workers, worker terminated due to signal 15 -> Failed to boot
I'm pretty new using django + gunicorn + aws. Im struggling to find the problem on "signal 15 from gunicorn". Below are the log file from gunicorn. https://github.com/benoitc/gunicorn/issues/2755 -
Django - Cancel one delivery but when cancelling one it cancels all the deliveries
I'm trying to cancel one "posted" delivery when the user clicks on the button "cancel", but it cancels all the posted deliveries below is the views.py views html models Here is the list of deliveries I want to cancel one delivery and it automatically moves to the "Done/Cancelled Deliveries" page. -
How to upload multiple images to a form divided into 3 tabs?
I have a form divided into 3 tabs, in tab 2 and in tab 3 you have to upload multiple images respectively. The information that I have found about it, for the most part I do not understand and the one that I have seen easily, throws me many errors, can you help me tell me what I am doing wrong? Thanks models.py class Carro(models.Model): placas=models.CharField(max_length=255) marca=models.CharField(max_length=255) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(null=True, upload_to="images/") garantia=models.ImageField(null=True, upload_to="images/") fecha_registros = models.DateTimeField(default=datetime.now, null=True) def __str__(self): return f'{self.placas} {self.marca}{self.cliente}{self.fotosCarro}{self.garantia}' \ f'{self.fecha_registros}' forms.py class CarroForm(forms.ModelForm): class Meta: model=Carro fields = ['placas','marca','cliente','fotosCarro','garantia'] exclude = ['fecha_registros'] widgets = { 'placas': forms.TextInput( attrs={ 'class': 'form-control', } ), 'marca': forms.TextInput( attrs={ 'class': 'form-control' } ), 'cliente': forms.Select( attrs={ 'class': 'form-select' } ), 'fotosCarro':forms.FileInput( attrs={ 'class': 'type-file', 'multiple': True, 'id': 'file-input', 'onchange':'preview()', } ), 'garantia':forms.FileInput( attrs={ 'class': 'type-file', 'multiple': True, 'id': 'file-inputz', 'onchange': 'previewz()', # 'id':'pro-images', # 'click': "$('#pro-images').click()", } ), 'fecha_registros': forms.DateInput( attrs={ 'class': 'form-control', } ), } views.py def create_carros(request): form = CarroForm(request.POST or request.FILES) if request.method == 'POST': form = CarroForm(request.POST or request.FILES) fotosCarro = request.FILES.getlist('fotosCarro') garantia = request.FILES.getlist('garantia') for img in fotosCarro: Carro.objects.create(fotosCarro=fotosCarro) Carro.objects.create(garantia=garantia) images=Carro.objects.all() if form.is_valid(): form.save() return redirect('carros/index.html') return render(request, "carros/carros-form-add.html", {'form': form}) -
Json transferred in javascript
jsonData = { "a":{ "b":{ "c":"d" ,"e":"f" } ,"g":{ "h":"i" ,"j":"k" ,"m":"n" } ,"l":{ "o":"p" ,"q":"r" } } } } How do you create an array starting with a with JavaScript and transfer it to the jsondata function? -
Django CASCADE deletion not working and throws IntegrityError
I'm running into this bug with cascade deletion which is frustrating as I couldn't figure out what the root cause is. I use PostgresQL and I have the following database models: class Subdomains(models.Model): subdomainid = models.AutoField(db_column='subdomainid', primary_key=True) subdomainname = models.TextField(db_column='subdomainname', unique=True, ) class Meta: managed = True db_table = 'subdomains' class Dnsdata(models.Model): dnsid = models.AutoField(db_column='dnsid', primary_key=True) dnsa = models.TextField(db_column='dnsa', blank=True, null=True) subdomainid = models.ForeignKey(Subdomains,on_delete=models.CASCADE, db_column='subdomainid') class Meta: managed = True db_table = 'dnsdata' class Issues(models.Model): issueid = models.AutoField(db_column='issueid', primary_key=True) class Meta: managed = True db_table = 'issues' class Alerts(models.Model): alertid = models.AutoField(db_column='alertid', primary_key=True) subdomainid = models.ForeignKey(Subdomains,on_delete=models.CASCADE, blank=True, null=True, db_column='subdomainid') dnsid = models.ForeignKey(Dnsdata,on_delete=models.CASCADE, blank=True, null=True, db_column='dnsid') issueid = models.ForeignKey(Issues,on_delete=models.CASCADE, blank=True, null=True, db_column='issueid') # FK can be null class Meta: managed = True db_table = 'alerts' Whenever I try to remove an object from Subdomains table as follows: Subdomains.objects.filter(subdomainid=1).delete() it throws the following error: django.db.utils.IntegrityError: update or delete on table "subdomains" violates foreign key constraint "alerts_subdomainid_be56ec78_fk_subdomains_subdomainid" on table "alerts" DETAIL: Key (subdomainid)=(1) is still referenced from table "alerts". Please note that I've used on_delete=models.CASCADE and Foreign Keys in Alerts table can be null as well. -
crontab is not working with docker django
I'm setting up the cron job in my Django project, when I go to add the corn using this command python manage.py crontab add in my docker container so I got the following error. error: /bin/sh: 1: /usr/bin/crontab: not found settings.py INSTALLED_APPS = ( 'django_crontab', ... ) # Cron Jobs CRONJOBS = [ ('0 0 * * *', 'projects.views.notifications_cron') ] and I want to run my corn job after every 24 hours at 12am midnight.