Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cloudflare with django hosting on aws causing "domain.com redirected you too many times"
After I transferred my nameserver from AWS Route 53 To Cloudflare (also with the same dns settings), I get: "mydomain.com redirected you too many times" I have this settings in django, which work without Cloudflare, I tried to remove them all but it didnt help. #SSL configuration SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True I currently use: nginx django ubuntu aws I really would like to use Cloudflare, any help to solve this issue ? -
DJango signup list
I have this Django model from django.db import models from django.utils.timezone import localtime from django.conf import settings from django.db import models # Create your models here. class Meal(models.Model): meal_time = models.DateTimeField("Tid/Dato") meal_description = models.CharField(verbose_name="Beskrivelse af måltid", max_length=300) meal_deadline = models.DateTimeField(verbose_name="Tilmeldingsfrist") meal_price_pp = models.DecimalField(verbose_name="Pris per person", decimal_places=2, max_digits=5) meal_price_tt = models.DecimalField(verbose_name="Pris i alt", decimal_places=2, max_digits=5) meal_resp = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_offer_takeaway = models.BooleanField(verbose_name="Tilbyd takeaway", default=False) meal_offer_eat_in = models.BooleanField(verbose_name="Tilbyd spisning i netværket", default=False) # meal_timezone = models.CharField(verbose_name="Tidszone", default='Europe/Copenhagen', max_length=50) def __str__(self): return (f"{self.meal_description} Dato:" f" {localtime(self.meal_time).date().strftime("%d/%m/%Y")} " f"{localtime(self.meal_time).strftime("%H:%M")} Pris: {self.meal_price_pp}") def weekday(self): weekdays = ["Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"] index = self.meal_time.date().weekday() return weekdays[index] def resp_name(self): return self.meal_resp.name class Participant(models.Model): list_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Bruger", on_delete=models.CASCADE) list_meal = models.ForeignKey(Meal, verbose_name="Måltid", on_delete=models.CASCADE) list_takeaway = models.BooleanField(verbose_name="Takeaway", default=False) list_eat_in = models.BooleanField(verbose_name="Spisning i netværket", default=False) list_registration_time = models.DateTimeField(verbose_name="Date/time registered") payment_due = models.DateField(verbose_name="Betales senest") payment_status = models.BooleanField(verbose_name="Er betalt", default=False) def registered_on_time(self): meal_record = self.list_meal return self.list_registration_time <= meal_record.meal_deadline def __str__(self): return f"Bruger: {self.list_user} Dato: {localtime(value=self.list_meal.meal_time).strftime("%x kl. %H:%M")}" And I would like to create a list of Meals where the (authenticated) user can select whether to sign up for a meal (on the Participants list) by selecting (if avalialable) check boxes for eat in, takeaway or both. I … -
how does the form_invalid() works in django5?
I am trying to pass the loggedin user to a form using form_invalid() and the code I used is as below. but it seems like there is a different way to code it in django 5.0 as the above code doesn't do anything. Any idea about how to do it in django 5.0? I tried : def form_invalid(self, form): form.instance.user = self.request.user return super(TaskListView, self).form_invalid(form) I want to : Restrict the user attribute of the model to the currently logged in user using django 5.0 -
Django rest not getting the image and attribute fields for any of my parent and child product
I crate an product model where I am showing all children product under it's parent but I am not seeing image and arribute fileds for any of my product. here my code **models.py class Product(models.Model): parent_product = models.ForeignKey('self',on_delete=models.CASCADE,null=True, blank=True) ...others fileds class Attribute(models.Model): name = models.CharField(max_length=100) product = models.ForeignKey(Product, on_delete=models.CASCADE) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='product_images/') serilizer.py class AttributeSerializer(serializers.ModelSerializer): class Meta: model = Attribute fields = ('name',) class ProductImageSerializer(serializers.ModelSerializer): class Meta: model = ProductImage fields = ('image',) class ChildProductSerializer(serializers.ModelSerializer): attributes = AttributeSerializer(many=True, read_only=True) images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = '__all__' class ProductSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() attributes = AttributeSerializer(many=True, read_only=True) images = ProductImageSerializer(many=True, read_only=True) class Meta: model = Product fields = '__all__' def get_children(self, obj): children = Product.objects.filter(parent_product=obj) serializer = ChildProductSerializer(children, many=True) return serializer.data here my response look like this [ { "id": 1, "children": [ {...my children product}] "title": "hello test sashjhas ahsbahs ahs ba sh as", "slug": "hello-test-sashjhas-ahsbahs-ahs-ba-sh-as", "description": "", "orginal_price": "200.00", "discount_price": "180.00", "discount": "10.00", "available": true, "quantity": 1, "unit": null, "is_published": false, "sku": "c2a4a7fa-afbd-484a-9cdf-ec03284ab2cc", "createdAT": "2023-12-29 19:50:13.637279+00:00", "updatedAt": "2023-12-29 19:52:53.172203+00:00", "parent_product": null } ] I added AttributeSerializer and ProductImageSerializer in my ProductSerializer and ChildProductSerializer but not getting the attribute … -
Strange duplicate logs in django app while starting
Basically I'm working on a website using django, and when I start the django app I can see that some lines are actually printed twice. Here is an example of logs: (in this case there is an error at the end, but when the app works correctly i don't see other duplicate logs, just at the startup) >python manage.py runserver test, this line should appear once! test, this line should appear once! Watching for file changes with StatReloader Watching for file changes with StatReloader Performing system checks... couldn't import psycopg 'c' implementation: No module named 'psycopg_c' System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): ... Maybe this information can be useful, some months ago I had to use another thread in this same app to perform a long task without making the website unavailable in the meanwhile. I stopped working at this code for some time and now I don't remember exactly what I did but probably i messed up something. I know it's difficult to help me with not so many details, but I don't even know/remember where to look, I would appreciate advices for a better debug of what's going … -
How to design a django website architecture with all the details ,proper plan
If we get a new django project requirement that we need to develop from scratch. Then how do We need to plan the project with all details in architecture like low level and high level design. I need some one to help me with detailed explanation and diagrams. I need exact architecture diagram and detailed api endpoints information -
Django throttle_scope doesn't seem to work
The problem I was trying to implement throttling following the django rest framework guide. Since I don't need to create another throttle class, I tried to use the .throttle_scope attribute. So, I implemented it like this: class MyView(APIView): throttle_scope = 'my_scope' def post(self, request) -> Response: # do something return Response(status=status.HTTP_200_OK) And in the settings I wrote something like this: REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'my_scope': '1/minute', } } What I tried I tried, using postman, to make more than 1 request per minute to that endpoint and I never received a 429 code. Than I tried creating a new throttle class and using the .throttle_classes attribute, like this: class MyView(APIView): throttle_classes = [MyThrottle] def post(self, request) -> Response: # do something return Response(status=status.HTTP_200_OK) class MyThrottle(UserRateThrottle): scope = 'my_scope' I left the settings unchanged and it worked as expected. Possible solution? So now I'm wondering, could it be that the throttling_scope attribute only works if the user is anonymous? -
What is the relationship here, One to Many or a Many to Many?
I am building a project(using django) whereby agents are issued with phones. When a phone gets damaged the agent sends the phone to hq for repairs. In the meantime, the agent is issued with another different phone. Once the phone gets repaired, its then issued to another agent who may have similar problems as the first agent. What is the relationship between the phone and agent keep in mind i want to preserve the history of phone ownership and also avoid having data that says " Phone x with imei XXXXX and Phone.Status=active is currently being used by more than one agent" I am still in planning phase but i cant crack this one -
How to fix django timeout error when sending email
I'm trying to make a simple django app that sends an email to a user, but every time i try to run the program, i get an error 'TimeoutError at /automail2/success [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond' this happens after a couple seconds of loading after the email address has been submitted. Here's a github link to the code https://github.com/Taterbro/automail I'm fairly new to coding and the stackoverflow community, so any help would be appreciated. tried to send an email using django expected the code to send an email the code timed out while trying to send the email -
Django-based Docker project will connect to local postgres DB on windows machines but not on a Mac or Linux machine
been struggling with this issue for close to a month now and I am at my wits end. I have the following docker-compose.yml file: version: '3.8' services: web: container_name: targeting build: ./Targeting command: python manage.py runserver 0.0.0.0:80 volumes: - ./:/usr/src/project/ ports: - "80:80" db: env_file: - ./.env restart: always image: postgres container_name: postgres environment: - POSTGRES_DB=${NAME} - POSTGRES_USER=${USER} - POSTGRES_PASSWORD=${PASSWORD} - POSTGRES_PORT=${PORT} ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data/ pgadmin: image: dpage/pgadmin4 container_name: pgadmin4_container restart: always ports: - "8888:80" environment: PGADMIN_DEFAULT_EMAIL: user-name@domain-name.com PGADMIN_DEFAULT_PASSWORD: strong-password volumes: - pgadmin-data:/var/lib/pgadmin volumes: postgres_data: pgadmin-data: and I have the following .env file: SECRET_KEY=random_secret_key DEBUG=TRUE NAME=postgres USER=postgres PASSWORD=password HOST=db PORT=5432 The following Dockerfile is used to create the python container: # pull official base image FROM python:3.11.4-slim-buster # set work directory WORKDIR /usr/src/project # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ../requirements.txt . RUN pip install -r requirements.txt # copy project COPY .. . On a Windows machine, after a docker compose build and a docker compose up command is issued, the project will be up and running and the django project will connect to the postgres database perfectly fine. I have verified this on two … -
Django Backend is giving me this Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'
I have tried just about everything from researching. Basically I have my frontend server and a backend server. My fronend server is getting the error from the backend server that is running Django. This is my settings in my Django app """ Django settings for appliAI project. Generated by 'django-admin startproject' using Django 4.2.7. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'removed because I am not giving that out' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # asdf.com has is replacing my actual URL ALLOWED_HOSTS = [ "localhost", "127.0.0.1", "asdf.com", "*.asdf.com", ] # Application definition INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sslserver', 'django_extensions', 'rest_framework', ] # Access-Control-Allow-Credentials = MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', # 'whitenoise.middleware.WhiteNoiseMiddleware', ] CORS_ALLOWED_ORIGIN_REGEXES = [ r"^https://\w+\.asdf\.com$", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_DEBUG = True CORS_ALLOW_METHODS … -
Django channels and react useState variable for room parameter instead of url
Is it possible instead of a url parameter in django channels to just use state from react. I mean instead of having to go to a specific url for example 'chat/str:roomname' to do something like this const [roomName, setRoomname] = useState('example') const chatSocket = new WebSocket( `ws://${window.location.host}/ws/chat/${roomName}/` ); I am asking this because I don't wanna redirect users to another page when they want to chat. -
python (Djanjo) - Page not found
I don't understand what the problem is, I'm a beginner in Python and I was asked to do this. I would be grateful for your help)) urls.py views.py models.pyurls.py - 2 example.html - it should be reflected in the price result -
formulario en Django a outlook
eh estado trabajando en una app en django en la que debo implementar un formulario de contacto el cual el cliente podra completar con sus datos y luego al **correo empresarial de outlook **me deberia llegar el correo con la info que el cliente ingreso, a la vez se debe confirmar la existencia del correo que ingresa el cliente para enviarle una copia del correo, esto lo habia hecho antes pero con Gmail y con outlook al parecer no es igual alguien me puede ayudar para saber en que estoy fallando, ya que no se envia el correo, ni tampoco entiendo el error que me aparece, gracias. settings.py from dotenv import load_dotenv from pathlib import Path env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) from decouple import config EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True OUTLOOK_EMAIL = config('OUTLOOK_EMAIL', default='') OUTLOOK_PASSWORD = config('OUTLOOK_PASSWORD', default='') DEFAULT_FROM_EMAIL = '#!' views.py def contact(request): if request.method == 'POST': form = ContactoForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] phone = form.cleaned_data['phone'] message = form.cleaned_data['message'] # Construir el cuerpo del correo email_body = f"Nombre: {name}\n" email_body += f"Email: {email}\n" email_body += f"Teléfono: {phone}\n" email_body += f"\nMensaje:\n{message}" # Crear el objeto EmailMessage email … -
DJANGO: send_mail is not throwing errors or exceptions
I want to send smtp emails. But it is not working and I do not know how to debug this problem. In my settings.py I set a complete wrong port: EMAIL_PORT = 3 In the Django shell I run this script without getting an error. send_mail is just returning 1 after execution. from django.core.mail import send_mail send_mail( 'Test Email', 'That is an test.', 'test@test.com', ['test@gmail.com'], fail_silently=False, ) I also have configured an error logger, which should log everything. But it is also not appearing anything in my logfile: ... 'loggers': { '': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, ... Is this the default behavior? I guess no? What I am doing wrong? -
Getting Unresolved attribute reference for inherited methods in Pycharm
I am getting Unresolved attribute reference for inherited methods in my Pycharm Django project. What I have tried without any luck: Used interpreter through poetry (also tried venv through poetry) Also tried to Invalidate caches and restart. Note: This issue seems to occurred only on inherited methods. When importing classes directly the autocomplete suggestions propagate correctly. -
Value Error: Expected 2D array, got 1D array instead
I am just trying to learn the KNN algorithm. I am running the following code, but getting the following ValueError. import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score df = pd.read_csv(r"C:\Users\User\Downloads\Social_Network_Ads.csv") df = df.iloc[:,1:] #We dont need all the columns encoder = LabelEncoder() df['Gender'] = encoder.fit_transform(df['Gender']) #Encoding the gender col into 0 or 1 scaler = StandardScaler() X = df.iloc[:,0:3].values X = scaler.fit_transform(X) y = df.iloc[:,-1].values y = scaler.fit_transform(y) X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=10) knn = KNeighborsClassifier(n_neighbors=5) knn.fit(X_train,y_train) y_pred = knn.predict(X_test) print(accuracy_score(y_test,y_pred))` Exception: ValueError: Expected 2D array, got 1D array instead: array=[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 1. 1. 1. ... 1. 1. 1. 0. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1. 0. 1. 0. 0. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 1. 1. 1. 0. 1. 1. 1. 0. 1.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. -
python django asyncua subscription synchronous
In the following example, I call my function check_data_acknowledge from a synchronous function to subscribe to a node, determine the moment of its modification, and act accordingly. I have tried many solutions without finding a way to execute a subscription in my Django code If someone can help me, thanks in advance. import asyncio import time from asyncua.common.subscription import SubscriptionHandler from asyncua.sync import Client from prod_declarator.config_line import line_id from prod_declarator.opcua import opcua_instance def run_asyncio_function_synchronously(coro): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete(coro) finally: loop.close() async def subscribe_acknowledge(client, node_path): print(f"started subscribe_acknowledge at {time.strftime('%X')}") handler = SubscriptionHandler() subscription = await client.create_subscription(500, handler) nodes = node_path await subscription.subscribe_data_change(nodes) # Your asynchronous logic here counter = 0 while counter < 10: await asyncio.sleep(1) counter += 1 return subscription async def subscribe_acknowledge_sync(client, node_path): return await subscribe_acknowledge(client, node_path) def check_data_acknowledge(part_declaration_check_packaging_number): async def run_async(): node_data_acknowledge_line_id = opcua_instance.instanceExigences["data_acknowledge"] line_name = line_id[part_declaration_check_packaging_number["line_id"]]["lineName"] node_data_acknowledge = node_data_acknowledge_line_id.replace("LineName", line_name) print(f"Node data acknowledge : {node_data_acknowledge}") end_point = line_id[part_declaration_check_packaging_number['line_id']]["end_point"] name_space = line_id[part_declaration_check_packaging_number['line_id']]["associatedNameSpaceIndex"] print(f"Name space : {name_space}") client = Client(end_point, timeout=10) client.aio_obj.session_timeout = 600000 client.connect() node_path = client.get_node("ns={};s={}".format(name_space, node_data_acknowledge)) result = node_path.get_value() print(f"Result : {result}") await subscribe_acknowledge_sync(client, node_path) client.disconnect() loop = asyncio.get_event_loop() loop.run_until_complete(run_async()) return part_declaration_check_packaging_number In this code, check_data_acknowledge is called from another synchronous function like … -
How to redirect to different pages using a single form in django
I was trying to design a form which can be used to redirect the user to corresponding pages as per the selected category field. i am new to django I'm not sure where the error can be. Therefore, I am sharing all four files i.e. models, views, forms and templates (The urls are correct). models.py from django.db import models from autoslug import AutoSlugField # Create your models here. class Category(models.Model): name = models.CharField(max_length = 80, null = False, blank = False) slug = AutoSlugField(populate_from = 'name', unique = True) class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name class Pdf(models.Model): pdf = models.FileField(upload_to="pdfs/") category = models.ForeignKey( Category, related_name = 'pdftools', on_delete = models.SET_NULL, blank = True, null = True ) def __str__(self): return f"{self.pdf}" views.py from django.shortcuts import render, redirect, get_object_or_404 import forms from django.contrib import messages # from .models import Category # from django.http import HttpResponseRedirect, HttpResponse # from django.urls import reverse # Create your views here. def linkview(request): return render(request, 'Link.html') def emailview(request): return render(request, 'Emails.html') def textview(request): return render(request, 'Text.html') def pdfUploadView(request): if request.method == 'POST': form = forms.UploadPdfForm(request.POST, request.FILES) if form.is_valid(): category = form.cleaned_data['category'] form.save() messages.success(request, "File uploaded successfully!!") # return HttpResponse('The file … -
Cannot use Model Form instance parameter with __init__ function
I am trying to create an edit form for a preexisting entry in one of my models. I need to limit the results for the select users field in my model form. However, when I try to use the instance=MyModelObject parameter for the form to load the prefilled from I get the error as follows. TypeError at /courses/course/asdd CourseForm.__init__() got an unexpected keyword argument 'instance' here is my view.py function @csrf_exempt @login_required def addCourse(request, course_id = None): #initialize data user = request.user school = user.school #check if submition is POST if request.method == 'POST': #if so check if user is linked to a school if user.school: #check if user has admin access to add courses if user.is_admin and user in school.admins: #get all form information # check if form data is valid if form.is_valid(): # save the form data to model form.save() return HttpResponseRedirect(reverse("courses", 'school')) #if GET check if user has a related school elif user.school: #check if user has admin access if user.is_admin: #check for course code, if so auto fill course info if course_id != None: #generate filled form course = Course.objects.get(code=course_id) form = CourseForm(instance=course, school=school) return render(request, "app/courses/addCourse.html", {'form': form}) #if no course code, generate blank form … -
Non-separation of elements
With this code, after pressing the close button, not only that product but all products will be sold, and the buyer cannot offer a price for any of them. views.py: @login_required def page_product(request, productid): product =get_object_or_404(Product, pk=productid) offers = Bid_info.objects.filter(product=product).order_by("-bid_price") off = Bid_info.objects.filter(product=product).order_by('id').first() # max bid try: bid_max = Bid_info.objects.filter(product_id=productid).latest('bid_price') except: bid_max ="No offer has been registered yet!" # close close_button = False try: if request.user == product.user: close_button = True off.bid_price = bid_max win = Bid_info.objects.filter(product_id=productid).order_by('id').latest("seller") for item in Bid_info.product: if item.id == Bid_info.product.id: Bid_info.checkclose = not Bid_info.checkclose else: close_button = False except: pass context = { 'product' : product,, 'offers' : offers, 'off' : off, 'close_button' : close_button, 'bid_max' : bid_max, 'checkclose' : Bid_info.checkclose, 'winner' : win } return render(request, 'auctions/page_product.html', context) def close(request, cid): return redirect(page_product, cid # bid def bid(request, bidid): product = get_object_or_404(Product, pk=bidid) if request.method == 'POST': user = request.user if user.is_authenticated: bid_price = Decimal(request.POST.get("bid_price", False)) other_off = Bid_info.objects.filter(product=product).order_by("-bid_price").first() if Bid_info.checkclose : messages.warning(request, "it sells.") else: Bid_ = Bid_info(product=product, seller=request.user, bid_price=bid_price) return redirect('page_product', bidid) If I delete the for loop in the first function and write this in the bid function in the if loop: if Bid_info.checkclose== true This is the situation again. html: … -
Location of signals in Django
I am confused about the use of signals. Where should I put the signal codes so that they are orderly and appropriate? I have a signal file for an app. Where do I call it? -
Is it possible to store a queue-like structure in Django database?
This might be a stupid question, but I'm new to databases and I could't find an answer anywhere. Is it possible to somehow store a FIFO queue in django? Some equivalent of python's collections.deque? Let's say I hypothetically have a model AverageRate, which stores a queue of up to 24 numbers and an average value of those numbers: (sum(numbers) / len (numbers)). class AverageRate: last_24_numbers = # FIFO queue up to 24 elements long average_value = # average value of last_24_numbers Every hour a function adds a new number to last_24_numbers and calculates average value. If the queue reaches 24 elements, then to append a new element to the end of the queue, it must pop the oldest element from the beginning of the queue. Honestly the only solution I came up with was to possibly convert the queue to string and store it in CharField, and then convert it back every time I need to use it. But I dunno... it just feels like not the best idea. I would obviously want to use the most efficient solution. -
How do I unfreeze or solve my python libraries being frozen problem
enter image description hereenter image description here I'm trying to make a test project and downloaded bootstrap in different ways but then this happened can anyone help me solve this. I tried deleting and downloading python again but that didnt work. -
How to create django model for tenants and properties?
2.2.Property Listing Module Property Details: Create property profile with information like Property name and address, location, features. Each property will have multiple units. Each unit will have features like rent cost,Type- 1BHK,2BHK,3BHK,4BHK property profile view with units and assigned tenant information 2.3.Tenant Management Module Create a tenant profile with name, address, document proofs. Assign a tenant with a unit under a property with details like agreement end date, monthly rent date. Need a search based on features added for units and properties. Show tenant profile view with personal information and rental information from django.db import models class Property(models.Model): name = models.CharField(max_length=100) address = models.TextField() location = models.CharField(max_length=100) features = models.TextField() def __str__(self): return self.name class Meta: verbose_name_plural = "properties" class Unit(models.Model): UNIT_TYPES = [ ('1BHK', '1BHK'), ('2BHK', '2BHK'), ('3BHK', '3BHK'), ('4BHK', '4BHK'), ] rent_cost = models.IntegerField() unit_type = models.CharField(max_length=4, choices=UNIT_TYPES) property = models.ForeignKey(Property, on_delete=models.CASCADE, related_name='units') def __str__(self): return f"{self.unit_type} unit in {self.property.name}" class Tenant(models.Model): name= models.CharField() address=models.TextField() document_proofs=models.ImageField() assigned_unit = models.ForeignKey(Unit, on_delete=models.SET_NULL, null=True, blank=True) def __str__(self) -> str: return self.name This what I developed.Is this correct way of creating model. how to include agreement end date, monthly rent date in this model