Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python FileNotFoundError even though file is in same directory
I'm trying to use pickle to load a file within the same directory but I am getting FileNotFoundError for some reason. This is my code in views.py: from django.shortcuts import render from django.http import HttpResponse from django.core.files.storage import FileSystemStorage import pickle model = pickle.load(open('braintumor.pkl', 'rb')) def say_hello(request): return render(request, 'hello.html', {'name:': 'Alisha'}) def index(request): return render(request, 'index.html', { 'a' : 1}) And this is my file structure: webapp views.py braintumor.pkl It's a django app so is more complex than this but it wasn't important to list every file and directory, there is definitely no spelling errors and the pkl file is definitely in the same directory as views.py. I also tried a file structure like this: webapp views.py models -braintumor.pkl And then I tried using the import statement: "from models import braintumor" but that didn't work because I got an error saying that there is no such file or directory 'models'. I also tried loading it with the statement: "model = pickle.load(open('models/braintumor.pkl', 'rb'))" but still get FileNotFoundError! It seems no matter what I do, python simply cannot load anything and I have no idea what to do. I see nothing wrong with any of the solutions I tried. Please help, … -
Tests - both classes share the same login code but it only works in one
I'm writing tests for locallibrary app following the tutorial on MDN. Both classes that test views share similar login code, but it only works in one class I tried finding spelling errors and comping both classes Code snippets: Login throws FAIL: class AuthorCreateViewTest(TestCase): def setUp(self): # Create two users test_user1 = User.objects.create_user(username='testuser1', password='fjo&*&d3h') test_user2 = User.objects.create_user(username='testuser2', password='J9cdj8we9') test_user1.save() # Give test_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() def test_view_url_accessible_by_name(self): login = self.client.login(username='testuser2', password='J9cdj8we9') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 200) Login works: class RenewBookInstancesViewTest(TestCase): def setUp(self): # Create two users test_user1 = User.objects.create_user(username='testuser1', password='fjo&*&d3h') test_user2 = User.objects.create_user(username='testuser2', password='J9cdj8we9') test_user1.save() test_user2.save() # Give test_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() def test_logged_in_with_permission_borrowed_book(self): login = self.client.login(username='testuser2', password='J9cdj8we9') response = self.client.get(reverse('renew-book-librarian', kwargs={'pk':self.test_bookinstance2.pk})) # Check that it lets us login - this is our book and we have the right permissions. self.assertEqual(response.status_code, 200) Here is the github link with all code in classes -
Is session always saved in Django?
The doc says below in When sessions are saved. *I use Django 4.2.1: By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted: But according to my experiment of the example in When sessions are saved, the session is always saved as shown below: # "views.py" from django.http import HttpResponse def test(request): request.session["foo"] = "bar" print(request.session.get('foo')) # bar del request.session["foo"] print(request.session.get('foo')) # None request.session["foo"] = {} print(request.session.get('foo')) # {} request.session["foo"]["bar"] = "baz" print(request.session.get('foo')) # {'bar': 'baz'} return HttpResponse('Test') Actually, I don't use the code below: request.session.modified = True And, SESSION_SAVE_EVERY_REQUEST is False by default and I don't even set it True in settings.py: SESSION_SAVE_EVERY_REQUEST = False So, is session always saved in Django? -
quickfix in django Execute multiple functions
When I run the code, it executes the command and opens the incomming file, but I cannot implement any other function. The file does not exist or cannot be opened. ` import time import quickfix import quickfix44 from django.shortcuts import render from django.shortcuts import render import threading from django.http import JsonResponse from quickfix import Message, MsgType from django.views.decorators.csrf import csrf_exempt symbol=['EURUSD', 'NZDAUD'] messages=[] messages1=[] messages2=[] should_stop_data_flow = True def messageToString(message): ............ def securityListRequest(sessionID): ............... def marketDataRequest(sessionID): ............ class Application(quickfix.Application): def __init__(self): super().__init__() def onCreate(self, sessionID): print("onCreate:") self.session_id = sessionID target = sessionID.getTargetCompID().getString() sender = sessionID.getSenderCompID().getString() return def onLogon(self, sessionID): self.sessionID = sessionID print("onLogon:", f"Session ID: {self.sessionID}") message = marketDataRequest(sessionID) print("market data request:", messageToString(message)) quickfix.Session.sendToTarget(message, sessionID) def onLogout(self, sessionID): print("onLogout..") return def toAdmin(self, message, sessionID): print("toAdmin:", messageToString(message), '\n') return def toApp(self, message, sessionID): print("toApp:", messageToString(message), '\n') return def fromAdmin(self, message, sessionID): print("fromAdmin:", messageToString(message), '\n') return def fromApp( self,message, sessionID): msg = messageToString(message) print("fromApp:", msg, '\n') def keepAlive(self): while True: time.sleep(30) def run_fix(): global app settings = quickfix.SessionSettings("CCFIX.ini") app = Application() storeFactory = quickfix.FileStoreFactory(settings) logFactory = quickfix.FileLogFactory(settings) initiator = quickfix.SocketInitiator(app, storeFactory, settings, logFactory) initiator.start() app.keepAlive() def start_fix_thread(): fix_thread = threading.Thread(target=run_fix) fix_thread.start() def fix_example_view(request): global symbol start_fix_thread() return render(request, 'show_messages.html', {'messages': messages})` -
Django on Airflow with remote logs: DAG stuck
I try running Django on Apache Airflow following this idea of a custom operator. When I use the default logging configuration, i.e. AIRFLOW__LOGGING__REMOTE_LOGGING=False, everything works as expected. However, when I now use remote logging with CloudWatch, the DAG seems to be stuck when Django starts to configure logging as invoked by django.setup(). I can confirm that logging to CloudWatch itself works as I have added a few logging events. *** Reading remote log from Cloudwatch log_group: job-sentinel-image-layer-log-group-5f303da log_stream: dag_id=clear_tokens/run_id=scheduled__2023-07-03T22_00_00+00_00/task_id=execute_clear_tokens_command/attempt=1.log. [2023-07-05, 17:23:27 CEST] Dependencies all met for dep_context=non-requeueable deps ti=<TaskInstance: clear_tokens.execute_clear_tokens_command scheduled__2023-07-03T22:00:00+00:00 [queued]> [2023-07-05, 17:23:27 CEST] Dependencies all met for dep_context=requeueable deps ti=<TaskInstance: clear_tokens.execute_clear_tokens_command scheduled__2023-07-03T22:00:00+00:00 [queued]> [2023-07-05, 17:23:27 CEST] -------------------------------------------------------------------------------- [2023-07-05, 17:23:27 CEST] Starting attempt 1 of 2 [2023-07-05, 17:23:27 CEST] -------------------------------------------------------------------------------- [2023-07-05, 17:23:27 CEST] Executing <Task(DjangoOperator): execute_clear_tokens_command> on 2023-07-03 22:00:00+00:00 [2023-07-05, 17:23:27 CEST] Started process 24150 to run task [2023-07-05, 17:23:27 CEST] Running: ['airflow', 'tasks', 'run', 'clear_tokens', 'execute_clear_tokens_command', 'scheduled__2023-07-03T22:00:00+00:00', '--job-id', '3', '--raw', '--subdir', 'DAGS_FOLDER/management_commands/src/clear_tokens.py', '--cfg-path', '/tmp/tmpkmehxuz0'] [2023-07-05, 17:23:27 CEST] Job 3: Subtask execute_clear_tokens_command [2023-07-05, 17:23:28 CEST] Running <TaskInstance: clear_tokens.execute_clear_tokens_command scheduled__2023-07-03T22:00:00+00:00 [running]> on host 147b23cea447 [2023-07-05, 17:23:28 CEST] Exporting the following env vars: AIRFLOW_CTX_DAG_ID=clear_tokens AIRFLOW_CTX_TASK_ID=execute_clear_tokens_command AIRFLOW_CTX_EXECUTION_DATE=2023-07-03T22:00:00+00:00 AIRFLOW_CTX_TRY_NUMBER=1 AIRFLOW_CTX_DAG_RUN_ID=scheduled__2023-07-03T22:00:00+00:00 [2023-07-05, 17:23:28 CEST] We are in pre-execute [2023-07-05, 17:23:28 CEST] after import of … -
Django User Avatar image is not getting reflected in media directory
I'm using django 3.2 on my GCP Ubuntu VM. My media folder as defined in my settings.py is ./media While as a user, I'm able to upload blog posts that contain images and the blog images show up inside ./media/blog but the profile picture(avatar) doesn't get uploaded to the .media/user directory. I get the following trace on my docker-compose when I click Save from my flutter front end to update the Profile picture. "PATCH /api/auth/user/ HTTP/1.1" 200 852 There is no error on my frontend so I'm troubleshooting the backend. The profile avatar details doesn't reflect even inside the auth directory under my username. Besides, On the frontend. The profile pic gets shown inside the profile box after upload but it fails(Nothing happens) when I click save and the profile box is again empty. This is something that I'm not able to figure on my own. Since this is related to both Flutter and Django , I'm uploading the avatar file flutter code below: if (avatarFile != null) { finalAvatarImage = FadeInImage( fit: BoxFit.cover, height: avatarSize, width: avatarSize, placeholder: const AssetImage(DEFAULT_AVATAR_ASSET), image: FileImage(File(avatarFile!.path!)), ); } else if (avatarUrl != null) { finalAvatarImage = Image( height: avatarSize, width: avatarSize, fit: BoxFit.cover, … -
Getting 500 internel server error while deploying django application inside digital ocean
I have been trying to deploy django application inside digital ocean ubunut vps for 12 hours. But can't solve this issue. Everything running just fine gunicorn, nginx eveyrhting looks good but still getting this error. Even tried to run it using my ip address:8000 and it ran well also. Here is the status of gunicorn: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2023-07-05 14:28:46 UTC; 1h 0min ago TriggeredBy: ● gunicorn.socket Main PID: 159720 (gunicorn) Tasks: 4 (limit: 1116) Memory: 258.2M CPU: 45.358s CGroup: /system.slice/gunicorn.service ├─159720 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application ├─159721 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application ├─159722 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application └─159723 /root/venv/bin/python3 /root/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock LeadScrapper.wsgi:application Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/chrome/webdriver.py", line 49, in __init__ Jul 05 15:16:59 scrapper gunicorn[159722]: super().__init__( Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/chromium/webdriver.py", line 51, in __init__ Jul 05 15:16:59 scrapper gunicorn[159722]: self.service.start() Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 97, in start Jul 05 15:16:59 scrapper gunicorn[159722]: self.assert_process_still_running() Jul 05 15:16:59 scrapper gunicorn[159722]: File "/root/venv/lib/python3.10/site-packages/selenium/webdriver/common/service.py", line 110, in assert_process_still_running Jul 05 15:16:59 … -
How to use the Mapbox Search API with django
I have a previous question that this question follows: How to implement a mapbox search box. So now I have implemented the search box, how do I use the API to be able to retrieve detailed information on the address on the place of interest such as longitude and latitude -
Hide fields from SearchForm depending on the request user groups
I have a StockSearchForm: class StockSearchForm(CustomForm): component__code__icontains = forms.CharField(label=_('component code'), required=False) component__name__icontains = forms.CharField(label=_('component name'), required=False) component__product__icontains = forms.ChoiceField( label=_('product'), required=False, choices=b_choice + PRODUCT_CHOICES) inventory = forms.BooleanField(label=_('to inventory'), required=False) def __init__(self, *args, **kwargs): super(StockSearchForm, self).__init__(*args, **kwargs) self.fields[ 'component__code__icontains'].widget.attrs[ 'class'] = 'form-control' self.fields[ 'component__name__icontains'].widget.attrs[ 'class'] = 'form-control' self.fields[ 'component__product__icontains'].widget.attrs[ 'class'] = 'form-control' self.fields['inventory'].widget.attrs['class'] = 'btn pull-left' self.fields['inventory'].initial = False The field that is named inventory I only need to display it if the request user has groups "Administrator" or "Purchasing". I tried many codes that I found but neither works, can someone how to do it? I tried doing if not request.user.groups.filter(name__in["Admnistrator", "Purchasing"]).exists(): del self.fields['inventory'] and even self.fields['inventory'].widget = forms.HiddenInput() but nothing works for me (I know that I'm not setting request as a parameter, but I tried setting it obviously even user as a parameter -
I see less than half of the number of push notification sent on firebase dashboard than number we actual send daily using pyfcm library
E.g. We send more than 5 lakh push notifications daily but only 1.5 lakh messages sent on that day shown in Firebase dashboard. I want to know why firebase dashboard analytics not giving correct number for messages sent daily and how can i fix this issue -
How to implement "notification" for receiving messages from a conversation partner
I have implemented a simple messenger. How can I implement a "notification" system for receiving messages from a conversation partner? For example, when User 2 sends a message to User 1, User 1 should see a notification icon indicating an unread message, and the chat with User 2 should move to the top of the list, all without page reload. I believe this can be done using signals, websockets, and Django Channels, but I'm not sure how to proceed. i tried using signals and websocket -
Django 4.2 Window + Lag function does not assess lag properly: only 0's returned
I am trying to calculate lag with Lag window function and use field reference so that I can refer to it later in Case When clause. I am using MySQL 8.0.32. Here's something similar to what I have contrived: class Foo(models.Model): bar = models.ForeignKey('self', on_delete=models.CASCADE) baz = models.IntegerField() def my_method(self): foos = self.foo_set.annotate(lag=Window( expression=Lag('baz', default=0), order_by=F('baz').asc() )).annotate(output=F('baz')-F('lag')) for i in foos: print(i.pk, i.output) # desired result. But I can't use F('output') subquery = Subquery( self.foo_set.annotate( lag=F('baz') - Window( expression=Lag('baz', default=0), order_by=F('baz').asc(), ) ).filter(pk=OuterRef('pk')).values('lag') ) foos = self.foo_set.annotate(output=subquery) reference = F('output') for i in foos: print(i.baz, i.output) # not desirable As commented, the problem with the first foos is that I can't use field reference with F. When I try, it says lag function is not for this context: (django.db.utils.OperationalError: (3593, "You cannot use the window function 'lag' in this context.'") On the other hand, for the second foos, Window function only returns 0's. With F('baz'), I get nothing subtracted from baz. Example for Extra Clarification Let's say that I have four instances of Foo: A, B, C, and D. A is the bar of B, C, and D. baz for B, C, and D is 2, 3, and 4 respectively. … -
Django: How to identify if object is connected through ManyToManyField?
A basic representation from my models: class CarType(models.Model): name = models.CharField(max_length=200) class Brand(models.Model): name = models.CharField(max_length=200) cartype = models.ManyToManyField(CarType) class Customer(models.Model): name = models.CharField(max_length=200) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) I have a search function where the CarType is readily provided. I would have this object by it's ID. The customer is connected to the brand, which has manytomany to cartype (please ignore the models in this case, they are for illustration purpose). In my query, I only want to return those customers, which are connected to a brand, which on its turn has a relation with the cartype from a many-to-many relationship. So basically; how do I filter the customers to show only those, where the brand has a relation with the cartype? What my current thought is: Is it possible to create a modelmanager of some sort, which accepts the CarType as argument and return all relevant customers Create a second model for customers, where records are stored with a foreignkey directly to cartype (perhaps trigger this when a customer is added) Add a manytomanyfield for CarType to Customer, which automatically creates all the manytomany relations based on the existing records available in brand (and run a cronjob to review/update … -
django update model and preventing full table lock
Im using django 4.0.0. I have a model with an touched column (DateTimeField) to specify when a specific row was "touched" (like the unix command). I want to write a management command that updates this column to now() like so MyModel.objects.all().update(touched=now()) but the numbers of rows is large and i DON'T want to have a full table lock for this. Is there any way to have django update the queryset in multiple batches - each batch in a DIFFERENT TRANSACTION? or is there anyway to split my queryset to do this manually? -
How to implement a mapbox search box
I am struggling to implement a single map box search box into my project. I have a form and an input box that I would like to show POI suggestions. I do not want the mapbox search box to make my webpage scroll and I have tried to control it with the html/css but I believe I have to control the search box itself but I do not know how to do this. Please help I have tried to copy this example: https://docs.mapbox.com/mapbox-search-js/example/theming/ But it still is not working because I have to use "autocomplete=street-address" this means there is no POI suggestions being shown only addresses. Finally after I have got the input of the user I would like what they click as a suggestion to be passed to the API so my backend function can get the information such as latitude and longitude -
Django admin StackedInline throws (admin.E202) 'accounts.CustomUser' has no field named 'user' error
I have a CustomUser model, and a Retailer model that holds the additional details of retailer user type. The Retailer model has a OneToOne relation to CustomUser model. There is no public user registration or signup, accounts are created by superuser. In the Django admin site, I am trying to leverage admin.StackedInline in the retailer admin page to enable superusers to create new retailer users directly from the retailer admin page. This eliminates the need to create a new user object separately in the CustomUser model admin page and then associate it with a retailer object using the default dropdown in the retailer model admin page. However, I got the below error: MODELS.PY class CustomUser(AbstractUser): """ Extended custom user model. """ uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = None # type: ignore first_name = None # type: ignore last_name = None # type: ignore name = models.CharField(_("Name of User"), max_length=150) email = models.EmailField(_("Email address of User"), unique=True, blank=False) date_modified = models.DateTimeField(auto_now=True) # Flags for user types is_retailer = models.BooleanField( _("Retailer status"), default=False, help_text=_("Designates whether the user should treated as retailer"), ) is_shop_owner = models.BooleanField( _("Shop owner status"), default=False, help_text=_("Designates whether the user should treated as shop owner"), ) USERNAME_FIELD = … -
How to upload image to cloudinary without creating a model in Django
I am building a website using Django. There is a Website and there is a server. Website communicates to server using API. I dont want the website to use any database (I want all data to be stored at the server). I want to upload images to cloudinary however couldn't figure out how to upload an image to cloudinary without creating a model in website. My website has an image upload location and when a user uploads an image, i want to upload that image to cloudinary directly and then retrieve the url of the image and send this url to server with api. Sending to server and uploading is fine, i can do that. But how can i upload to cloudinary and retrieve the url of the uploaded image in the same view function without creating a model or storing any data on the database (i will store it on the server's database) Thanks. I was able to upload images to cloudinary and retrieve the url however i was only able to do this by creating a model and saving it to the database. I don't want to create a model and save to the database. I just want … -
How to mock test a function inside save method
I want to send an email each time the status of an object was equal to 13. def save(self, *args, **kwargs): from user_profile.models import SopResumeBuy if skip_sop_resume := kwargs.get('skip_sop_resume'): del kwargs['skip_sop_resume'] if(self.status == 13): email_sender( "subject", f"email body", ) ...... the save method will call another email_sender which is a function inside another file. I want to make sure that the email will be sent.How can i mock the process of sending email? -
What causes a blank white screen in react app on the local host 3000
I am working on a web app in Django and React and when I try to run the react app on the localhost 3000, nothing is showing on the screen. It shows only a blank white screen, and the following error Failed to compile. .\src\api\api.js Cannot find file '../config.json' in '.\src\api'. What might be the problem -
Data given in django model form is not getting displayed in another page
#my Models.py file from django.db import models # Create your models here. class EmpModel(models.Model): empName = models.CharField(max_length = 20) empJob = models.CharField(max_length = 20) def __str__(self): return self.empID # myForms.py file from django.forms import ModelForm from myWebApp.models import EmpModel class EmpModelForm(ModelForm): class Meta: model = EmpModel fields = [ "empName", "empJob"] #myViews.py File from django.shortcuts import render from django.db import models from myWebApp.models import EmpModel from django.template import loader from django.http import HttpResponse from django.forms import modelformset_factory # Create your views here. from .forms import EmpModelForm def empDetails(request): if request.method == "POST": form = EmpModelForm(request.POST) if form.is_valid(): empFormSave = form.save() empInfoData = EmpModel.objects.all() return render(request, "empInfoData.html", {"empInfoData" : empInfoData}) else: form_class = EmpModelForm return render(request, "empInfo.html", {"form" : form_class}) #myCollectedDateDisplay Page <!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>Employee Information Submitted</title> </head> <body> <h2>Employee Data available in the system</h2> <p>Employee Name : {{ empInfoData.empName }}</p> <<p>Employee Job : {{ empInfoData.empJob }}</p> </body> </html> Initially I had many modelfields like positiveinteger, datetime, etc.. I was getting integrity error. So, I removed and kept only charfield. The integrity error is resolved and page is being displayed but data is showing empty I have done "python manage.py makemigrations" python … -
How can I connect google pay to my django project?
I am making a django project and I want to add a google pay system so that I can take payments and then provide them with the course. I can't find anything on internet I even asked ChatGPT and Bard but they did'nt told properly so can't do anything. -
I am integrating SAML with django using djangosaml2 and idp as okta, configured my setting.py file with SAML_CONFIG,
My settings.py is like import os BASEDIR = os.path.dirname(os.path.abspath(__file__)) SAML_CONFIG = { "strict": True, "debug": True , "service" :{ "sp": { 'name': 'XXX', 'allow_unsolicited': True, 'want_assertions_signed': True, # assertion signing (default=True) 'want_response_signed': True, "want_assertions_or_response_signed": True, # is response signing required 'name_id_format': "urn:oasis:names:tc:SAML:1.1:nameid-format:basic", "entityId": "https://localhost:8002/metadata/", "assertionConsumerService": { "url": "https://localhost:8002/?acs", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" }, "singleLogoutService": { "url": "https://localhost:8002/?sls", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" }, "NameIDFormat": "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", "x509cert": "", "privateKey": "" }, "idp": { # "entityId": "https://dev-92033760.okta.com/app/exv13qURtCj35d7/sso/saml/metadata", "entityId": "http://www.okta.com/3qURtCj35d7", "singleSignOnService": { "url": "https://dev-9203760.okta.com/app/dev-92033760_saml4july_1/exRtCj35d7/sso/saml", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" }, "singleLogoutService": { "url": "https://dev-9233760.okta.com/app/dev-92033760_saml4july_1/exka35d7/sso/saml", "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" }, }, }, 'metadata': { 'local': [os.path.join(BASEDIR, 'remote_metadata.xml')], } } but getting below after successful redirection from okta Authentication Error. Access Denied. and on logs getting Traceback (most recent call last): File "/home/zec/label-studio-project/djangosaml2/djangosaml2_venv/lib/python3.8/site-packages/djangosaml2/views.py", line 469, in post response = client.parse_authn_request_response( File "/home/zec/label-studio-project/djangosaml2/djangosaml2_venv/lib/python3.8/site-packages/saml2/client_base.py", line 773, in parse_authn_request_response raise SAMLError("Missing entity_id specification") saml2.SAMLError: Missing entity_id specification Forbidden: /saml2/acs/ -
How can I get the right Lag using Subquery, Django ORM
Using Django 4.2, MySQL 8.x I am using one model which refers to itself with field name supertask. self.accumulative indicates that proportion field is recorded in accumulative manner. If True, I would like to get lag to get proper value. For example, say task A has subtasks B, C, and D, with 2, 3, and 4 for their proportion. A.accumulative is True. So, I would like to use F('proportion') - F('lag') for calculating weighted_achievement. However, I get 0 for lags (supposed to have 2, 1, and 1, respectively). Here's the code: def assess_achievement(self): if self.subtasks.exists(): subtasks = self.subtasks.order_by('proportion') print(subtasks.query) proportion = F('proportion') proportion_total = Sum('proportion', output_field=FloatField()) if self.accumulative: subquery = Subquery( self.subtasks.annotate( lag=Window( expression=Lag('proportion', offset=1, default=0), order_by=F('proportion').asc(), partition_by=F('proportion') ) ).values('lag')[:1] ) subtasks = subtasks.annotate(lag=subquery) print(subquery.query) for i in subtasks: print(i.proportion, i.lag) # 0 proportion -= F('lag') proportion_total = Max('proportion', output_field=FloatField()) weighted_achievement_total = subtasks.annotate( weighted_achievement=Case( # pseudo_achievement When(completed=True, then=proportion), default=F('achievement')*proportion, output_field=FloatField(), ) ).values('weighted_achievement').aggregate( weighted_achievement_total=Sum( 'weighted_achievement', output_field=FloatField() ) ).get('weighted_achievement_total', 0) Why can't this code get the right lag and how can I fix it? -
Does subprocess.Popen.wait deadlock when using file type for stdout?
Any help is appreciated. I have a custom Django command and a method like the one below: def read_status_to_list(self) -> List[str]: with open('git.txt', 'w+') as temp: status = subprocess.Popen(['git', 'status'], stdout=temp) status.wait() statuses = [line.split()[-1] for line in temp.readlines() if 'modified:' in line ] # remove file when done if os.path.isfile('git.txt'): os.remove('git.txt') return statuses However, statuses is always empty even when git status produces a number of modified modules not added yet. I noticed a warning in the wait method: Warning: This will deadlock when using stdout=PIPE and/or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that. Is this warning related to the problem, and how can I successfully complete this task using subprocess? Thank you. -
Django Interview Question for showing the result in coding
While showing my project by sharing the screen, I explained my project which is on Student Management System to interviewer but he was kept asking me about show me the result in code. I'm fresher and I haven't used python Django much so can anyone explain me what result should I show to the interviewer? I have done that project by watching tutorials on Student Management System. What do they expect us to show? YouTube Link - https://youtu.be/FMPpaTFdL2k I explained him the overall working of code. I showed him backend admin panal and also python code fies urls settings models views. But he was keep repeating show me the result. Please explain me someone how can I show the result.