Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Crispy forms in my Django project and the input field appears to be too small
When I see other examples people can make the entire field screen-wide. Like this: Bootstrap example However what appears on my screen is too small: My example How can I fix it? For reference, I'm using Bootstrap v4.5.3 Code: models.py from django.db import models from django.utils import timezone from django.core.validators import FileExtensionValidator # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) description = models.TextField() video_file = models.FileField(upload_to='uploads/video_files', validators = [FileExtensionValidator(allowed_extensions=['mp4', 'mkv'])]) thumbnail = models.FileField(upload_to='uploads/thumbnails', validators = [FileExtensionValidator(allowed_extensions=['png', 'jpeg', 'jpg'])]) date_posted = models.DateTimeField(default=timezone.now) create_videos.html {% extends 'videos/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container mb-5"> <div class="row justify-content-center"> <div class="col-md-6 col-sm-12 col-xs-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <legend class="border-bottom mb-4">Upload video</legend> {{ form | crispy }} <div class="col-md-4 ml-auto"> <button class="btn btn-outline-primary btn-block mt-3">Upload</button> </div> </form> </div> </div> </div> {% endblock content %} I have tried: Messing with the 3rd to change col-md size. Editing individual fields (mainly 'title' and 'description') with {{ form.field | as_crispy_field }}. -
ImportError: DLL load failed while importing _psycopg: The specified module could not be found. and i use pip instal psycopg2 and the binary one
enter image description here I can't access tp psycopg2 no error and access to psycopg2 and not connected to django project show error no module found and server can't run and i use pip instal psycopg2 and the binary one (myvenv) C:\Users\justp>python -c "import psycopg2" Traceback (most recent call last): File "", line 1, in File "C:\Users\justp\myvenv\Lib\site-packages\psycopg2_init_.py", line 51, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. (myvenv) C:\Users\justp>pip freeze -
Netsuite - Multiple Page Forms / Multi Step Forms
Is there a way to setup multiple paged form in Netsuite (or Hubspot) or somehow reorganize it custom after integration in a website. Not a problem if the page is updating or fetching the next field element. The most important is the multi-page structure (as a kind of quiz card) and the completeness of the arranged data. Working on django/js, kind of PRG pattern. Have tried to use the pagination libraries or sliders to give that effect through putting the timeout after the form mounting. Didn't really work. -
Binding Ajax Search Result To TextField
The search functionality that I have implemented using Ajax works as expected, the problem that I am facing is I couldn't find a solution to bind the search result to the text field when I click an item from the search result. The Ajax search results are displayed using resultBox and the input text field used for searching is SearchInput. Upon clicking an item in the resultBox the value needs to be binded to the searchInput. But currently when I click the item in the resultBox the page is getting refreshed. console.log("Sanity check!"); const url = window.location.href window.onload = function() { const searchForm = document.getElementById("search-form") const searchInput = document.getElementById("search-box") const resultBox = document.getElementById("results-box") const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value const sendSearchData = (stock_name) =>{ $.ajax({ type: "POST", url: '', data:{ 'csrfmiddlewaretoken' : csrf, 'stock_name':stock_name }, success: (res) =>{ console.log(res.data) const data = res.data if (Array.isArray(data)) { resultBox.innerHTML= "" data.forEach(stock_name =>{ resultBox.innerHTML += ` <a href="" style="text-decoration : none;"> <div> <p> ${stock_name.symbol_name} </p> <small> ${stock_name.symbol}</small> </div> </a> ` }) } else { if (searchInput.value.length > 0) { resultBox.innerHTML =`<b>${data}</b>` } else { resultBox.classList.add('not-visible') } } }, error: (err) =>{ console.log(err) } }) } searchInput.addEventListener('keyup',e=> { console.log(e.target.value) if (resultBox.classList.contains('not-visible')){ resultBox.classList.remove('not-visible')} sendSearchData(e.target.value) }) } Please … -
i am facing django.db.migrations.exceptions.InvalidBasesError Cannot resolve bases, when i run python manage.py migrate
I have two apps, coreapp and product app. As all models in product app have common fields , i created a BaseModel in coreapp and then inherited the BaseModel in the models in product app. Then i ran python manage.py makemigrations and python manage.py migrate. After that i made some changes in the models, I added abstract = True in BaseModel and renamed some fields in the models in product app. Then i ran python manage.py makemigrations. Now, when i run python manage.py migrate i get the following error django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'product.Attribute'>, <ModelState: 'product.Category'>, <ModelState: 'product.Product'>, <ModelState: 'product.AttributeValue'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/4.1/topics/migrations/#dependencies for more Below are the two models coreapp/models.py from django.db import models # Create your models here. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) product/models.py from django.db import models from project_root.coreapp.models import BaseModel # Create your models here. class Attribute(BaseModel): title = models.CharField(max_length=100) def __str__(self): return self.title class AttributeValue(BaseModel): title = models.CharField(max_length=100) attribute_object = models.ForeignKey(Attribute,on_delete=models.CASCADE, related_name='attribute_values') def __str__(self): return self.title class Category(BaseModel): title = models.CharField(max_length=200) parent= models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title … -
session cookie is working in other browser
I created log in system in Django using session(not using built in functionality), Now I face issue like : if I log in into one private tab/in my browser then Django create on cookie named "sessionid" and if I create same cookie on other pc or other browser window(Except current log in window) then that also works and shows user is logged in. Why this problem occur and how i can solve this? I want the solution of this problem and explanation why this happens? -
Creating a range of objects at once in django
I am creating a set of numbers and I want to save each of them in the database. My approach is: class NbrSetForm(forms.ModelForm): last_number = Nbr.objects.order_by("-number").first().number start_number = forms.IntegerField(required=True, initial=last_number+1) end_number = forms.IntegerField(required=True, initial=last_number+1) class Meta: model = Nbr fields = ["start_number", "end_number", ...] exclude = ["number"] def clean(self): cleaned_data = super().clean() s = int(cleaned_data["start_number"]) e = int(cleaned_data["end_number"]) + 1 self.number_list = [n for n in range(s, e)] def save(self, commit=False): for n in self.number_list: print("number to create", number) instance = Nbr.objects.create(number=n, ...) print("all done", instance) return super.save(self) I can see the output of both of the print statements in the console (number has a reasonable value here). But nothing is saved to the database and I get an IntegretyError from the return super().save(self) statement (I guess it's this one) saying: NOT NULL constraint failed: app_nbr.number. -
How to improve a complex django code to reduce database queries and avoid loops?
This code is currently making a separate query to the database for each module in the queryset, because I need to have the progress for each of them. I would like to improve the code so that it makes a single query (or as less queries as possible) to the database and does not use a loop. Can anyone help me with this? This was the best I've got. def get_queryset(self): return CourseLanguage.objects.prefetch_related( "modules", "users" ).filter( pk=self.kwargs["course_language_pk"] ).first() @property def modules(self): modules = [] queryset = self.get_queryset().modules.all().values() for module in queryset: percentage = UserContentAnswer.objects.filter( user=self.request.user, content__topic__module__pk=module["id"] ).aggregate( total=Count("pk"), completed=Count("pk", filter=Q(status=ContentStatusType.COMPLETED)), progress=ExpressionWrapper( Case( When(total=0, then=Value(0.0)), default=100.0 * F("completed") / F("total"), ), output_field=FloatField() ), )["progress"] modules.append( { **module, "percentage": f"{percentage:.1f}" } ) return modules -
Docker build failed [insufficient_scope: authorization failed]
I am trying to build an image for a django project. I tried '''sudo docker login''', after that also same error message. tried in macOS M1 & rasberrypi 4B. **Dockerfile: FROM python3.9.2-slim ENV PYTHONUNBUFFERED 1 RUN sudo apt update -y && sudo apt upgrade -y RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install --user -r requirements.txt COPY . /app/ CMD python3 manage.py runserver Output(sudo docker build . -t ttapp-image): [+] Building 2.1s (4/4) FINISHED docker:default => [internal] load build definition from Dockerfi 0.0s => => transferring dockerfile: 279B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => ERROR [internal] load metadata for docker.io/l 2.0s => [auth] library/python3.9.2-slim:pull token for 0.0s ------ > [internal] load metadata for docker.io/library/python3.9.2-slim:latest: ------ Dockerfile:1 -------------------- 1 | >>> FROM python3.9.2-slim 2 | 3 | ENV PYTHONUNBUFFERED 1 -------------------- ERROR: failed to solve: python3.9.2-slim: pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed -
"Got KeyError when attempting to get a value for field `username` on serializer `UserSerializer`
trying to get current user but it shows username keyerror but everything's all good from my side. Can anyone say whats the error? views : @api_view(['POST']) def register(request): data = request.data user = SignUpSerializer(data=data) if user.is_valid(): if not User.objects.filter(username = data['email']).exists(): user = User.objects.create( first_name = data['first_name'], last_name = data['last_name'], username = data['email'], email = data['email'], password = make_password(data['password']) ) user.save() return Response({ 'details':'Sucessfully registered.' }, status.HTTP_201_CREATED) else: return Response({ 'error':'User already exists.' }, status.HTTP_400_BAD_REQUEST) else: return Response(user.errors) Serializers.py : class SignUpSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') extra_kwargs = { 'first_name':{'required':True, 'allow_blank':False}, 'last_name':{'required':True, 'allow_blank':False}, 'email':{'required':True, 'allow_blank':False}, 'password':{'required':True, 'allow_blank':False, 'min_length':4} } This is user serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username') -
What is best practice for organizing Django REST Framework serializers?
I am working on migrating a legacy REST api to Django REST framework. Many responses from contain nested serializers, for example: class TemplateSerializer(serializers.ModelSerializer): colors = ColorSerializer(read_only=True, many=True) fonts = FontSerializer(read_only=True, many=True) property_ids = serializers.PrimaryKeyRelatedField(many=True, queryset=Property.objects.all()) ... class Meta: model = Template fields = '__all__' class ColorSerializer(serializers.ModelSerializer): swatch = SwatchSerializer(read_only=True) class Meta: model = Color fields = '__all__' # and so forth, just imagine several serializers with fields that are read only or write only etc Currently I was have all serializers in my_app/serializers.py and the serializers.py file has grown way too large and disorganized. In that file, a django model usually has several versions of serializers, for example, the list view method may have a different serializer than retrieve and create may have a different serializer than update, etc. So a single ViewSet may have 4-5 different serializers. Also, the nested serializers, like the ColorSerializer above, may have different versions based on requirements of the response when its nested in another serializer versus when GET /colors endpoint is called. With that being said, I want to start organizing/refactoring things for readability to try to be more DRY. I'm aware the API is poorly designed, but redesigning is not an option … -
How to remove from django sitemap pagination ?p=(1,2,3...n)
Okay we have a lot of pages. So when the content pages spill over 400 is created next page for sitemap and it looks like that - sitemap-instructions.xml?p=5 The problem is that pagination is conflicted with robots.txt where we have restrictions for many things including pagination pages. So we tried to handle it with robots.txt but got more problems than we had. My question is How to edit pagination address and replace or remove ?p= -
Django: Object of type WindowsPath is not JSON serializable
I am trying to add ckeditor_uploader to my project, and adding posts in django default admin site. I get the following error: Error during template rendering in \venv\lib\sitepackages\django\contrib\admin\templates\admin\change_form.html, error at line 6 Object of type WindowsPath is not JSON serializable 1 {% extends "admin/base_site.html" %} 2 {% load i18n admin_urls static admin_modify %} 3 4 {% block extrahead %}{{ block.super }} 5 <script src="{% url 'admin:jsi18n' %}"></script> 6 {{ media }} 7 {% endblock %} in settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / 'media' CKEDITOR_BASEPATH = BASE_DIR / 'static/ckeditor/ckeditor' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 1300, }, } in models.py from django.db import models from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=get_default_category) text = RichTextUploadingField(default="add your post here") Kindly help. I tried adding + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) after urlpatterns in urls.py and got no luck. -
How do i get Django API javascript call to work
I am making a fake stock trading django app. i am 99% sure that my file structure is correct. I get a 404 error from the javascript fetch Not Found: /api/stock/IBM/ [24/Oct/2023 19:09:52] "GET /api/stock/IBM/ HTTP/1.1" 404 2250 could someone assist me? I was expecting to get a live feed of the ibm stock. I would also like to make it customizable to any stock. I am new to handling api. Thank you! Relevant Files api_utils.py import requests def fetch_intraday_data(symbol): API_KEY = 'HRUU8PUIVR7TPGIJ' # Replace with your Alpha Vantage API key url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=5min&apikey={API_KEY}' try: response = requests.get(url) response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx) data = response.json() # Check if Alpha Vantage returns an error message if "Error Message" in data: return {"error": data["Error Message"]} return data except requests.RequestException as e: return {"error": str(e)} views.py from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.forms import UserCreationForm from django.urls import reverse from django.contrib.auth.models import User from .models import UserProfile from django.contrib import messages from django.contrib.auth import login as auth_login from django.contrib.auth import logout from django.shortcuts import redirect from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import render from stocktrading.api_utils import fetch_intraday_data from django.http import … -
Querying Django Models linked by a Foreign Key to get a complete Query set, counting liked posts
This is a CS50 Pset - Network - I'm battling my way through this and all but this bit is finished I think I have trapped myself into a corner, I have 4 different Models, 3 are related to this question, User, Posts and LikeMatrix. LikeMatrix uses a Foreign key to both the User Model (user) and the Posts Model (post), its a matrix recording what user liked what post as I couldn't get my original idea to work with a many to many link between User and Posts Models. (if I did it all again I would do it different). I have my Js working, my API's working, evrything else working except the last piece of the puzzle, to count the likes per post in the LikeMatrix Model and then send it to index.html I run a query in views.py that extracts the data from Posts and sends it in a template/Queryset to index.html, see screen shot below for what it looks like on the screen. Im sure there are a lot more professional ways to do what I'm doing but I'm learning as I go and doing it solo, this has taken me weeks already...... Any advice on … -
I want to filter a queryset according to which button is pressed
i am quite new to django. I have a Task model which has various fields such as date, task name, description, is_completed, level of importance. I what to filter the result according to which button is clicked in a template. I am really stuck! this is my code enter code here 'from django.db import models # Create your models here. class Task(models.Model): IMPORTANT_CHOICES = [("high","high"),("mid","mid"),("low","low")] taskName = models.CharField(max_length = 100) taskDescription = models.CharField(max_length = 100) createdDate = models.DateField(auto_now_add = True) finishDate = models.DateField(blank=True, null=True) last_access = models.DateField(auto_now = True) importance = models.CharField(max_length = 20, choices=IMPORTANT_CHOICES, default="low", blank=True, null=True) daysToFinish = models.IntegerField(blank=True, null=True) completed = models.BooleanField(default = False) def __str__(self): return self.taskName views.py def all_tasks(request, pk): person = Person.objects.get(id=pk) all_t = person.task_set.all() tasks = all_t #calulate day to complete task: date_now = datetime.now() date_now_date = date_now.date() for i in tasks: finish_date = i.finishDate diff = finish_date - date_now_date diff_in_days = diff.days i.daysToFinish = diff_in_days i.save() if request.POST.get('s') == "completed": tasks = tasks.filter(completed = True) elif request.POST.get('s') == "notcompleted": tasks = tasks.filter(completed = False) context ={"tasks":tasks} elif request.POST.get('s') == "high": tasks = tasks.filter(importance = "high") context ={"tasks":tasks} print("high") print(tasks) elif request.POST.get('s') == "mid": tasks = tasks.filter(importance = 'mid') context ={"tasks":tasks} print(tasks) print("mid") … -
How to get 1 list when using django queries with a M2M relationship
This question is very similar(if not the same to): Django query — how to get list of dictionaries with M2M relation? . I am just asking this question to be able to learn if there has been any improvements to djagno that include functionality for this since 11 yrs ago I have a M2M relationship: class RandomObject(models.Model): name = models.CharField(max_length=50,blank=False) description = models.TextField(blank=False) features = models.ManyToManyField('Features',blank=False,db_table='RandomObjectFeatures') class Features(models.Model): LIGHTING = "LIT" SECURE = "SGE" COVERED ="CVP" FEATURE_NAME_CHOICES = [ (LIGHTING,"Lighting"), (SECURE,"Secured Well"), (COVERED,"Covered"), ] feature_name = models.CharField(max_length=3,choices=FEATURE_NAME_CHOICES,blank=False,null=True) def __str__(self): for code, display_name in self.FEATURE_NAME_CHOICES: if self.feature_name == code: return display_name return self.feature_name I have populated the database and now want to query the database to be able to show the features of a randomObject in a template random_objects_data = random_objects.values('name','features__feature_name') Now when I print this I get the following: (I have truncated it as it is long, but it makes the point) {'name': 'object1', 'features__feature_name': 'SGE'}, {'name': 'object1', 'features__feature_name': 'LIT'},{'name': 'object1', 'features__feature_name': 'CVP'} This is unhelpful as objects not in the database are created. I would like to get (or something similar to): {'name': 'object1', 'features__feature_name': ['SGE','LIT','CVP']} This means in the template I can iterate though each feature in features__feature_name. … -
Activate the virtual environment through the command line
I have a problem to Activate the virtual environment through the command line,I did it before and this problem didn`t appear to meenter image description here Microsoft Windows [Version 10.0.19045.3570] (c) Microsoft Corporation. All rights reserved. C:\Users\user>cd projects\django_pm C:\Users\user\projects\django_pm>pipenv shell Launching subshell in virtual environment... Microsoft Windows [Version 10.0.19045.3570] (c) Microsoft Corporation. All rights reserved. (user-KgVmIwbj) C:\Users\user>` I try to create new virtual environments -
Django model relations - "Owning" a related model enforced at the model level
I'm not really sure how to title this question, so forgive my title's ambiguity. I have two models, Customer and Address. Each has typical fields you would infer from their model names. Address is also set as an inline to Customer in admin.py: class Customer(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Address(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) street = models.CharField(max_length=100) street_additional = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(choices=US_STATES) zip = models.CharField(max_length=5) def __str__(self): return self.street I want to add a billing_address and shipping_address to the Customer model to allow a customer to choose one of several saved addresses to be used as those types of addresses accordingly, but I don't want any customer to be able to choose any address. My initial plan was to model the Customer with a foreign key relation back to Address while using limit_choices_to such as: class Customer(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True) billing_address = models.ForeignKey("Address", on_delete=models.SET_NULL, related_name='billing_address', blank=True, null=True, limit_choices_to={'customer_id':some_callable()) shipping_address = models.ForeignKey("Address", on_delete=models.SET_NULL, related_name='shipping_address', blank=True, null=True, limit_choices_to={'customer_id':some_callable()) def __str__(self): return f"{self.first_name} {self.last_name}" I realized this is not how limit_choices_to is intended … -
empty data in views.py with threads in django app
I have a Django app where I'm initializing generative and document retrieval models. I want to dedicate a thread to the generative model as it uses GPU. Below is my apps.py: import atexit import threading import time import torch import os import pickle from django.apps import AppConfig from django.conf import settings from haystack.nodes import EmbeddingRetriever, PromptNode, PromptTemplate, AnswerParser from transformers import LlamaForCausalLM, LlamaTokenizer, BitsAndBytesConfig from queue import Queue class ChatbotConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'chatbot' generative_queue = Queue(maxsize=1) # Create a queue for generative pipeline requests document_queue = Queue(maxsize=10) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') session_data = {} generative_data= {} models_initialized = False # Flag to track if models have been initialized gen_models_initialized = False session_lock = threading.Lock() # Lock for session management generative_data_lock = threading.Lock() processing_complete_event = threading.Event() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.models_initialized = False def ready(self): # Register resource cleanup for application exit atexit.register(self.cleanup_resources) # Create a thread for processing generative pipeline requests generative_thread = threading.Thread(target=self.generative_thread) generative_thread.daemon = True generative_thread.start() # Create a thread for concurrent document retrieval document_retrieval_thread = threading.Thread(target=self.document_retrieval_thread) document_retrieval_thread.daemon = True document_retrieval_thread.start() def cleanup_resources(self): self.deallocate_gpu_memory() def deallocate_gpu_memory(self): gc.collect() torch.cuda.empty_cache() def generative_thread(self): while True: session_id, query, pipeline_type, last_activity = self.generative_queue.get() if pipeline_type … -
Using django and chart.js to create a matrix heatmap showing crime over a range of dates. Can't drill down into a week cell and get the tooltip value
I have a django template that uses script.js to create a webpage that produces a matrix heatmap I want to create an alert that shows the value of the tooltip for any cell in the matrix chart. Heres a sample of the data that has the tooltips: {"type": "matrix", "options": {"aspectRatio": "5", "plugins": {"legend": false}, "scales": {"y": {"type": "time", "offset": true, "time": {"unit": "year", "round": "year", "parser": "yyyy", "displayFormats": {"year": "yyyy"}}, "reverse": true, "position": "right", "ticks": {"maxRotation": 0, "autoSkip": true, "padding": 1, "font": {"size": 9}}, "grid": {"display": false, "drawBorder": false, "tickLength": 0}}, "x": {"type": "time", "position": "bottom", "offset": true, "time": {"unit": "week", "round": "week", "parser": "w", "displayFormats": {"week": "ww"}}, "ticks": {"maxRotation": 0, "autoSkip": true, "font": {"size": 9}}, "grid": {"display": false, "drawBorder": false, "tickLength": 0}}}}, "data": {"datasets": [{"data": [{"x": "1", "y": "2020", "z": 0, "tooltip": "2020W01: 0 crimes"}, {"x": "1", "y": "2021", "z": 9, "tooltip": "2021W01: 9 crimes"}, {"x": "1", "y": "2022", "z": 4, "tooltip": "2022W01: 4 crimes"}, {"x": "1", "y": "2023", "z": 1, "tooltip": "2023W01: 1 crimes"}. . . . function clickHandler(event) { const tooltipElement = document.querySelector('.chart-tooltip'); // Get the clicked cell. const clickedCell = event.target; // Get the value of the tooltip. const tooltipValue = tooltipElement.textContent; // Display the … -
How can I setup Django to serve files on a file server?
I am working on a Django website where files are going to be sold. These files can be large in size, up to 5GB. So, I believe that in addition to a VPS for serving the website, I also need to set up a file server (download server). First of all, since I haven't used download servers before, I'm unsure about how to connect the download server to the VPS that hosts my website. In my research, I've come across the idea of setting up a subdomain. For instance, if my website is mywebsite.com, I would create a new DNS A record, like dl.mywebsite.com, and then use this link to serve the files to users on my website. Is this a correct approach? And also what protocol should be used for this connection when a user clicks a download button? Is it going to be a file protocol, HTTP, FTP, or something else? Another question is that I have no idea how to configure my Django project to provide download links to users who have purchased a file when the files are located on another server. For example, how do I configure the media root and URL so that the … -
how to pass queryset or kwarg to RangeFilter class in Django filters
I'm working on a Django-driven website which uses django-filters and, specifically, RangeFilter to show price diapason of the real estate properties and visualize it as a slider on search form. My queryset is initially formed in the PropertyListView as a list of objects with a certain status (sale or rent), and then it is being passed to the filter, PropertyFilter. The PropertyFilter uses several other classes to construct corresponding widgets, such as slider for the price: class PropertyFilter(FilterSet): price = PriceFilter() ... class PriceFilter(RangeFilter): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) values = [p.price for p in Property.objects.all()] min_value = min(values) max_value = max(values) self.extra['widget'] = CustomRangeWidget(attrs={'label':_('Price, €'),'data-range_min':min_value,'data-range_max':max_value}) The problem is that the PriceFilter does not "know", which objects are in the queryset, and takes the price diapason from the full list of objects. This results in awkward slider, whose diapason is too wide, from 600 to 300,000 euro, which is irrelevant. I want to make the PriceFilter to get prices from the queryset. How it is possible to do it? I've tried to use queryset directly inside this filter, to pass the queryset into it, or to pass the status as a kwarg parameter, but every time I got an … -
how to preserve data in form after a unsuccessful submit or after page reload after the error?
I have a Crud Project in which when i add any new member in the list the data i entered is vanished if i entered the same email which is already registered, i want that if i entered the mail id which is already registered so it will only give a message of that ID is already registered and data which i filled in the form it will not vanished , can we do this ? type here i want that if i entered the mail id which is already registered so it will only give a message of that ID is already registered and data which i filled in the form it will not vanished , can we do this ? Add_Member view.py @login_required def user_data_create(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] gender = request.POST['gender'] role = request.POST['role'] if Members.objects.filter(email=email).exists(): messages.error(request,"This Email Is already registred") else: user_data = Members.objects.create(user=request.user, name=name, email=email, phone=phone, gender=gender,role=role) user_data.save() messages.success(request,"New Member added Succesfully") return redirect('dashboard_page') return render(request, 'add.html') Update View.py @login_required def user_data_update(request, id): try: user_data = Members.objects.get(id=id) if user_data.user == request.user: if request.method == 'POST': user_data.name = request.POST['name'] user_data.email = request.POST['email'] user_data.phone = request.POST['phone'] user_data.gender = … -
Running a django project on windows server 2016 - IIS
I’m trying to run a django site on windows server 2016. I am using IIS and FastCGI to do this. After trying to open the site in the browser, I get this error message: Error occurred while reading WSGI handler: traceback (most recent call last).:File "C:\Python\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response. physical_path) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Python\Lib\site-packages\wfastcgi. py", line 605, in get_wsgi_handler handler = handler() ^^^^^^^^^ File "C:\Python\Lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\Python\Lib\site-packages\django\__init__. py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python\Lib\site-packages\django\apps\registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant StdOut: I tried adding enviromental variables which didn't help but maybe I didn't set them correctly. I would be very grateful for advice and guidance on how to fix this error. Have a nice day Lukas