Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dependent/Chained Dropdown List with Django not working
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I follow the Article (https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) but not working. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. Because he cannot find me gruppo_single and therefore does not start the rescue if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda … -
How to update user status (multiple user at a time used checkall ids)?
my concern is user is selecting all id's and update the user status(eg :status='assign')? im getting this url with multiple ids(when i checkall) http://127.0.0.1:9000/assignagent/id/20,21,22,23,24,25,26,27 this is my actual url path('assignagent/id/int:pk',views.SciBulkAssignView.as_view(),name='assignagent') views.py class SciBulkAssignView(UpdateView): login_url = 'login' model = Sci1stKey fields = ['id','projectId','status'] initial = {'status': 'assign'} template_name = 'all_adminhtmlpages/updatesci_details.html' success_url = reverse_lazy('reassigntickets') and another view i tried also # def assignagent(request, id): top = get_object_or_404(Sci1stKey, id=id) top.status ='assign' top.save(update_fields=['status']) return redirect('assigntickets') this is my html and js code im selecting all ids need to update the status of id( checkboxes) <input type="button" class="main" value="selectall" onclick="checkAll()" name="inputs"> <button type="button" value="deselectAll" class="main" onclick="uncheckAll()">Clear</button> <script type="text/javascript"> // Select all check boxes : Setting the checked property to true in checkAll() function function checkAll(){ var items = document.getElementsByName('brand'); var checkedValue = []; for (var i = 0; i < items.length; i++) { if (items[i].type == 'checkbox') items[i].checked = true; checkedValue.push(items[i].value) ; } console.log(checkedValue); url = '/assignagent/id/' + checkedValue; window.location.replace(url); } // Clear all check boxes : Setting the checked property to false in uncheckAll() function function uncheckAll(){ var items = document.getElementsByName('brand'); for (var i = 0; i < items.length; i++) { if (items[i].type == 'checkbox') items[i].checked = false; } } </script> -
How to get and render out foreign key objects depending on a boolean in the base model?
I do have two models with a foreignkey relationship: class Poller(models.Model): """ Main Model to describe Poller objects """ created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(Account, on_delete=models.SET(get_deleted_user)) is_active = models.BooleanField(default=True) headline = models.CharField(max_length=100) class PollerBookmark(models.Model): """ A model that contains bookmarks made to a poller """ poller = models.ForeignKey(Poller, on_delete=models.CASCADE, related_name='PollerBookmark') user = models.ForeignKey(Account, on_delete=models.CASCADE) is_bookmarked = models.BooleanField(default=True) created_on = models.DateTimeField(auto_now_add=True) I now want to render out all Poller objects that have is_bookmarked = True in the PollerBookmarkmodel. # views.py .. poller_bookmarks = PollerBookmark.objects.filter(user__username=username).filter(is_bookmarked=True) context = { 'poller_bookmarks': poller_bookmarks } .. # Template {% for poller_bookmark in poller_bookmarks %} {{ poller_bookmark.poller.headline }} {% endfor %} But the headline isn't rendered out, although the context contains a legit queryset of PollerBookmarks. -
Use one modal for all entries javascript
I'm trying to send the id of the object that we select to edit in the form action. let edit_buttons = document.querySelectorAll(".edit-modal"); for(var i = 0; i < edit_buttons.length; i++) { edit_buttons[i].addEventListener("click", function(e) { console.log(`${this.getAttribute("data-id")}`) console.log(`{% url 'users:edit' pk=1 %}`) document.querySelector("form").setAttribute("action", "{% url 'internal-users:edit-product' pk=${this.getAttribute("data-id")} %}"); }) } {% for object in object_list %} <tr> <td class="border-0 size-13 text-gray-dark">{{object.name}}</td> <td class="border-0 size-13 text-gray-dark">{{object.surname}}</td> <td class="border-0 size-13 text-gray-dark">{{ object.type }}</td> <td class="border-0 size-13 text-gray-dark"> {{ object.status_label }} </td> <td class="border-0 size-13 text-gray-dark"> <button class="btn btn-gray text-gray size-13 edit-modal" data-id="{{ object.pk }}" data-toggle="modal" data-target="#editModal">Edit</button> </td> <td class="border-0 size-13 text-gray-dark"> <button class="btn btn-gray text-gray size-13" onclick="location.href='{% url 'internal-users:products' pk=object.pk %}'">Details</button> </td> </tr> {% endfor %} <form method="POST" action=""> {% csrf_token %} <input type="hidden" id="object_id"> <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModal" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content p-4"> <div class="modal-header border-0"> <h5 class="modal-title size-20" id="exampleModalLabel">Edit Product</h5> </div> <div class="modal-body"> <div class="row no-space"> <div class="col-12"> <label>Name</label> <input type="text" name="name" id="name" value="Name" /> </div> </div> <div class="row no-space mt-3"> <div class="col-12"> <label>Status</label> <input type="radio" name="status" id="active" /> <label for="active" class="inline">Active</label> <input type="radio" name="status" id="inactive" class="ms-2" /> <label for="inactive" class="inline">Inactive</label> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn" data-dismiss="modal">Cancel</button> <button type="submit" class="btn btn-yellow new-button">Save</button> </div> </div> … -
Time difference between extraction of encrypted and unencrypted data
Suppose I have two models class Student(models.Model): name = models.CharField(max_length = 60,blank= False,) subject = models.CharField(max_length = 60,blank=False) marks = models.IntegerField(default =0,blank=True) teacher = models.CharField(max_length = 60,blank=False) and another model class EncryptedStudent(models.Model): name = models.CharField(max_length = 60) subject = pgcrypto.EncryptedCharField(blank=False) marks = pgcrypto.EncryptedIntegerField(default = 0,blank= True) teacher = pgcrypto.EncryptedCharField(blank=False) Now I want to query on the database. Will there be any time difference? How to evaluate for any time difference? I am using pgcrypto module . Here is the github link. -
Django Form 'readonly' widget invalidates 'initial'
In short: I have an app where a user inputs workouts. Before they add exercises to their workout, they must submit a 'readiness' questionnaire with 5-10 questions, rating each low-high. Models: Model with the question set (ReadinessQuestion), and model that stores readiness_question, rating and the Workout it belongs to (WorkoutReadiness). Form: I've made a ModelForm into a formset_factory. When I set the 'readiness_question' form field widget to be 'readonly', this makes my form invalid and ignores my 'initial' data View: I want to create a view where the 5-10 Questions from ReadinessQuestion are in a list, with dropdowns for the Answers. I have set initial data for my form (each different question) the user selects the 'rating' they want for each readiness_question a new Workout is instantiated the WorkoutReadiness is saved, with ForeignKey to the new Workout How my page it looks now (nearly how I want it to look): https://imgur.com/a/HD1l3oe The error on submission of form: Cannot assign "'Sleep'": "WorkoutReadiness.readiness_question" must be a "ReadinessQuestion" instance. The Django documentation is really poor here, widget=forms.TextInput(attrs={'readonly':'readonly'}) isn't even on the official Django site. If I don't make the readiness_question 'readonly', the user has dropdowns which they can change. #models.py class Workout(models.Model): user … -
store API data to the database in Django [closed]
I'm trying to save the retrieve API data from the endpoint to the database in Django but I'm getting as error as TypeError at / string indices must be integers when I print the API data it shows "class" Views.py def homeview(request): userb = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() print(type(table_data)) data = json.dumps(table_data) print(data) new_data={ "stage" : data["stage"], "region" : data["region"], "area" : data["area"] } user = Userbase.objects.create( **new_data) user.save() return render(request, 'home.html', {'userb':userb,'table_data':table_data}) API data: [{'id': 163, 'stage': 'stage1', 'region': 'NORTHAMERICA', 'area': 'US'}] -
Django Model Admin
How I can display in the Model Admin only the login user and not all Users? Models.py user = models.ForeignKey(User,db_column="user",null = True, on_delete = models.SET_NULL) Admin.py def get_queryset(self, request): qs = super(Museum_ItemAdmin, self).get_queryset(request) if request.user.is_superuser: return qs return qs.filter(user=request.user) The problem is when logging in as "Peter" I can see and manage all users. The question is how I can see only Peter and not be able to see or change any other users? Thanks a lot in advance -
django:How to use "objects.all()" and "for" in async
I want to access the information of the model periodically using asyncio and threading. After fetching the model data with objects.all() in the async coroutine, an error occurs when running the for loop. You cannot call this from an async context - use a thread or sync_to_async. ---code--- [task.py] asyncio.run_coroutine_threadsafe(chat.handle(), loop.LOOP) [chat.py] async def handle(): while True: users = user.objects.all() for user in users: print(user.user_id) await asyncio.sleep(60) ---Details--- [Website/loop.py] import asyncio LOOP = None def run_loop(): global LOOP LOOP = asyncio.new_event_loop() LOOP.run_forever() [Website/__init__.py] from Monitoring import loop import threading import sys threading.Thread(target=loop.run_loop).start() When you access the test page, check() in task.py will work. [Monitoring/task.py]] import asyncio from Monitoring import chat from Website import loop def check(): asyncio.run_coroutine_threadsafe(chat.handle(), loop.LOOP) [chat.py] import asyncio from Monitoring.models import User async def handle(): while True: users = User.objects.all() for user in users: print(user.user_id) await asyncio.sleep(60) -
How to force URL with django rest framework?
I use an apache container which acts as a loadbalancer and redirects the flow to 2 apache wsgi. I use django-rest-framework on the 2 apaches. I have a problem to get the files. Indeed, the api returns me: { avatar: http://127.0.0.1:8000/media/avatars/2.jpg } Instead of http://127.0.0.1:8000/, I want the api to return https://api.myservice/ How to force the url ? -
hosting django with angular on digitalocean with nginx
I have a Django-Angular project which I want to deploy on DigitalOcean with Nginx and I am successful in running the whole setup, but I have some doubts that I want to clear before finally proceeding with the solution. This is what I've done so far Currently, I've gunicorn.sock and gunicorn.service files to set up gunicorn and passed this file in Nginx's location block location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } The Django project is running without any issue. For the angular project, I am using supervisor, inside /etc/supervisor/conf.d/my_angular_app.conf, I've set up configurations for the angular app [program:my_angular_app] command=ng serve directory=/path/to/angular/project/ user=www-data autostart=true autorestart=true stdout_logfile=/path/to/angular/project/logs/angular.log redirect_stderr=true this starts the angular project on localhost:4200 Now, I've added another location block inside my Nginx file to proxy pass the requests to angular location / { include proxy_params; # this will pass the requests to angular project proxy_pass http://localhost:4200; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /api { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # this will proxy pass the request to gunicorn which is running django app } This whole setup … -
Django Form inputs show up as blank in Django Admin
So I'm creating software for an ice cream company, and I'd like to get the customer's information from the order entry html. But when I fill out the first name, last name, shipping address, etc, it shows up in Django admin as blank. Here's my code: forms.py from django import forms from orderentry.models import customerInfo, orderInfo class customerForm(forms.ModelForm): firstName = forms.CharField(max_length=30) lastName = forms.CharField(max_length=30) shippingAddress = forms.CharField(max_length=60) billingAddress = forms.CharField(max_length=60) class Meta: model = customerInfo fields = ('firstName','lastName','shippingAddress', 'billingAddress',) views.py from django.http import HttpResponse import orderentry from orderentry.forms import customerForm def getCustomerInfo(request): form = customerForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() orderentry.forms.firstName = form.cleaned_data['firstName'] orderentry.forms.lastName = form.cleaned_data['lastName'] orderentry.forms.shippingAddress = form.cleaned_data['shippingAddress'] orderentry.forms.billingAddress = form.cleaned_data['billingAddress'] return redirect('/orderentry') else: form=customerForm() return render(request, 'orderentry.html', {'form' : form}) orderentry.html <p> <!--Basic Customer Information--> <form method = "post"> {% csrf_token %} {{ form.as_p }} <button type = "submit">Place your order!</button> </form> </p> Here's what it looks like in Admin It is blank in the python shell as well. I'm new to Django. Any help is appreciated. Thanks. -
passing 2 different models from 2 different apps to another app table
app1/model class Deployment(models.Model): uid = models.CharField(max_length=255, blank=True) target = models.CharField(max_length=255) name = models.CharField(max_length=255, blank=True) description = models.TextField(blank=True) app2/model class Account(models.Model): name = models.CharField(max_length=255, blank=True) file_name = models.CharField(max_length=255, blank=True) national_id = models.CharField(max_length=255, default="") app3/views.py class IndexView(LoginRequiredMixin, ListView): model = AccountRecord template_name = "tableview/table_view.html" paginate_by = 25 def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['deployment'] = Deployment.objects.all() return context app3 html template <table class="table card-table table-vcenter text-nowrap"> <thead> <tr> <th>Deployment</th> <th>Account</th> <th>National ID</th> <th>Filename</th> </tr> </thead> <tbody> {% for account in object_list %} <tr> <td>DEPLOYMENT.NAME HERE!</td> <td>{{ account.name }}</td> <td>{{ account.national_id }}</td> <td>{{ account.file_name }}</td> </tr> {% endfor %} </tbody> </table> I am trying to pass data from these 2 model to another apps html template. with my current app3/views.py the table only show blank column even after i put {{ deployment.name }} can anyone point out how to do it correctly. -
Forbidden error from Postman request to Django
I have the url of login/ to login to my web But when i tried to do the same thing on Postman, it failed by returning me 403 Forbidden. How come? From the traceback, it says Forbidden (CSRF token missing or incorrect.): /login/ . But when i tried it in my web browser, I am able to access the web page and even login. Is there something I am doing wrong? Postman: Traceback: -
problems dropdown filter saving data in the database but return error
I have a problem with a select that filters the other. I did all the filtering correctly from the frontend point of view but in the backend I can not save the data. This is the error: select a valid choise. That choice is not one of the available choices. I follow the Article (https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html) but not working. I think the problem is in the fact of the form as it does not find 'group_single' that I pass through post in my views. models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = True, null = True ) dati_esercizio = models.ForeignKey( Esercizi, … -
How to add date-time arguments to django URL tag
I am trying to get this URL in my template. path('show_date/<int:year>/<int:month>/<int:date>/',show_date,name='show_date'), My template <a href="{%url 'diary:show_date'{{date|date:'Y'}} {{date|date:'m'}} {{date|date:'j'}} %}">{{date}}</a> returns this error Could not parse some characters: 'diary:show_date'|{{date||date:'Y'}} Please help me fix this issue -
How to automatically run all django-crontab jobs?
I'm trying to schedule some work in my Django app with django-crontab -library. I've set up a job in my settings.py like this: CRONJOBS = [ ('*/1 * * * *', 'test_app.cron.my_scheduled_job') ] This is my cronjob function: def my_scheduled_job(): print("HELLO FROM CRONJOB") I'm using docker-compose to run the app and first I tried starting it with command: bash -c "python manage.py crontab add && python manage.py runserver 0.0.0.0:8000". This didn't do anything, so next I tried this: bash -c "python manage.py crontab add && python manage.py crontab run 874ec9a239dc8b28ca961ecd41c5fa60 && python manage.py runserver 0.0.0.0:8000". This runs the job correctly but only once. So my question is, how do I run the job automatically every minute after starting the server? -
Configure django logger to perform write logs to seperate file every 24hrs
I am using basic logging functionality of django. I have configured logger as follow. What I need is , I want to create separate file every 24hrs in logs directory so that all the logs will be written in date wise log files. LOGGING ={ 'version':1, 'disable_existing_loggers': False, 'formatters':{ 'simpleRe': { 'format': '[{levelname}] [{asctime}] [{module}] {process:d} {thread:d} {message}', 'style': '{', } }, 'handlers':{ 'to_file':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/debug.log', 'formatter':'simpleRe', }, }, 'loggers':{ 'django':{ 'handlers':['to_file'], 'level':'DEBUG' } }, } I also want file names should be something like 'debug_26102021.log' etc. -
How to call API in Django views
I wanted to call the API in Django views and want to render into html template but I couldn't able to pass the API.I have tried different way views.py def homeview(request): userbase = Userbase.objects.all() table_data= requests.get('http://127.0.0.1:1500/api/').json() if request.method == 'POST': userb = Userbase() userb.company_code = request.POST.get('company_code') userb.Area = request.POST.get('area') userb.country = request.POST.get('country') # userb.Netdue_Date = request.POST.get('datefilter') userb.From_Date = request.POST.get('from_Date') userb.To_Date = request.POST.get('to_Date') userb.Predicted_Paid_days = request.POST.get('Predicted_Paid_days') userb.PBK_Desc = request.POST.get('PBK_Desc') userb.Vendor_Name = request.POST.get('Vendor_Name') userb.Reference = request.POST.get('Reference') userb.Payment_Term = request.POST.get('Payment_Term') userb.save() return render(request, 'home.html', {'userbase':userbase, 'table_data':table_data}) return render(request, 'home.html', {'table_data':table_data}) -
How can I make my Django app scalable for uploading CSV File?
I want to upload a big csv file (40MB). Now for 1 MB file it is taking almost 1.5 minutes and I think it's not good enough for me. I want to make it so fast. I used bulk create instead of create function but what I notice is that both are taking same amount of time. How can I make it fast? Which procedure is good enough for uploading big csv? Can I give the to django Celery for uploading big csv. #this is my code def upload_file_view(request): start_time = datetime.now() form = CsvModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CsvModelForm obj = Csv.objects.get(activated=False) with open(obj.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i == 0: pass else: print(row) date = row[0] appl_open = row[1] appl_high = row[2] appl_low = row[3] appl_close = row[4] appl_volume = row[5] appl_adjusted = row[6] dn = row[7] mavg = row[8] up = row[9] direction = row[10] Data.objects.create( date = date, appl_open = appl_open, appl_high = appl_high, appl_low = appl_low, appl_close = appl_close, appl_volume = appl_volume, appl_adjusted = appl_adjusted, dn = dn, mavg = mavg, up = up, direction = direction ) obj.activated = True … -
How to create endpoint admin/advisor in a Djangi API
Someone please help me in understanding how to create an endpoint admin/advisor in Django API. Since /admin/ is in Django is inbuilt endpoint how can I add advisor to it. See the photo please. -
Django javascript redirect using id
We are trying to redirect to our checkout.html page which requires an id in its arguments to get to, but we are trying to get to it using Javascript. In out store.html page {% for item in product %} <div class="col-md-3"> <div class="card" style="width: 90%; margin: 5px 5px;"> <a href="Product/{{item.id}}"><img src="{{item.image.url}}" class="card-img-top"></a> <div class="cart-footer text-center"> <button onclick="redirect()">Order</button> </div> </div> </div> {% endfor %} <script> function redirect() { var url = "{% url 'Checkout' %}"; var id = $(this).item('id'); window.location.href = url + "/" + id; } </script> We know we can just use a regular button like <button onclick="window.location.href='Checkout/{{item.id}}'">Order</button> Which is how we had it before, but we're trying to get it through Javascript for future use How do you get a specific objects' id in javascript? urls.py path('', views.Store, name= "Store"), path('Checkout/<id>', views.createlocation, name="Checkout"), path('Product/<id>', views.product_details, name="Product") -
Django Postgresql Error in Production (quiz.models.Question.DoesNotExist:)
I am creating a quiz application using a guide. My application works perfectly fine in development with both sqlite3 and postgresql databases. But when pushed to production, I am faced with errors using a postgresql database. So I tried using my development sqlite3 database in production to test things out. My sqlite3 database works fine in production, but postgresql does not work in production. Initially, I thought the error is on the views level, but now I am seeing the error coming from the postgresql. Could be errors in my views or models schema. I really can't tell. The corresponding error I get when using a postgresql database in production using a linux server with gunicorn and nginx is here below, and the whole models design and views are here below too. Thanks, I appreciate your time in giving me a suitable answer to my question. models.py from django.db import models import random from account.models import Profile from django.urls import reverse import datetime from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField class PublishedBookManager(models.Manager): def get_queryset(self): return super(PublishedBookManager, self).get_queryset().filter(publish_book=True) class Book(models.Model): name = models.CharField(max_length=120) description = models.TextField() created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL) number_of_questions = models.IntegerField() number_of_sections = models.IntegerField() time = … -
Django How to update some specific fields data after input from another model using signals
I have some problem with django signals. I wanna update PermohonanWP status model fields from 'PROSES' to 'SUCCESS' after I Input data to PenelitiPemindahanWP. (Suppose i have already input data to PermohonanWP model with status = 'PROSES') here my model.py class PermohonanWP(models.Model): npwp = models.CharField(max_length=15, null=False) nama = models.CharField(max_length=100, null=False) status = models.CharField(max_length=20, null=True) class PenelitiPemindahanWP(models.Model): permohonan_pemindahan = models.ForeignKey(PermohonanWP, on_delete=models.CASCADE) nomor_lhp = models.IntegerField(null=True) nomor_st = models.CharField(max_length=50, null=True) here my signals i input it in model.py @receiver(post_save, sender=PenelitiPemindahanWP, dispatch_uid="update_permohonan_id") def update_permohonan(sender, instance, **kwargs): pemohon = PermohonanWP.objects.get(id=instance.permohonan_pemindahan) pemohon.status = "SUCCESS" pemohon.save() I wanna update the status field from PermohonanWP but whenever i submit saved button, it not saved and not update the fields. -
Django axes resets cool off the moment another failed login occurs
Currently, django axes will reset the cool off timer to the latest time a failed login attempt happens eg. after 3 login failed login attempts axes will lock out the user account for 15 minutes until 1015am(unlock at 1030am). If i attempt a 4th time at 1020am it will extend the lockout to 1035am. Is there anyway to modify axes so that it will not reset the cool off time on login attempt failure?