Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Download a video captured through a webcam in Django
I'm currently working on a project where I capture video through the webcam in the frontend and send it via WebSocket to Django for downloading. This is my WebSocket consumer code. import base64 import json import os from channels.generic.websocket import AsyncWebsocketConsumer from django.conf import settings from api.models import * import tempfile from django.core.files import File from moviepy.editor import VideoFileClip class VideoConsumers(AsyncWebsocketConsumer): async def save_video(self, patient_id, exercise_name, exercise_type, video_data): binary_data = base64.b64decode(video_data) print(binary_data) temp_path = tempfile.gettempdir() with open(temp_path + '/video.mp4', 'wb') as wfile: wfile.write(binary_data) score = 0 correctPic = Correctpic.objects.filter(exercisename=exercise_name, exercisetype=exercise_type).first() patient = Patient.objects.filter(id=patient_id).first() with open(temp_path + '/video.mp4', "rb") as file: form = Patientpic() file_obj = File(file) form.picturefilename = file_obj form.score = score form.correctpicid = correctPic form.patientid = patient form.save() file_name = form.picturefilename clip = VideoFileClip(file_name) duration = clip.duration clip.close() print(duration) async def connect(self): print("웹소켓에 연결되었습니다.") # websocket 연결 await self.accept() await self.send(text_data=json.dumps({ 'message': "socket connected" })) async def disconnect(self, close_code): print("해제됩니다.") if close_code == 1000: await self.close() async def receive(self, text_data=None, bytes_data=None): data = json.loads(text_data) patient_id = data['patient_id'] exercise_name = data['exercise_name'] exercise_type = data['exercise_type'] video_data = data['video_data'] await self.save_video(patient_id, exercise_name, exercise_type, video_data) await self.send(text_data='Video saved successfully.') Although the video is being downloaded, when I try to output its length, I … -
Check if value exists, if so, add value to existing value
For a small app im building I want to do the following: Check if there already is a record with this spirit for the selected account. If so, add the amount value to the existing record. If not, add new record. I am using crispy forms to display the form and use a formset to dynamically add extra items. I'm pretty sure I need to do this check after the if form.is_valid(): but I do not know how. Is this correct? And if so, how do I do this? See my Model here: class Spirits(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Account(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): return reverse("forecast:account_detail", kwargs={"pk": self.pk}) class VolumeItem(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) spirit = models.ForeignKey(Spirits, on_delete=models.CASCADE) amount = models.IntegerField() def __str__(self): return f"{self.account}, {self.spirit} - {self.amount}" And my forms.py here: class VolumeForm(forms.ModelForm): class Meta: model = VolumeItem fields = ('spirit','amount') ItemForecastFormSet = inlineformset_factory( Account, VolumeItem, form=VolumeForm, min_num=1, extra=0, can_delete=False ) class FormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super(FormSetHelper, self).__init__(*args, **kwargs) self.layout = Layout( Div( Row( Column('spirit', css_class='form-group col-md-6'), Column('amount', css_class='form-group col-md-6'), ), Row( Submit('submit', 'Add', css_class='my-3 btn btn-secondary') ) ) ) My view currently looks like this: def account_detail_view(request, pk): … -
Creating e-commerce website to master frontend + backend
i m a normal reactjs developer ( frontend) and a intermediate django developer. I have planned a very complex e-commerce project in a markdown file. Basically i wanna create this as a personal project to master some technologies like ( Frontend, Backend, Postgresql) i have some options and i confused between them. Please explain me that what stack is best for my learning project and why should I use that instead of two others 1: Remixjs or Nextjs ( Fullstack ) 2: React (Vite) + React Router + Express + Postgresql 3: React (Vite) + React Router + Django + Postgresql -
How to get the all descendants of a node including itself with Django treebeard?
I have Category model extending MP_Node with Django treebeard as shown below: # "models.py" from django.db import models from treebeard.mp_tree import MP_Node class Category(MP_Node): name = models.CharField(max_length=50) node_order_by = ('name',) def __str__(self): return self.name Then, I could to get all descendants of a category not including itself with get_descendants() using Django treebeard as shown below: categories = Category.objects.get(name="Food").get_descendants() print(categories) # <MP_NodeQuerySet [<Category: Meat>, <Category: Fish>]> But, when I tried to get all descendants of a category including itself with get_descendants(include_self=True) using Django treebeard, I got the error below as shown below: categories = Category.objects.get(name="Food").get_descendants(include_self=True) print(categories) # Error TypeError: get_descendants() got an unexpected keyword argument 'include_self' Actually, I could get all descendants of a category including itself with get_descendants(include_self=True) using Django mptt as shown below. *I switched Django mptt to Django treebeard because Django mptt is unmaintained: categories = Category.objects.get(name="Food").get_descendants(include_self=True) print(categories) # <TreeQuerySet [<Category: Food>, <Category: Meat>, <Category: Fish>]> How can I get the all descendants of a category including itself with Django treebeard? -
Establish one to one relationship through the Django Admin tool
I am updating a system and am taking the opportunity to revamp a number of things but want to preserve a few fields from the old Users table. I have established a profile in the new project and want to link it to the legacy users table through a one-to-one relationship, chiefly so I can leverage things that are linked to the old uid. I have the following in models.py: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) first_name = models.CharField(max_length=20, help_text='Enter your first name.', blank=False) last_name = models.CharField(max_length=20, help_text='Enter your last name.', blank=False) class LegacyUser(models.Model): legacy_id = models.CharField(max_length=10, null=False) legacy_email = models.CharField(max_length=50, blank=True, null=True) legacy_current_user = models.OneToOneField(Profile, null=True, on_delete=models.PROTECT) In admin.py I have: from django.contrib import admin from .models import Profile, LegacyUser # Register your models here. class LegacyAdmin(admin.StackedInline): model = LegacyUser @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'first_name','last_name'] raw_id_fields = ['user'] inlines = [ LegacyAdmin ] Right now I can see the legacy table in the admin tool but can't appear to make the relationship between the old and the new. In an ideal world, I would like to be able to put in a legacy uid, have it populate the fields in the rest of the subform (for a … -
AWS EC2 Problems
**I cant seem to dowload and connect MySQl connector and workbench to the EC2 instance. Im using the AWK Linux server which means the console is remote on my mac terminal. Ive tried pip3, python3, sudo and dnf. my linux service does provide the directory for instillation but im not sure why it wont download them. the errors I get when trying are saying I cant download it because I need prerequisite but the prerequisite's I cant get cause they're also not downloading. Im new to coding and its my first project where Im using aws. shouldnt RDS connect MySQL to the EC2 instance? Why does the EC2 need to connect twice? I connected RDS with MySQL, and connected that to my instance but it still wont connect.... mhmmmmmmm** HELP (PS this is a coding question dont report it) I tried to connect MySQL to EC2 but it wont connect. I did connect it to RDS but it wont. (I also greated a repository in github too and connected my project thorugh that to EC2 it still didnt work -
can't connect websocket django channels
(index):28 WebSocket connection to 'ws://127.0.0.1:8000/niwera/stories/1/' failed: when im in http://127.0.0.1:8000/niwera/stories/ and i click "entrar na história (join story)" this error appears in my dev tools console, but python django terminal return 200/300. here is my codes: ASGI: import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import niwera_rpg.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'niwera.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter(niwera_rpg.routing.websocket_urlpatterns) }) settings.py ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'niwera_rpg', 'channels' ] CHANNEL_LAYERS = { 'default': { 'BACKEND': "asgi_redis.RedisChannelLayer", 'CONFIG': { 'hosts': [('localhost', 6379)], }, 'ROUTING': 'niwera_rpg.routing.channel_routing', }, } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'niwera.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'niwera.wsgi.application' urls.py (project) urlpatterns = [ path('admin/', admin.site.urls), path('niwera/', include('niwera_rpg.urls')) ] stories.html <body> <div class="container"> <h1>Histórias Disponíveis:</h1> {% for story in stories %} <div class="card mb-3"> <div class="card-body"> <h5 class="card-title">{{ story.title }}</h5> <p class="card-text">{{ story.description }}</p> <a href="#" class="btn btn-primary" onclick="joinStory({{ story.id }})">Entrar na História</a> </div> </div> {% endfor %} </div> <script> function joinStory(storyId) { console.log(`Joining story ${storyId}...`); const socket = new WebSocket( `ws://${window.location.host}/niwera/stories/${storyId}/`); socket.onopen = … -
Django app page with Daphne asgi won't load after Google Cloud App Engine deployment
Receiving this error message ModuleNotFoundError: No module named 'trip_tracker_project' in the Google Cloud App Engine logs when trying to launch the application after deployment. There may be an issue with the asgi daphne spin up (the app uses websockets and webRTC)... the initial local server spin up of daphne was tricky There could also be some naming confusion. The main root directory (where manage.py sits) is trip_tracker_project and is found here: Desktop/trip_tracker_project However the “project” directory (where settings.py sits), is called trip_tracker, is a child of the trip_tracker_project directory, and sits here: Desktop/trip_tracker_project/trip_tracker I've been going over the ASGI file and Settings.py, and wondering if the app.yaml file at line 3 entrypoint may have an issue: runtime: python310 instance_class: F2 entrypoint: daphne -u /tmp/daphne.sock trip_tracker.asgi:application automatic_scaling: target_cpu_utilization: 0.65 min_instances: 1 max_instances: 15 env_variables: DJANGO_SETTINGS_MODULE: "trip_tracker.settings" PYTHONPATH: "/app" How can I figure out what is causing this error? Previously I: —removed the google-cloud-sdk from the root directory —updated the app.yaml file to include: PYTHONPATH: "/app" changed line 7 in the asgi.py file: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import video_chat.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'trip_tracker.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( video_chat.routing.websocket_urlpatterns ) … -
Django ASGI vs WSGI performance
I am trying to test the performance difference in ASGI and WSGI servers when there are i/o bound functions. I am going to receive streaming responses from 3rd party APIs and then stream them back to client, I am planning on using StreamingHttpResponse of Django. I created two test views, one async one sync, and used time.sleep and asyncio.sleep functions to simulate these web requests that will take a long time to complete. This is the async view: async def async_view(request): async def generate_response_data(): for i in range(10): await asyncio.sleep(1) yield f'{i} ' response = StreamingHttpResponse( generate_response_data(), content_type='text/event-stream' ) return response And this is the sync view: def sync_view(request): def generate_response_data(): for i in range(10): time.sleep(1) yield f'{i} ' response = StreamingHttpResponse( generate_response_data(), content_type='text/event-stream' ) return response I tried to load test these two endpoints to see the performance difference. I ran sync view with Django's builtin development server and async view with uvicorn. I used apache benchmarking tool for load testing. I used this command ab -c 500 -n 1000 <endpoint> meaning 500 concurrent request and total of 1000 requests. ASGI server resulted in 35 requests per second, and WSGI server 42 requests per second. Every article I read … -
Django ORM and python gRPC now playing nicely in UnitTest
Been stuck for a while, appreciate any insight here. We're a kubernetes shop that runs grpc for our microservices. Recently I've been trying to use Django ORM with grpc for a new project. I'm trying to write unittests that hit the gRPC endpoints, and verify that data has been correctly stored into the DB. The endpoint I'm hitting does the following: Does a lookup based on the request (think of this like an authentication step) Uses the result of the lookup + the request to create a new ORM object. Saves that ORM object. In order to test this, in my unittest I first pre-load some data into the DB during the setUp method, and then run the rest of the test. This to ensure that step (1) works as intended. The issue I'm seeing - inside of the gRPC method, it doesn't find this preloaded data. However, inside the unittest I'm able to verify that the data exists. To further debug, I also printed out the "DATABASES" setting from my settings.py file, and verified that it's what I expect - it points to a local sqlite table (my unittest is also pointing to this same sqlite file). What's weird … -
Django dividing polls into answered and unanswered
Okay so I have two models 'Question' and 'Answer'. Of course the answer has foreign keys 'user' and 'question'. The list of all the polls worked fine but now Im trying to pass the polls inside two lists: 'answered' and 'unanswered' so I could list the polls in two tables and user could see which polls hes got left. Basically, I used a simple for loop and it only passes answered questions correctly while it wont pass unanswered questions. I would love to find out why and perhaps how could I approach it differently. Heres what I did: def polls_view(request): polls = polls.objects.all() answers = answers.objects.filter(user=request.user) answered = [] unanswered =[] for answer in answers: if answer.poll in polls: answered.append(answer.poll) for poll in polls: if poll not in answered: unanswered.append(poll) -
Axios GET request modified by something in the frontend
In this action i have a basic GET response at the URL "api/media/action" export const listWorks = async (dispatch) => { try{ dispatch({type:WORK_LIST_REQUEST}) const { data } = await axios.get('api/media/works/') dispatch({type:WORK_LIST_SUCCESS, payload:data}) } catch(error) { dispatch({type:WORK_LIST_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message }) } } in App,js the route is defined in this way <Route path='/work/:name'component={WorkScreen}/> And by launching the action i receive this error in the backend: [26/Jul/2023 20:47:24] "GET /work/api/media/works/ HTTP/1.1" 404 2712 I Can't understand why "work" gets added to the GET request -
Handling Blocking External API Calls in Django
I'm part of a Django project where we make many API calls to external services using the requests and zeep libraries. These calls are done sequentially and our API heavily relies on their immediate responses. However, when our server experiences high traffic, it stops responding. It seems like all our workers become occupied, waiting for these external network calls to finish, leaving no workers available to process new incoming requests. The project is large and converting the entire project to asynchronous isn't currently feasible. Furthermore, because of our need for immediate responses from these API calls, using a task queue system like Celery is not a solution. As we anticipate even more traffic in the future, I'm looking for a solution that can efficiently handle these blocking network calls without blocking our server or requiring a complete rewrite to asynchronous. I increased the number of gunicorn workers using 2*CPU+ 1 formula, but that might not be enough in the future. -
How to solve 'x similar queries' in Django
I have a view that takes over 80 seconds to serve. The SQL tab from django-debug-toolbar says I have 422 total queries, from which 210 are similar. The view calculates a weekly rate (revenue / miles) for 35 weeks of current year for each commodity and truck_type. Any help on how I can optimise my queries is appreciated. Here's the view: def rates_weekly(request): tenant = request.tenant loads = Load.objects.all().exclude(load_status='Cancelled').values('billable_amount_after_accessorial', 'total_miles') from fleetdata.utils import start_week_nr def calculate_rate(year, week_num, commodity, truck_type): start_of_week = start_week_nr(year, week_num) end_of_week = start_of_week + datetime.timedelta(days=7) relevant_loads = loads.filter(drop_date__gte=start_of_week, drop_date__lt=end_of_week, truck_type=truck_type, commodity=commodity) revenue = relevant_loads.aggregate(Sum("billable_amount_after_accessorial"))['billable_amount_after_accessorial__sum'] miles = relevant_loads.aggregate(Sum("total_miles"))['total_miles__sum'] if revenue and miles is not None: rate = revenue / miles else: rate = 0 return rate rates = {} for week in range(1, CURRENT_WEEK_CUSTOM+6): rate_ct_reefer = calculate_rate(CURRENT_YEAR, week, 'Reefer', 'CT') rate_ct_dryvan = calculate_rate(CURRENT_YEAR, week, 'DryVan', 'CT') rate_ct_flatbed = calculate_rate(CURRENT_YEAR, week, 'Flat Bed', 'CT') rate_oo_reefer = calculate_rate(CURRENT_YEAR, week, 'Reefer', 'OO') rate_oo_dryvan = calculate_rate(CURRENT_YEAR, week, 'DryVan', 'OO') rate_oo_flatbed = calculate_rate(CURRENT_YEAR, week, 'Flat Bed', 'OO') rates[str(CURRENT_YEAR) + '-' + f"{week:02d}"] = {} rates[str(CURRENT_YEAR) + '-' + f"{week:02d}"]['rate_ct_reefer'] = rate_ct_reefer rates[str(CURRENT_YEAR) + '-' + f"{week:02d}"]['rate_ct_dryvan']= rate_ct_dryvan rates[str(CURRENT_YEAR) + '-' + f"{week:02d}"]['rate_ct_flatbed']= rate_ct_flatbed rates[str(CURRENT_YEAR) + '-' + f"{week:02d}"]['rate_oo_reefer'] = rate_oo_reefer rates[str(CURRENT_YEAR) + '-' … -
Django custom serializer validation for unique field
I'm trying to write custom invitational system for user registration using DRF. I need separate path only for checking is code is valid. I'm stuck with serializer returns is_valid = False in case if this code exists in database, because code field is defined as Unique in model. And i need opposite behavior. Model class InviteCode(models.Model): code = models.CharField(max_length=32, null=False, unique=True) referal = models.ForeignKey(to=User, null=True, blank=True, on_delete=models.CASCADE, related_name='%(class)s_referal') is_teacher = models.BooleanField(default=False) used_by = models.ForeignKey(to=User, null=True, blank=True, on_delete=models.CASCADE, related_name='%(class)s_used_by') Serializer class InviteCodeSerializer(serializers.ModelSerializer): class Meta: model = InviteCode fields = "__all__" I tried to add validate_code() method to serializer for custom validation def validate_code(self, value): code = InviteCode.objects.filter(code = value).first() if code is None: raise serializers.ValidationError("Invite code doesn't exist") #Other validation checks return code But it is being called after unique check, so in cases when code is present in database method won't be called, and i will still get {'code': [ErrorDetail(string='invite code with this code already exists.', code='unique')]} after calling is_valid on serializer -
In Django 4.2.3 an error occurs in Windows when using QueueHandler, QueueListener and RotatingFileHandler
Windows 10, Django 4.2.3 To implement log rotation in Django, I use QueueHandler, Queue Listener and RotatingFileHandler. I use the following logging setup: class CustQueueListener(QueueListener): def __init__(self, cust_level, queue, handlers, respect_handler_level: bool = False): super().__init__(queue, *handlers, respect_handler_level=respect_handler_level) self.level = cust_level settings.py ... LOGS_QUE = queue.Queue(-1) file_fmt = '[%(asctime)s] [%(levelname)-7s] [%(name)-12s] %(funcName)s:%(lineno)d -> %(message)s' console_fmt = '[%(levelname)-7s] [%(name)-12s] %(funcName)s:%(lineno)d -> %(message)s' file_formater = logging.Formatter(file_fmt) file_handler = logging.handlers.RotatingFileHandler( f'{str(LOGS_DIR)}/q_debug.log', maxBytes=5000, backupCount=9, encoding='UTF8' ) file_handler.setFormatter(file_formater) LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'console': { 'format': console_fmt }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'level': 'INFO', 'formatter': 'console', }, 'queue_handler': { 'class': 'logging.handlers.QueueHandler', 'level': 'DEBUG', 'queue': LOGS_QUE, }, 'queue_listener': { '()': CustQueueListener, 'cust_level': logging.DEBUG, 'queue': LOGS_QUE, 'handlers': [file_handler,], } }, 'loggers': { '': { 'level': 'DEBUG', 'handlers': ['console', 'queue_handler', 'queue_listener'], "propagate": False, }, 'django': { "handlers": ["console", 'queue_handler',], "propagate": False, }, 'django.server': { 'level': 'DEBUG', 'handlers': ['console', 'queue_handler', 'queue_listener'], "propagate": False, }, 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console', 'queue_handler', 'queue_listener'], "propagate": False, } }, } In all modules where I use logging I do: import logging logger = logging.getLogger(__name__) Next, for example, I open the site and start refreshing the page to generate log messages. When the log file size reaches … -
Django Model.objects.create vs Model.save()
New to Django ORM and had a small question. If I have a model like: class Person(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) I can add a new person in the following ways: p1 = Person.objects.create(name="Bob") or p2 = Person(name="Bob") p2.save() In the first case (p1), I can expect that the "id" field is set (auto-incremented when insertion is done). Can I expect the same in the second case? Does django update the in-memory "Person" object's properties (in this case the id field) once a save is done? Follow-up questions: Let's say I had another model class Business(models.Model): id = models.BigAutoField(primary_key=True) owner = models.ForeignKey(Person) Does it make a difference if I do b = Business(owner=p1) b.save() vs b = Business(owner=p2) b.save() What happens if I don't save or create the person object before passing it into Business? e.g. p = Person(name="Bob") b = Business(owner=p) b.save()? -
Django app profile page still showing after logging out
I am trying to set up a profile page for users. Although when I logout and go to the profile page url("127.0.0.1:8000/profile"), it is still showing the result of the user(with which I logged in) views.py: def login_user(req): if req.method == 'POST': form = AuthenticationForm(data=req.POST) if form.is_valid(): user = form.get_user() login(req, user) return redirect('http://127.0.0.1:8000/') else: form = AuthenticationForm() return render(req, 'loginpage.html', {'form': form}) def logout_user(req): if req.method=='POST': logout(req) return redirect('home') @login_required def profile_page(req): user = req.user user_profile, created = UserProfile.objects.get_or_create(cur_user=user) return render(req, 'profilepage.html', {'user': user, 'user_profile': user_profile}) @login_required def edit_bio(req): if req.method == 'POST': new_bio = req.POST.get('bio') user_profile = req.user.userprofile user_profile.bio = new_bio user_profile.save() return redirect('profile_page') urls.py: from django.urls import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ path('', views.homepage, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.login_user, name='login'), path('profile/', views.profile_page, name='profile_page'), path('profile/edit/', views.edit_bio, name='edit_bio'), path('logout/', views.logout_user, name='logout'), ] urlpatterns += staticfiles_urlpatterns() What can be the problem here? -
Django ASGI vs WSGI performance
I am trying to test the performance difference in ASGI and WSGI servers when there are i/o bound functions. I am going to receive streaming responses from 3rd party APIs and then stream them back to client, I am planning on using StreamingHttpResponse of Django. I created two test views, one async one sync, and used time.sleep and asyncio.sleep functions to simulate these web requests that will take a long time to complete. This is the async view: async def async_view(request): async def generate_response_data(): for i in range(10): await asyncio.sleep(1) yield f'{i} ' response = StreamingHttpResponse( generate_response_data(), content_type='text/event-stream' ) return response And this is the sync view: def sync_view(request): def generate_response_data(): for i in range(10): time.sleep(1) yield f'{i} ' response = StreamingHttpResponse( generate_response_data(), content_type='text/event-stream' ) return response I tried to load test these two endpoints to see the performance difference. I ran sync view with Django's builtin development server and async view with uvicorn. I used apache benchmarking tool for load testing. I used this command ab -c 500 -n 1000 <endpoint> meaning 500 concurrent request and total of 1000 requests. ASGI server resulted in 35 requests per second, and WSGI server 42 requests per second. Every article I read … -
Passing a function into context
I'm trying to do what this Article says, and the answer says to simply create a function to do this. How would I go about that? I have tried creating a function that gets the requests from the form and getting the foreign key with the same id but I can not seem to make it work. models.py ``` class Categories(models.Model): category_name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=300, blank=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.category_name class Product(models.Model): product_category = models.ForeignKey(Categories, on_delete=models.SET_NULL, null=True, related_name='categories', blank=True) title = models.CharField(max_length=100) description = models.TextField(max_length=250) price = models.DecimalField(max_digits=12, decimal_places=2) stock = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Products' unique_together = ['title', 'product_category'] def __str__(self): return self.product_category.category_name + '-' + self.title views.py class ProductUpdateView(UpdateView): model = Product template_name = 'products/product_update.html' form_class = ProductForm # success_url = reverse_lazy('products_list') context_object_name = 'products' object = Product.objects.all() #Trying to get the specific id def preselect(self): prod_cat = self.request.POST.get('product_category_id') pre_select = Categories.objects.get(id=prod_cat) final_preselect = pre_select.id return final_preselect # def form_valid(self, request): # if 'Delete' in self.request.POST: # reverse_lazy('products_list', kwargs={'pk': object.pk}) # else: # self.object = request.save() # return HttpResponseRedirect(self.get_success_url()) extra_context = {'preselect': preselect, 'category_context': Categories.objects.all()} def get_success_url(self): if 'categories/' in self.request.path: the_pk = self.request.POST.get('product_category') category = … -
django template: floatformat filter not working when used within an if-condition
In my template, I have: {% if subject.market_value_increase_pct > subject.neighborhood_increase_pct %} Values provided are: market_value_increase_pct = 8.6 & neighborhood_increase_pct = 10.5 I expect the if-condition should evaluate to false with these values. However, it was evaluating to true and the code block within the if-condition was being executed. My thought was may be the variables are being considered as strings, in which case it would evaluate to true. So, I tried to force convert the values to float using floatformat and then compare: {% if subject.market_value_increase_pct|floatformat > subject.neighborhood_increase_pct|floatfomat %} But, that isn't working. It still evaluates to true. The floatformat filter works outside of the if-condition though: <td>{{ subject.market_value_increase_pct|floatformat }}%</td> As per Django template docs, using filters in if-condition is permitted. Would appreciate if anyone can point out what I am missing. Below is the complete code block: {% if subject.market_value_increase_pct|floatformat > subject.neighborhood_increase_pct|floatfomat %} <tr> <th>Subject's market value last year:</th> <td>{{ subject.market_value_last_year | currency | remove_decimal_point}}</td> </tr> <tr> <th>Percent increase:</th> <td>{{ subject.market_value_increase_pct|floatformat}}%</td> </tr> <tr> <th>Average percentage increase for state class {{subject.state_class}} in neighborhood {{ subject.neighborhood_code }}:</th> <td>{{ subject.neighborhood_increase_pct|floatformat}}%</td> </tr> {% endif %} I tried using add:"0" and int filters also. None of them work. Basically, filters aren't working within if-condition … -
How can I get my PostgreSQL server to wrok?
Total spawn time to start the pgAdmin4 server: 0.017 Sec 2023-07-26 18:16:20,262: WARNING werkzeug: WebSocket transport not available. Install simple-websocket for improved performance. Serving Flask app 'pgadmin' Debug mode: off 2023-07-26 18:16:20,262: WARNING werkzeug: Werkzeug appears to be used in a production deployment. Consider switching to a production web server instead. An attempt was made to access a socket in a way forbidden by its access permissions It says PgAdmin 4 server could not be contacted. I tried deleting, uninstalling still nothing. I'm using windows 11. PosgtreSQL 15. I used the pgAdmin 4 that comes with it. I then deleted the pgAdmin 4 and downloaded pgAdmin 4 7v4. It started but it doesn't connect. As for the installation process, I installed directly from the postgreSQL app with the installer and followed all the right steps. -
Merge two values from form.Model in defined CharField
I try to merge two values from dropdown "on the fly" to a HTML input field model.py class ProjectID(models.Model): project_id = models.CharField(max_length=120, unique=True) def __str__(self): return self.project_name class ProjectName(models.Model): project_name = models.CharField(max_length=120, unique=True) def __str__(self): return self.project_name class Project(models.Model): combine_name = models.CharField(max_length=50, unique=True) project_id = models.ForeignKey(ProjectID, related_name='p_number', on_delete=models.CASCADE) project_name = models.ForeignKey(ProjectName, related_name='p_name', on_delete=models.CASCADE) def __str__(self): return f"{self.project_id}_{self.project_name}" views.py class AddProject(generic.FormView): template_name = 'project/project-add.html' form_class = ProjectAddForm success_url = reverse_lazy('project:project-dashboard') urls.py urlpatterns = [ path('', views.dashboard, name='project-dashboard'), path('add/', views.AddProject.as_view(), name='project-add') ] forms.py: class ProjectAddForm(forms.ModelForm): class Meta: model = Project fields = ['project_id', 'project_name', 'combine_name'] project-add.html {% block main-body %} <div class="container"> <form method="post" class="form card p-3 mt-5"> {% csrf_token %} <div class="row align-items-start"> <div class="col-md-4" id="option_a"> {{ form.project_id|as_crispy_field }} </div> <div class="col-md-4" id="option_b"> {{ form.project_name|as_crispy_field }} </div> </div> <div class="row align-items-center"> <div class="col-md-8">{{ form.combine_name|as_crispy_field }}</div> </div> {% endblock main-body %} I try to merge form.project_id form.project_name if the dropdowns are selected and appears into the field form.combine_name With jquery the result failed because I guess it's not possible to handle with templatetags $('#option_a, #option_b').change(function() { var val = $('#option_a').val() + $('#option_b').val(), new_price; $("#new_option").text(val); -
How unable to run pipenv install due to python version incompatibility
I imported a python folder that came with Pipfile and Pifile.lock in it. I tried to run pipenv install in my VScode terminal window but I got a warning saying: "Warning: Python 3.9 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python". I was expecting pipenv install to install the application dependencies and then create a virtual environment which I can go into using pipenv shell. But all to no avail. In my machine, I have python 3.11.4. Would downgrading the version of my machine to python 3.9 solve the problem? or is there a better way to go about this? Looking forward to your assistance. Thanks -
Order management system in the ecommerce website
The problem is about the logic of the implementation of an order management system in an ecommerce website I try to implement an order management system using django in an ecommerce website can anyone help me in the implementation of the oms in the ecommerce website using stripe and paypal in the process of the payement