Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django GIS: initGEOS_r symbol not found on MacOS
I'm experiencing an issue with Django GIS on my MacOS machine. When I try to run my Django application, I get the following error: Traceback (most recent call last): File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/manage.py", line 22, in <module> main() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django_eventstream/models.py", line 7, in <module> class EventCounter(models.Model): File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/models/base.py", line 143, in __new__ new_class.add_to_class("_meta", Options(meta, app_label)) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/models/base.py", line 371, in add_to_class value.contribute_to_class(cls, name) File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/models/options.py", line 231, in contribute_to_class self.db_table, connection.ops.max_name_length() ^^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/utils/connection.py", line 15, in __getattr__ return getattr(self._connections[self._alias], item) ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/utils/connection.py", line 62, in __getitem__ conn = self.create_connection(alias) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/utils.py", line 193, in create_connection backend = load_backend(db["ENGINE"]) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/rowsen2904/Documents/Programming/projects/gozle_taxi/venv/lib/python3.12/site-packages/django/db/utils.py", … -
Access to the searched word in Filters through the Table class
Friends, I have a table (django-tables2) and a search filter called 'comment'. (django-filters) I want to access the searched word inside the Table class. For example, inside the qs() event or somewhere else, I pass it to the request, so that I can access it on the other side in the Table class. class CommentFilter(FilterSet): class Meta: model = Comments fields = ['comment'] @property def qs(self): parent = super().qs # here I want to pass it search_key=self.data.get('comment') return parent The table class : class CommentTable(tables.Table): def render_comment(self, record): return record.comment -
two word param search
my instance's name is "hello world",just imagine in an urgent situation, i am going to search with param as "helloworld". how to handle without space cases if q: normalized_q = q.replace('_', ' ').replace('-', ' ').replace('/', ' ').strip() programs = programs.annotate( search=SearchVector( Replace(Replace(Replace('marketing_title', Value('_'), Value(' ')), Value('-'), Value(' ')), Value('/'), Value(' ')), Replace(Replace(Replace('slug', Value('_'), Value(' ')), Value('-'), Value(' ')), Value('/'), Value(' ')), Replace(Replace(Replace('name', Value('_'), Value(' ')), Value('-'), Value(' ')), Value('/'), Value(' ')) ) ) search_query = SearchQuery(normalized_q) programs = programs.filter( Q(search=search_query) | Q(name__icontains=normalized_q) | Q(program_duration__icontains=normalized_q) ) -
Error initializing the from_config() function in teh embedchain package
I am facing an issue in initializing the from_config() function of embedchain package: Here is my code: from embedchain import App from openai import OpenAI import yaml def initialize_bots(config_filename='config.json'): global news_bot, email_bot, link_inserter_bot, image_inserter_bot, article_bot # Load the JSON configuration directly # Determine the base directory based on whether the script is running as a standalone executable or as a script if getattr(sys, 'frozen', False): # Running as an executable base_directory = sys._MEIPASS # Temporary folder where the executable's data is unpacked else: # Running as a script base_directory = os.path.dirname(os.path.abspath(__file__)) config_file_path = os.path.join(base_directory, config_filename) # Debug statement: if os.path.exists(config_file_path): print(f"{config_filename} is present in the base directory.") else: print(f"{config_filename} is NOT present in the base directory.") # Check if the configuration file exists if not os.path.exists(config_file_path): raise FileNotFoundError(f"The configuration file {config_file_path} does not exist.") # Load the configuration file with open(config_file_path, 'r') as file: config_data = json.load(file) # Retrieve models and selected option from the configuration models = config_data.get('Models', {}).get('models', None) selected_option = config_data.get('Settings', {}).get('selected_ai_option', None) # Ensure models is not None if models is None: raise ValueError("Models configuration is missing or incorrectly set in the configuration file.") # Initialize news_bot config_path = os.path.join(base_directory, 'config', 'openai.yaml') # -------- Debug statement … -
how to display data from two Django model classes in a template by id?
I am new in django. I am try to make my first app called blog.This application contains two classes (with articles) finnews and fingram, I need to display all articles finnews and fingram on one template (I got it). I also need that from this template, the user clicks on the title of the article to go to the template with the full text of the article - and here with this I have problems. I'm reading the documentation and can't figure out how to fix the problem. Clicking on the finnews header results in a 404 error, and clicking on the fingram header results in a 'blogid() got an unexpected keyword argument 'id'' error. So far I'm reading the documentation and can't figure out how to fix it. urls.py for all project urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py for blog app def blogmain(request): all_fingrams = Fingram.objects.order_by('-id') all_finnewss = Finnews.objects.order_by('-id') data = { 'all_fingrams': all_fingrams, 'all_finnewss': all_finnewss, } return render(request,'blog/financial-news.html', data) def blogid(request): single_fingram = get_object_or_404(Fingram, pk=id) single_finnews = get_object_or_404(Finnews, pk=id) data = { 'single_fingram' : single_fingram, 'single_finnews' : single_finnews, } return render(request,'blog/financialarticle.html', data) urls.py for blog app urlpatterns = [ path('', views.blogmain, name='blogmain'), … -
Which Python library should I use to convert my HTML along with css into Docx file using Django?
I'm developing a Django app where users submit a NOC form. The information is stored in the database, and based on that data, I need to generate a visa application that should be downloadable in .docx format. I tried using pypandoc to convert HTML into DOCX, but the problem is that the CSS is not rendering in the output document. Here is my current approach: #Code for Generating the DOCX File: @login_required(login_url='login') def generate_noc_doc(request, noc_id): print("Generating NOC DOCX") # Fetch the NOC instance noc_instance = get_object_or_404(NOC, id=noc_id) grade = noc_instance.grade.strip() if noc_instance.grade else "" # Fetch employee ID and visa type from NOC instance employee_id = noc_instance.applicant_id visa_type = noc_instance.type_noc.lower() additional_travelers = noc_instance.additional_travelers.all() # Prepare family members text if there are additional travelers if noc_instance.no_of_travelers > 0: travelers_list = [f"({traveler.relationship_with_traveler}) named {traveler.additional_passport_name} bearing Passport No. {traveler.additional_passport_no}" for traveler in additional_travelers] family_members_text = ", ".join(travelers_list) else: family_members_text = "" # Fetch employee data based on applicant_id employee = Employees.objects.get(EmployeeID=noc_instance.applicant_id) # Determine pronouns based on gender if employee.Gender.lower() == 'male': pronoun_subjectC = 'He' pronoun_subjectS = 'he' pronoun_object = 'him' pronoun_possessive = 'his' elif employee.Gender.lower() == 'female': pronoun_subjectC = 'She' pronoun_subjectS = 'she' pronoun_object = 'her' pronoun_possessive = 'her' else: pronoun_subjectC = 'They' … -
Self-referential relationship or Different Model (Django referral system)
The first example implements Self-referential relationship: class User(models.Model): username = models.CharField(max_length=50, null=True) referrer = models.ForeignKey("self", related_name='referrals', null=True, blank=True) referrer_bonus = models.IntegerField(default=0) referral_bonus = models.IntegerField(default=0) The second option uses an intermediate model: class Referral(models.Model): referrer = models.ForeignKey(User, on_delete=models.PROTECT, related_name="referrals") referral = models.OneToOneField(User, on_delete=models.PROTECT, related_name='referral') referrer_bonus = models.IntegerField(default=0) referral_bonus = models.IntegerField(default=0) The question is that one referral can have one referrer. But a referrer can have many referrals. What approach will be better if I need to use anotation to calculate the total bonus and the number of referrals. And which option will be optimal for performance? -
Updating Request Headers in Django Middleware
Before I start complaining about my problem, I have to admit, that I'm not sure if my approach is the best way to handle my problem. I'm using Nuxt as my Frontend and I want to check/renew the JWT access token if it is expired, but the refresh token is still valid. Hey, I'm currently trying to write a middleware in Django, which is responsible for updating the JWT access token. However, the test says that I'm not authorized, even though I've updated the header. class JWTRefreshMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request: HttpRequest): if request.headers.get("Authorization"): try: AccessToken( str(request.headers.get("Authorization")).split(" ")[1], verify=True ) except TokenError: if refresh_token_cookie := request.COOKIES.get("refresh_token"): try: refresh_token = RefreshToken(refresh_token_cookie, verify=True) user = CustomUser.objects.get( id=refresh_token.payload.get("user_id") ) new_access_token = str(AccessToken.for_user(user)) request.META["HTTP_AUTHORIZATION"] = ( f"Bearer {new_access_token}" ) except TokenError: pass response: HttpResponse = self.get_response(request) return response The endpoint which I'm trying to call looks like the following: from ninja_jwt.authentication import JWTAuth router = Router() @router.get("/profile", response={200: UserProfileResponse}, auth=JWTAuth()) def get_user_profile(request): # Some Code I've also tried to override request.headers["Authorization"], but... TypeError: 'HttpHeaders' object does not support item assignment -
Elegant way to add a list view test case in drf
I have one concern in writing the test code for list view. For DRF's list view, it responds to multiple data. What should I do if I assume that the response.data object is a model with many fields? response.data --> [{"id": 1, "field1": "xxx", "field2": "yyy"....}, {"id": 2, ...}, ...] Too much input is required to compare with static data when a returns a lot of field data. def test_xx(self): self.assertEqual(response.data, [{"id": 1, "field1": "xxx", ..., "field12": "ddd", ...}, ...]) Currently, the way I came up with is as follows. I created an example model called Dog. class Dog(models.Model): ... hungry = models.BooleanField(default=False) hurt = models.BooleanField(default=False) As an example, let's say there is a class called Dog and there is logic in View to get a list of hungry dogs. I'm going to make a test about the logic of get a list of hungry dogs. class ... def test_dog_hungry_list(self): response = client.get("/api/dog/hungry/") expected_response = Dog.objects.filter(hungry=True) self.assertEqual(response.data, expected_response) The two values that I want to compare with assertEqual, response and expected_response, are of different types. response --> Response expected_response --> Queryset In the case of response.data, Serializer is applied, so when it's in dict form, I want to compare it … -
Prepend Text in Crispy Forms - Django
I have a form that works generally as expected, but I am trying to prepend some text on one of the fields to make it more user-friendly. In this case, all entries in the "RFP Control Number" field should start with "RFP-" so I want to use crispy forms to prepend that text. I have followed the setup in the crispy forms documentation to the best of my ability, but am not having any luck getting the prepended text to show up. Any ideas? The documentation is linked below: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html and a simplified version of my form is included below as well. Greatly appreciate any help! Please let me know if you have any questions, or if any additional information is needed. class ProposalForm(forms.ModelForm): class Meta: model = Proposal fields = [ 'organization', 'rfp_control_number', ] def __init__(self, *args, **kwargs): super(ProposalForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout( 'organization', PrependedText('rfp_control_number', 'RFP-'), Submit('submit', 'Submit', css_class='btn btn-primary'), ) I tried the few different syntaxes listed in the documentation website included in my post to no avail. I have looked online for articles and watched YouTube videos about Crispy Forms, but I have not found anything that covers this directly. … -
(fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples
I created this model below and I was working fine for almost the whole week. Closed the server and restarted it again and it threw me the (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples error. Used django documentation exactly, still no solution. `class Inspection(models.Model): RESULT_CHOICES = [ ("PR" "Passed"), ("PR" "Passed with minor Defects"), ("PR" "Passed with major Defects"), ("FR" "Failed due to minor Defects"), ("FR" "Failed due to major Defects"), ("FR" "Failed"), ] vin_number = models.ForeignKey(Vin, on_delete=models.CASCADE, related_name='inspections') inspection_number = models.CharField(max_length=20) year = models.CharField(max_length=4) inspection_result = models.CharField(max_length=30, choices=RESULT_CHOICES) ag_rating = models.CharField(max_length=30) inspection_date = models.DateField() link_to_results = models.CharField(max_length=200) def __str__(self): return self.inspection_number` I tried to: YEAR_IN_SCHOOL_CHOICES = { "FR": "Freshman", "SO": "Sophomore", "JR": "Junior", "SR": "Senior", "GR": "Graduate", } but still didn't work. Can even migrate due to the error -
How to make function, after specific time/minute the status of post change status using django?
i want to create a function in views or html file after 15 seconds , the status of post from pending to activa using django? tried to look for solutions but didnt understand. Also looked to ai to see what type of answer gave , but wanted to use traditional help to understand better -
How to run react code to render a webpage and display to user?
Say I have some generated react code that I want to display to the user for them to click through and comment on. The user isn't the one coding the website, I just want to show them how the generated website looks so they can make some comments on it. An example of the generated code could look like this: import { useState } from 'react'; import { Card, CardHeader, CardContent } from '@/components/ui/card'; import { MailIcon, GithubIcon, LinkedinIcon } from 'lucide-react'; export default function Website() { const [activeTab, setActiveTab] = useState('about'); return ( <div className="min-h-screen bg-gray-100 p-8"> {/* Navigation */} <nav className="bg-white shadow-lg rounded-lg p-4 mb-8"> <div className="flex justify-between items-center"> <h1 className="text-2xl font-bold text-blue-600">My Website</h1> <div className="space-x-4"> <button onClick={() => setActiveTab('about')} className={`px-4 py-2 rounded ${activeTab === 'about' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > About </button> <button onClick={() => setActiveTab('projects')} className={`px-4 py-2 rounded ${activeTab === 'projects' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > Projects </button> <button onClick={() => setActiveTab('contact')} className={`px-4 py-2 rounded ${activeTab === 'contact' ? 'bg-blue-600 text-white' : 'text-gray-600'}`} > Contact </button> </div> </div> </nav> {/* Main Content */} <div className="max-w-4xl mx-auto"> {activeTab === 'about' && ( <Card> <CardHeader> <h2 className="text-2xl font-bold">About Me</h2> </CardHeader> <CardContent> <p className="text-gray-600"> Hello! I'm a … -
How to skip django DeleteModel operation
I have deleted a model, Django creates a DeleteModel operation that I'd like to skip because i don't want to drop the table yet, but i also don't want to keep the model around. How can i skip dropping the table in this case but still delete the model? I have tried commenting out the operation in the migration file but the next time you run makemigrations command the operation is recreated. -
Handling Errors in Django Test Cases
I am currently writing test cases using Django and would like to improve the way we handle errors, particularly distinguishing between errors that arise from the test cases themselves and those caused by the user's code. Context: Let’s say a user writes a function to fetch and increment the likes count of a post: def fetch_post(request, post_id): try: post = Post.objects.get(id=post_id) except Post.DoesNotExist: raise Http404("Post not found") post.likes += 1 post.save() return HttpResponse("Post liked") Here’s the test case for that function: from django.test import TestCase from project_app.models import Post from django.urls import reverse from django.http import Http404 class FetchPostViewTests(TestCase): def setUp(self): self.post = Post.objects.create(title="Sample Post") def assertLikesIncrementedByOne(self, initial_likes, updated_post): if updated_post.likes != initial_likes + 1: raise AssertionError(f'Error: "Likes cannot be incremented by {updated_post.likes - initial_likes}"') def test_fetch_post_increments_likes(self): initial_likes = self.post.likes response = self.client.get(reverse('fetch_post', args=[self.post.id])) updated_post = Post.objects.get(id=self.post.id) self.assertLikesIncrementedByOne(initial_likes, updated_post) self.assertEqual(response.content.decode(), "Post liked") def test_fetch_post_not_found(self): response = self.client.get(reverse('fetch_post', args=[9999])) self.assertEqual(response.status_code, 404) Scenario: Now, if a user accidentally modifies the code to increment the likes by 2 instead of 1 and didn't save the post object. # Wrong code that will fail the test case def fetch_post(request, post_id): try: # used filter() method instead of get() method post = Post.objects.filter(id=post_id) except Post.DoesNotExist: … -
AxesBackend requires a request as an argument to authenticate
I need to add a restriction on account login attempts to my django site, I found the popular django-axes library, followed the documentation and code examples, but when I try to log in to my account (whether the password is correct or not) I get the error AxesBackend requires a request as an argument to authenticate even though my code follows the instructions exactly and I'm passing the request. Here is all the code that is somehow related to this: settings.py INSTALLED_APPS = [ ... 'axes', ] MIDDLEWARE = [ ... 'axes.middleware.AxesMiddleware', ] AXES_FAILURE_LIMIT = 4 AXES_RESET_ON_SUCCESS = True AXES_COOLOFF_TIME = 1 AUTHENTICATION_BACKENDS = [ 'axes.backends.AxesBackend', # Axes must be first 'django.contrib.auth.backends.ModelBackend', ] AUTH_USER_MODEL = "users.User" LOGIN_URL = "/user/login/" views.py from django.contrib import auth, messages def login(request): if request.method == "POST": form = UserLoginForm(data=request.POST) if form.is_valid(): username = request.POST["username"] password = request.POST["password"] user = auth.authenticate(request=request, username=username, password=password) if user: auth.login(request, user) redirect_page = request.POST.get("next", None) if redirect_page and redirect_page != reverse("user:logout"): return HttpResponseRedirect(request.POST.get("next")) return HttpResponseRedirect(reverse("main:main_page")) else: form = UserLoginForm() context = {"title": "Вход", "form": form} return render(request, "users/login.html", context) Django==5.0.4 django-axes==6.5.2 I would be very grateful for your help! Indicated above. Here is the exact output in the console that … -
error: PermissionError(13, 'Access is denied', None, 5, None)
I have this error while working with celery [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return True, loads(get_payload()) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\queues.py", line 394, in get_payload with self._rlock: File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\synchronize.py", line 115, in __enter__ return self._semlock.__enter__() ^^^^^^^^^^^^^^^^^^^^^^^^^ PermissionError: [WinError 5] Access is denied During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 351, in workloop req = wait_for_job() ^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 480, in receive raise SystemExit(EX_FAILURE) SystemExit: 1 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 292, in __call__ sys.exit(self.workloop(pid=pid)) ^^^^^^^^^^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 396, in workloop self._ensure_messages_consumed(completed=completed) File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 406, in _ensure_messages_consumed if self.on_ready_counter.value >= completed: ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 3, in getvalue PermissionError: [WinError 5] Access is denied [2024-10-06 14:38:15,464: ERROR/SpawnPoolWorker-3] Pool process <billiard.pool.Worker object at 0x0000016C0BBF5A00> error: PermissionError(13, 'Access is denied', None, 5, None) Traceback (most recent call last): File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 473, in receive ready, req = _receive(1.0) ^^^^^^^^^^^^^ File "D:\study\learning-python\back-end\ecommerce\venv\Lib\site-packages\billiard\pool.py", line 445, in _recv return … -
How are emails set up for employees in an organization?
I'm pretty new to the SMTP aspect... I have been trying to understand how setting up an email account for each user (employee) in an enterprise application works. For example, let's say I am using Brevo (SendinBlue) as my SMTP service and I want to create for each lecturer that I have in my application, say john.smith@havard.org Do I create another sender on Brevo for each of the accounts I want to create and would the user be able to login to his email and view emails sent to him? And I would be able to send a dynamic email from my backend using from his email Just, how does it work? -
CommandError: Unknown command:
I created a custom command and want to run it automatically on start My command file # project/parser_app/management/commands/create_schedules.py class Command(loaddata.Command): def handle(self, *args, **options): # some code Added command to wsgi.py import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("makemigrations") call_command("migrate") call_command("collectstatic", interactive=False) call_command("create_schedules parser_app/management/commands/schedule_fixtures.json") I can run in console command python manage.py "create_schedules parser_app/management/commands/schedule_fixtures.json" and everything is working but when I added command to wsgi.py (to run on start) import os from django.core.wsgi import get_wsgi_application from django.core.management import call_command os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings') application = get_wsgi_application() call_command("makemigrations") call_command("migrate") call_command("collectstatic", interactive=False) call_command("create_schedules parser_app/management/commands/schedule_fixtures.json") I have an error raise CommandError("Unknown command: %r" % command_name) django_1 | django.core.management.base.CommandError: Unknown command: 'create_schedules parser_app/management/commands/schedule_fixtures.json' -
In Django, how to retrieve an id to use in a dynamic link?
I have a Django app. In my sidebar I have a navigation link that goes to a list of reports. That link needs an id to get the correct list of reports. The <li> element in base.html that links to the ga_reports page is below. This link needs the app_config.id to resolve correctly. With this element {{ app_config.id }} does not exist because {{ app_config }} does not exist. I will add that on the Reports page, this link works as {{ app_config }} gets created. Why does {{ app_config }} exist on the Reports page but not on the parent page? <li class="relative px-12 py-3"> <a class="inline-flex items-center w-full text-sm font-semibold transition-colors duration-150 hover:text-gray-800 dark:hover:text-gray-200 " href="/base/ga_reports/{{ app_config.id }}"> <span class="ml-4">Reports</span> </a> </li> These are entries from base/urls.py path('app_config', app_config_views.app_config, name='app_config'), ... path('ga_reports/<int:app_config_id>', ga_views.ga_reports, name='ga_reports'), The AppConfiguration model is included on base/views.py from .models import AppConfiguration This is base/ga_views.py @login_required def ga_reports(request, app_config_id): app_config = AppConfiguration.objects.filter(id = app_config_id).first() if not app_config: messages.error(request, "Invalid Configuration") return redirect('app_config') return render(request, 'base/ga_reports.html', {'app_config': app_config}) This is app_config_views.py. @login_required def app_config(request): app_configs = [] for app_type in APP_TYPE: app_type_subscription = UserSubscription.objects.filter(user_id = request.user.id, app_type = app_type[0], is_active = True, is_expired = False).first() app_configuration … -
What is the best way to sanitize uploaded filenames in Django?
I tried using slugify however it made too many changes to the original filename, such as removing spaces joining the file extension to the rest of the name. I'd like to simply ensure that names are safe: 1. Not too long and 2. Prevent any attacks that can be carried out using the file's name(such as path traversal). My app allows users to upload files(files are uploaded to DigitalOcean Spaces via my app) and filenames are stored using models.py/ -
How to get the estimated remaining time of an already started Celery task?
I am using django with Celery and redis. I would like that when a user initiates a Celery task my app estimates the amount of time left until the task is completed(so that I can, for example, represent this data to the frontend as a progress bar). For example, given this polling function: views.py: @csrf_protect def initiate_task(request): task = new_celery_task.delay(parmeter_1, parametr_2) @csrf_protect def poll_task_status(request, task_id): #task_id provided by frontend import base64 task_result = AsyncResult(task_id) if task_result.ready(): try: ... response_data = { 'status': 'completed', } except Task.DoesNotExist: return JsonResponse({'status': 'error', 'message': 'There has been an error'}, status=404) elif task_result.state == 'REVOKED': return JsonResponse({'status': 'terminated', 'message': 'Task was terminated'}) else: #add code to calculate estimated remaining time here remaining_time_est = estimate_remaining_time() #estimate task by id return JsonResponse({'status': 'pending' #add code to return estimated remaining time here 'est_remaining_time':remaining_time_est }) and task: task.py: app = Celery('myapp')# @app.task def new_celery_task(arg_1, arg_2): #complete task How would I estimate the remaining time left on an initiated task? -
My django project shows no error in terminal using vs code it got right request but on browser it not showing what i expected the output, not updated
I am facing some problem in VS code in django project. After saving the code in vs code, even after running the server in the terminal, I am not getting the output of the code in the browser normally. pylance - does not show any errors. The update of get request in terminal comes every time after running server but still doesn't show data in browser. Despite not giving pylance error, I check the code 5-6 times by myself. There is no error. I have not installed pylint as I am still in medium level pylint asks to follow the actual code structure of pep8 which is a bit tough now so I did not install it, still why is this happening. Tried a simple project for 2 hours yesterday and couldn't figure out the error, I was sure the code was fine. Running the same project this morning, everything is running fine. I am reading the same problem again today. Even after browser reload/hard reload, browser change, even port number change, the same problem is happening again and again. I want a solution, can someone tell me where the problem is? Point to be noted, the terminal shows no … -
Best approach for showing custom data in the Volt template dashboard for Django
I am currently building a personal app and would like to use the Volt template for Django. The link to the template is here: https://tb-volt-dashboard-django.appseed-srv1.com/dashboard.html I want to update the chart in the dashboard to use custom generated data from the view. What's the best approach/ recommended approach to do that? I see currently that the data is being hard-coded in the volt.js file in the Volt directories. -
How to Separate Django Channels WebSockets into a Scalable Microservice for a Multiplayer Game?
I have a Django web application that includes a multiplayer game feature, using Django Channels for real-time communication over WebSockets. Currently, the WebSockets functionality (real-time game updates, player interactions, etc.) is handled directly within the main Django application. As the project grows, I'm considering separating the WebSockets/game logic into its own microservice for scalability and maintainability. My goals are to have a dedicated microservice that handles all real-time communication and game logic, and to be able to scale this service independently of the main Django web app. Here are the specific details of my setup: Backend Framework: Django (with Django Channels for WebSockets) Current Architecture: Monolithic Django app with WebSockets handled directly in the same codebase - as the rest of the application Desired Architecture: Separate microservice dedicated to handling WebSocket connections and game logic, which can be scaled independently Questions: What are the best practices for separating WebSocket real-time communication into a dedicated microservice? What tools or technologies can be useful for building this scalable WebSocket-based microservice? I'd like not to use another django services but something lighter How should communication between the main Django app and the WebSocket microservice be handled (e.g., API, message queues, etc.)? How should …