Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"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 -
change dropdown data - django
How can i change the values in the department fields based on the selection made in school. I have the below models school_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) name = models.CharField(max_length=50) abbr = models.CharField(max_length=5) class Department(models.Model): dept_id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) school = models.ForeignKey(School, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=30) forms.py school = forms.ModelChoiceField(required=True, queryset=School.objects.all(), empty_label="Select School", widget=forms.Select( attrs={ 'class': 'form-control select form-select', 'onchange': 'this.form.submit()' } )) department = forms.ModelChoiceField(required=True, queryset=Department.objects.all(), empty_label="Select Department", widget=forms.Select( attrs={ 'class': 'form-control select form-select' } )) how can i tweak my views? -
Syncing issue within Socket IO
I've implemented a website chat with python-socketio and socket.io-client. At times, when we simultaneously open multiple tabs in different browsers or incognito sessions with the same logged-in user, the newly opened tabs can successfully send and receive messages. However, the older tabs do not send or receive messages, even though they remain connected to Python Socket.IO and socket.io-client. Additionally, I've already used a room session for managing the connections. This Problem happens on a live server where, at any point about 50-100 users are connected to the socket, not on localhost. The versions I'm using are as follows: python-socketio==5.9.0 uvicorn==0.16.0 eventlet==0.33.3 socket.io-client = 4.7.2 Backend: import socketio sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins='*', logger=True, engineio_logger=True) connected_users = {} room_user_count = {} @sio.on("connect") async def connect(sid, environ): try: query_string = environ.get("QUERY_STRING") or "Anonymous" if query_string: username = query_string.split("username=")[1].split("&")[0] await sio.save_session(sid, {'username': username}) room_name = await change_group_name(username) sio.enter_room(sid, room_name) print(f"[Connected] {sid}") except Exception as e: print("Connected error", str(e)) @sio.on("login") async def handle_login(sid, data): username = data.get("username") session_id = await sio.get_session(sid) connected_users[sid] = {"username": username, "session_id": session_id['username']} print(f"{username} logged in.") @sio.on("disconnect") async def disconnect(sid): try: username = connected_users.get(sid, {}).get("username", "Anonymous") connected_users.pop(sid, None) leave_room = await change_group_name(username) sio.leave_room(sid, leave_room) print(f"Disconnected: {sid}, Username: {username}") except Exception as … -
Using Django ORM to query a Model with two FKs that are related through an unique_together constraint on a third Model
I am currently facing a challenge in creating a QuerySet that accurately represents the relationships within my Django models. I have a model equipped with two foreign keys, FK1 and FK2. These two foreign keys, when combined, create a tuple representing a classification (FK1, FK2 -> CLS.pk). This relationship is managed and represented through another model, where I store the records corresponding to these foreign keys and the resulting classification (FK1, FK2, CLS.pk). Defining my question has been a challenge in itself, so I've tried to simplify the relationship to illustrate the core idea of what I'm attempting to achieve here. class Event(models.Model): value = models.DecimalField(decimal_places=2, max_digits=11, default=0.0) event_date = models.DateField() local = models.ForeignKey(Local, on_delete=models.CASCADE, related_name='event_set') origin = models.ForeignKey(Origin, on_delete=models.CASCADE, related_name='event_set') class Meta: db_table = 'db_event' class Local(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'db_local' class Origin(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'db_origin' class Classification(models.Model): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'db_classification' class ClassificationPerOriginAndLocal(models.Model): local = models.ForeignKey(Local, on_delete=models.CASCADE, related_name='classification_related_set') origin = models.ForeignKey(Origin, on_delete=models.CASCADE, related_name='classification_related_set') classification = models.ForeignKey(Classification, on_delete=models.CASCADE, related_name='classification_related_set') class Meta: db_table = 'db_classification_per_origin_and_local' unique_together = ('local', 'origin',) Consider an 'Event' Model designed to store records for events occurring at a specific origin … -
I am trying to host my Django project in heroku, but i am getting an error when i am collecting static files with python manage.py collectstatic
I am trying to host my Django project in heroku, but i am getting an error when i am collecting static files with python manage.py collectstatic. I have looked for this file 'plugins/flot/jquery.flot.js.map' in my plugin folder, but i can't find it anywhere. whitenoise.storage.MissingFileError: The file 'plugins/flot/jquery.flot.js.map' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000001BE271A1810> I tried running python manage.py collectstatic, reconfigure the manifestfile in the settings.py, but no solution. -
Can I run python 3.11 django application on centOS 7? Failing to execute wsgi script
I am trying to run my django application based on python version 3.11.5 on centOS 7 with openssl version 3.0.11. My application is not able to find math module which comes in-built with python installation. But I am able to import math module in the python script. I am getting the below error, when I try to run my application on server: [Tue Oct 24 20:44:17.092551 2023] [wsgi:error] [pid 30479] [client 129.214.105.163:35318] mod_wsgi (pid=30479): Failed to exec Python script file '/var/www/html/hmi.hmt/HMT/HMT/wsgi.py'. [Tue Oct 24 20:44:17.092643 2023] [wsgi:error] [pid 30479] [client 129.214.105.163:35318] mod_wsgi (pid=30479): Exception occurred processing WSGI script '/var/www/html/hmi.hmt/HMT/HMT/wsgi.py'. [Tue Oct 24 20:44:17.116764 2023] [wsgi:error] [pid 30479] Traceback (most recent call last): [Tue Oct 24 20:44:17.116826 2023] [wsgi:error] [pid 30479] File "/var/www/html/hmi.hmt/HMT/HMT/wsgi.py", line 17, in <module> [Tue Oct 24 20:44:17.116976 2023] [wsgi:error] [pid 30479] from django.core.wsgi import get_wsgi_application [Tue Oct 24 20:44:17.117017 2023] [wsgi:error] [pid 30479] File "/var/www/html/new_env/lib/python3.11/site-packages/django/__init__.py", line 1, in <module> [Tue Oct 24 20:44:17.117097 2023] [wsgi:error] [pid 30479] from django.utils.version import get_version [Tue Oct 24 20:44:17.117130 2023] [wsgi:error] [pid 30479] File "/var/www/html/new_env/lib/python3.11/site-packages/django/utils/version.py", line 1, in <module> [Tue Oct 24 20:44:17.117200 2023] [wsgi:error] [pid 30479] import datetime [Tue Oct 24 20:44:17.117225 2023] [wsgi:error] [pid 30479] File "/var/www/html/Python-3.11.6/Lib/datetime.py", line 12, … -
Supervisor (superuser) approval of root superuser login in Django
In my Django project with two superusers called root and supervisor, I'm trying to implement the following flow: When root logs into the application, he is directed to a 'waiting for authorisation' page In the meantime, an email is sent to the supervisor containing the OTP in plain text as well as a parameterised link (containing the OTP and session token) When the supervisor clicks this link, approval via OTP verification for root occurs If authentication is successful, the supervisor sees a message saying OTP authentication successful, and in the meantime, the root user is redirected from the waiting page to the landing page If authentication fails, root and the supervisor are shown a message on the page saying that the OTP authorisation failed The only user who needs OTP authentication is root and approval can only be granted by supervisor. My first approach had been to trigger OTP generation when root logs in, root gets redirected to a waiting page. Once the supervisor clicks the link, root is redirected to the landing page All my code was working except for the part where root gets redirected from the waiting area to the landing page. My current approach is to … -
Geographic point created in admin Django panel is not displayed correctly located in the html
I've created a model with postgis and rendered the templates with Folium. But when rendering the html. Geographic points appear in a geographic area that does not correspond. I've checked the srid and from what I've read they come by default at 4326 or WGS84. Can anyone help me fix this? models.py from django.contrib.gis.db import models class Location(models.Model):name=models.CharField(max_length=250,verbose_name='nombre arbol') punto=models.PointField() def str(self): return f"{self.punto}"` views.py from django.shortcuts import renderimport foliumfrom .models import * def home(request): locations=Location.objects.all()initialMap=folium.Map(location=[-33.56919516402464, -70.81542789027874], zoom_start=18) for location in locations: folium.Marker(location.punto ,popup='Arbol'+ location.punto ).add_to(initialMap) context={'map':initialMap._repr_html_(),'locations':locations} return render(request, 'survey/home.html',context) admin.py from django.contrib import adminfrom .models import * admin.site.register(Location) error points This is where the dots should appear I need to know what I need to set so that the points appear where they correspond geographically where I created them (I created them from the Django admin panel) Point Creation from admnin panel here is the libs installed on my venv asgiref==3.7.2 branca==0.6.0 certifi==2023.7.22 charset-normalizer==3.3.1 Django==4.2.6 folium==0.14.0 GDAL @ file:///-/Downloads/GDAL-3.4.3-cp311-cp311-win_amd64.whl#sha256=f78861fb5115d5c2f8cf3c52a492ff548da9e1256dc84088947379f90e77e5b6 idna==3.4 Jinja2==3.1.2 MarkupSafe==2.1.3 numpy==1.26.1 psycopg2==2.9.9 requests==2.31.0 sqlparse==0.4.4 tzdata==2023.3 urllib3==2.0.7 I would appreciate your help, thank you very much for your time. -
How to fix in django "Page not found (404)" error ("Django tried these URL patterns... The empty path didn't match any of these.")
As a newbie to Django, I encountered the same problem as many before me. I would appreciate if you didn't mark my question as a double immediately because I checked the fixes those old posts suggested but to no avail, unfofrtunately. When I start server I get: Page not found (404). Using the URLconf defined in shops_online.urls, Django tried these URL patterns, in this order: admin/ api/organizations/ [name='organizations-list'] api/organizations/<int:id>/shops_file/ [name='get-shops-file'] api/shops/<int:id>/ [name='shop-view'] api/v1/token/ [name='token_obtain_pair'] api/v1/token/refresh/ [name='token_refresh'] api/v1/token/verify/ [name='token_verify'] docs/ [name='schema-swagger-ui'] The empty path didn’t match any of these. Here`s my views.py: from django.shortcuts import render from rest_framework.views import APIView from .models import Shop, Organization from shop.serializers import OrganizationSerializer, ShopSerializer from rest_framework.response import Response from rest_framework import status import pandas as pd import logging from django.http import HttpResponse from django.core.mail import send_mail from background_task import background from background_task.models import Task from background_task.models import Task from .tasks import send_email_task from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @api_view(['GET']) @permission_classes([IsAuthenticated]) class OrganizationListView(APIView): def get (self, request): try: organizations = Organization.objects.filter(is_deleted=False) serializer = OrganizationSerializer(organizations, many=True) # logging logging.info('GET request was successful') return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: logging.error(f'An error occurred while executing the request: {e}') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['PUT']) … -
Automatically refresh Django admin panel
I'm wanting to automatically refresh/update a model in the admin page to show updated data. How can I modify the admin panel to do that?