Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing information from view to form with FormWizard
I'm trying to pass data from my view to my form class using WizardView. Without WizardView, I do this using get_forms_kwargs() like the below: def get_form_kwargs(self): kwargs = super(MenuAdd, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs And in my form class I use: def __init__(self, *args, **kwargs): self.month = kwargs.pop('month', None) All good - I'm able to use 'month' for validation in e.g. clean(). When I'm using WizardView though, I'm specifying the step in get_forms_kwargs() as follows, per the docs: def get_form_kwargs(self, step=0): kwargs = super(MenuAddWizard, self).get_form_kwargs() kwargs.update({'month': self.kwargs['month']}) return kwargs My get_form() doesn't like this: File "python312\Lib\site-packages\formtools\wizard\views.py", line 311, in post return self.render_next_step(form) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "python312\Lib\site-packages\formtools\wizard\views.py", line 322, in render_next_step new_form = self.get_form( ^^^^^^^^^^^^^^ File "myproject\views.py", line 1614, in get_form form = super().get_form(step, data, files) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "python312\Lib\site-packages\formtools\wizard\views.py", line 432, in get_form return form_class(**kwargs) ^^^^^^^^^^^^^^^^^^^^ TypeError: BaseFormSet.__init__() got an unexpected keyword argument 'month' Any idea how to properly pass kwargs (or any other way) to a form with Django Form Wizard? -
I don't understand why the Django built in 'Reverse' function is not working
I am trying to learn Django in python, when today, I stumbled upon this error: "NoReverseMatch at /downloader/ Reverse for 'login' not found. 'login' is not a valid view function or pattern name." I am not sure why this is happening, but here is my code: (this is the views.py code) if not request.user.is_authenticated: return HttpResponseRedirect(reverse("login")) (here is my urls.py) urlpatterns = [ path("", views.index, name="index"), path("add/", views.add, name="add"), path('scrape/', views.scrape_all, name='scrape_all'), path('find_url/', views.find_song_urls, name='find_song_urls'), path('downloader/', views.downloader, name="downloader"), path("login/", views.login_view, name="login"), path("logout/", views.logout_view, name="logout"), path("create_acount/", views.create_account, name="create_account") ] I was just trying to make a login function with my project but I don't get what I am doing wrong. -
How to know if the syntax of my urls is a valid django url syntax?
I generate my URLs dynamically and I want to know if there is a way to check if the syntax is valid or not. Because I'll create my URL from the Django admin panel, and if the syntax isn't correct for Django, the code will crash. For example, if I make a mistake and create a URL like this: test/<:custom_pk>/`, the app will crash, and I won't be able to modify it from the admin panel because of the crash. The error is : File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 307, in init self.converters = _route_to_regex(str(route), is_endpoint)[1] File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 277, in _route_to_regex raise ImproperlyConfigured( django.core.Exceptions.ImproperlyConfigured: URL route 'test/<:custom_id>' uses parameter '<:custom_id>' which isn't a valid Python identifier. I try to send to my urlpatterns an url which had an incorrect syntax and i except this error : File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 307, in init self.converters = _route_to_regex(str(route), is_endpoint)[1] File "usr/local/lib/python3.12/site-packages/django/urls/resolvers.py", line 277, in _route_to_regex raise ImproperlyConfigured( django.core.Exceptions.ImproperlyConfigured: URL route 'test/<:custom_id>' uses parameter '<:custom_id>' which isn't a valid Python identifier. -
A very faulty Django when it comes to rendering image in my template
Right lets try this again. My Django images are not showing in my template. Despite setting this up correctly. This is my setup - a fully replicable setup -, as follows: # settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #urls.py from django.urls import path, include from . import views from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.views.static import serve urlpatterns = [ path('<uuid:uuid>', views.details), ] # Only for development. Do not use this in production. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) #views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from django.template import loader from .models import MediaModule def details(request, uuid): articles = MediaModule.objects.all().values() article = get_object_or_404(MediaModule, uuid=uuid) title = article.article_headline return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles}) #media-article.html <img src="{{article.article_image.url}}" alt="{{article.article_image.url}}"/> #models.py from django.db import models import uuid # Create your models here. class MediaModule(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_image = models.ImageField(upload_to='media/assets') This is my file directory layout: Root-| media-| templates-| models.py views.py urls.y media-article.html media-| assets-| image.jpg Is there a valid reason as to why, hen I go to the debug console in my browser - does it give me a 404 error despite the … -
bypassing integrityError gotten from unique field in a django model
I want a unique field generated at database level. The way unique=True works is it raises an error if it see's a duplicate value in the database. I don't want that though, I want it to simply generate a new unique number instead of raising an error. This is the model that gives a user an account number, Any help will be much appreciated class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) account_number = ShortUUIDField(unique=True,length=10, max_length=25, prefix="217", alphabet="1234567890") -
In django how can I resolve a reverse error when copying text from an html table row and attempting to write it to a text file?
I have a django app with a page that shows a data table of text strings populated from a model. Each string is a website url. I need to be able to click on any one of these rows and have that url string written to a text file. What I have so far results in a 'reverse' error as soon as the server tries to load the home page. Here is the model: class Environment(models.Model): url = models.CharField(max_length = 250, null=True, blank=True) def __str__(self): return self.url Here is the view for the home page, which displays a list of urls populated from the model: def home(request): envs = Environment.objects.all() f = open('environment.txt', 'r') file_content = f.read() f.close() context = {'title':'Home Page', 'year':datetime.now().year, 'envs':envs, 'file_content':file_content} return render(request, 'app/home.html', context) here is the view for the writing of the url text to the file: def write_url_to_file(request, url): with open('environment.txt', 'w') as file: file.write(url) file.close() return redirect('app:home') Here is the url pattern: path('write-url/<str:url>/', views.write_url_to_file, name='write_url_to_file'), Here is the template tag. The idea is to click a url to write it to a text file: <table> <tr> <th>Environment</th> </tr> {% for env in envs %} <tr> <td><a href="{% url 'app:write_url_to_file' env.url %}">{{ env.url … -
Why do I get a server side HTTP 400 error when I try to access my django server with my mobile phone?
I have set up a simple, local running django server which provides buttons to trigger some bash commands on the server (currently my MacBook Pro). The output of these commands is then displayed on the website. Anyways: The website is working fine as long as I access it from the DuckDuckGo Browser on my MacBook. I also tried with the Brave Browser installed on my Desktop PC - works fine. Now, as I try to access the website from my iPhone, a connection is established, the buttons are working and also, the text on the buttons disappeared. But more importantly, I get a strange error on the server inside the console which is running the server. The error says: [26/Apr/2024 11:33:04] code 400, message Bad request version ('p¤\x99é4rÙu*\x08\x8dÎ\x06¨A©\x06\x8f?l\x19\x9fz\x97\x00,êê\x13\x01\x13\x02\x13\x03À,À+Ì©À0À/̨À') [26/Apr/2024 11:33:04] You're accessing the development server over HTTPS, but it only supports HTTP. Using WireShark, I compared the package traffic between the iPhone and the server, and between the desktop / macbook and the server. It was obvious that the phone tries to use HTTPS / TLS to connect to the server while the desktop / macbook connect using HTTP. But as this fails, the TLSv1 package contains the following alert … -
Why is Django randomly deleting images from my template for no reason
Django never ceases to baffle me with completely uncalled for actions. I I have a media article template which is derived from a Django model. All works a treat and looks awesome, except for the images. One minute they're present, the next Django needs a new glasses prescription as it suddenly decides it can't see the image which is blatantly in the directory with which I have set up. Here's my full reproduceable example and see if anyone can figure out why Django decides its not going to show the image: #models.py from django.db import models import uuid # Create your models here. .... uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) article_image = models.ImageField(upload_to='media/assets') .... In my views.py, I have the following: def details(request, uuid): articles = MediaModule.objects.all().values() article = get_object_or_404(MediaModule, uuid=uuid) title = article.article_headline return render(request, 'media-article.html', {'article': article, 'title':title, 'articles':articles}) The file directory is as follows: Root| |- media |- template | - media-article.html |- media | - assets | - image.jpg #media-article.html <img src="{{article.article_image}}" alt="{{article.article_image}}"/> Just why does Django think "Ah-hah, there's the image!", and then says "Actually, I'm going to deliberate pretend the image is not there, because I am going to be difficult now" Why does it … -
"Error: InconsistentMigrationHistory - Django migration admin.0001_initial applied before its dependency Users.0001_initial"
I am encountering an error while running `python manage.py migrate` in my Django project. The error message is as follows: It appears that there is an inconsistency in the migration history of my Django project. Specifically, the `admin.0001_initial` migration is being applied before its dependency `Users.0001_initial`. How can I resolve this issue and ensure that migrations are applied in the correct order? Thank you for your assistance. i tried python manage.py makemigrations and then python manage.py migrate Database connection is good even im able to see dabase table on server but on local machine there is no table \dt List of relations Schema | Name | Type | Owner --------+---------------------+-------+-------- public | django_content_type | table | cc_app public | django_migrations | table | cc_app (2 rows) -
Django-tables2 linkify to other app of project: TemplateDoesNotExist error
Since my project is a bigger one, I have several apps with each app having some database tables (with each table in its own file): project --project -all -overview -home In all/probe_list.html I have a table which displays Probe objects. I want to link the probe name to a details page that is in the overview app (overview/probe_details.html). The link works and shows the correct URL 127.0.0.1:8000/overview/probe_detail/1 but I get TemplateDoesNotExist error since django searches for all/probe_detail.html. project/urls.py urlpatterns = [ path('', include('home.urls')), path('all/', include('all.urls', namespace='all')), path('overview/', include('overview.urls', namespace='overview')), ] all/urls.py app_name = 'all' urlpatterns = [ path('probe_list', views.AllProbesView.as_view()), ] all/models/probe.py class Probe(Compound): targetName = models.CharField(max_length = 100, verbose_name="Target(s)") inVivoActivity = models.CharField(max_length=10, verbose_name="In vivo use"); mechanismOfAction = models.CharField(max_length = 255, verbose_name="Mechanism") def get_absolute_url(self): return reverse('overview:probe_detail', args=[str(self.id)]) def __str__(self): return f'{self.name}, {self.targetName}, {self.mechanismOfAction},{self.inVivoActivity}' class Meta: app_label = 'all' all/tables.py class AllProbesTable(tables.Table): name = tables.Column(linkify=True) class Meta: model = Probe template_name = "django_tables2/bootstrap5-responsive.html" sequence = ("targetName", "name", "mechanismOfAction" ,"inVivoActivity",) exclude = ("id",) all/views.py class AllProbesView(SingleTableView): model = Probe table_class = AllProbesTable queryset = Probe.objects.all() template_name = "all/probe_list.html" all/templates/all/probe_list.html {% load render_table from django_tables2 %} {% render_table table %} overview/urls.py app_name = 'overview' urlpatterns = [ path('probe_detail/<int:pk>', views.ProbeDetailView.as_view(), name="probe_detail"), ] overview/views.py (not ready … -
PostgreSQL: How to tag every table in my database? Generic Foreign Keys, array column, or other method
I'm currently designing a PostgreSQL database where I need to implement a tagging functionality. Essentially, any item from any table in my database can be tagged via key-value tags, very much like Azure tags. I'm considering different approaches for implementing this feature and I'm confused about the best approach: Using Django's Generic Foreign Keys: One approach I'm considering is leveraging Django's Generic Foreign Keys functionality to create a versatile "Tags" table that can reference any other table in the database. This allows flexibility and avoids complex logic. However, there might be drawbacks like performance implications or the database not making sense without Django's ORM. Manual Implementation in a single table, without Generic Foreign Keys: Another option is to implement the "Tags" table manually without relying on Django's Generic Foreign Keys. I would create a separate table that can reference any other table in the database, but without the use of formal foreign keys. This would require to either store some logic in the database or the backend, being more complex to maintain. Separate cross-reference tags table for each table: Alternatively, I could create a separate table (i.e. car_tags, house_tags, person_tags) for each table in my database that requires tagging. This … -
How do I setup "Django" to generate multiple 'STATIC_ROOT' deployment directories in its settings.py?
Here's the problem, when migrating multiple 'STATICFILES_DIRS', I am good to go, and the server continues to run with no errors... ... Here's the snippet to my 'STATICFILES_DIRS' ... ... STATIC_URL = 'Application/' #Multiple Static Directories STATICFILES_DIRS = [ os.path.join('Application', 'Bootstrap'), os.path.join('Application', 'html'), ] #End of Multiple Static Directories STATIC_ROOT = 'Application/templates/Application' ... ... As for the actual problem I've encountered during the "python3 manage.py runserver" command, the snippet error is this ... ... STATIC_URL = 'Application/' #Multiple Static Directories STATICFILES_DIRS = [ os.path.join('Application', 'Bootstrap'), os.path.join('Application', 'html'), ] #End of Multiple Static Directories #Multiple Static Root Directories STATIC_ROOT = [ os.path.join('Application', 'templates/Application'), os.path.join('Domains', 'https://example.com'), ] #End of Multiple Static Root Directories ... ... Are there any ways to solve this error for Django to read/generate multiple 'STATIC_ROOT' deployment directories? Regards, ~ Rickey Kenneybrew -
Create SQL function using Django migrations command
I am using Django Framework in Python with MySQL Database. For adding a table in the database, I create a class in models.py and then run python manage.py makemigrations. This creates the migration file in my app with the table columns details. Now, similarly, I want to create a new function in my database. For now, I create a new empty migration file in my app using python manage.py makemigrations --empty myApp and then add the SQL code to the migration file operations[ migrations.RunSQL('Create function SQL Code') ] This editing migration file can be done on a local or testing environment but is not advisable in the production environment. Is there any better way to create the MySQL function through Django Migrations command or models.py that works similarly to tables and creates functions only 1 time when we use the migrate command? -
Django: Change Datatable by input value [closed]
I have an input field where the user can input specific 'year', and it will show all related rows. It's not the search function that I want, this one is different. There are multiple rows that has the same information, so if I use the search bar, it won't give me rows from other 'year'. So all the info in my datatable will depend on what is in the input field. I'm not sure if you get what I mean. Thank you! -
How do I update status to either expired or active depending on date and time?
I have an application built in Django. The application allows businesses to manage their day-to-day operations and has features like; HR Management, Sales, Point of Sale, Accounting, etc. For businesses to be able to attach discounts on their products, I have created a Discount model: class Discount(CommonField): name = models.CharField(max_length=255, blank=True, null=True) discount = models.DecimalField(max_digits=15, decimal_places=2) discount_type = models.CharField(max_length=255, choices=DISCOUNT_TYPE_CHOICES, blank=True, null=True) discounted_products_count = models.PositiveSmallIntegerField(default=0) start_date = models.DateTimeField(blank=True, null=True) expiry_date = models.DateTimeField(blank=True, null=True) status = models.CharField(max_length=255, default="inactive", choices=DISCOUNT_STATUS) objects = DiscountModelManager() Discounts have a start date and an expiry date which have been included in the model, they also have a status field that will determine if the status is expired, active, or inactive. One of the challenges I was facing had to do with at what point I should update the status of discounts. To overcome this challenge, I created a Model Manager to have a central place where the logic of updating the status is placed; class DiscountModelManager(TenantAwareManager): def get_queryset(self): queryset = super().get_queryset() self.change_promo_code_if_end_date_extended(queryset) self.activate_discount_if_start_date_reached(queryset) self.expire_discount_if_expiry_date_reached(queryset) return super().get_queryset() def change_promo_code_if_end_date_extended(self, queryset): """ Activates promo codes if expiry_date has been extended and the status is expired. """ queryset.filter(expiry_date__gte=timezone.now(), status="expired").update(status="active") def activate_discount_if_start_date_reached(self, queryset): """ Activates promo codes if start_date has … -
Provider in create Social App in Django Administration is blank
I tried to do google auth in Django but got stuck when there wasn't any provider in the create social app i already creates the sites as my local host and tried changing site Id to 1 and 2 still it didnt show the problem INSTALLED APPS TEMPLATES I wanted to implement sign in with google but seeing a vid from youtube but i got stuck at the providers. In providers it should show google but it didn't i tried most things i know even though a beginner. Kindly help me. And it didnt show any error though. I can show u the code if u asked its just if i upload it notes as spam -
Trouble running react-google-drive-picker in Django
I'm attempting to implement a google drive picker in my django + react project: import React from 'react'; import { Button, Card, Image } from 'antd'; import useDrivePicker from 'react-google-drive-picker'; import { useState, useEffect } from 'react'; const { REACT_APP_GOOGLE_CLIENT_ID, REACT_APP_GOOGLE_API_KEY } = process.env; const Upload = () => { const [openPicker, data, authResponsive] = useDrivePicker(); const upload = (data) => { console.log("uploading") }; const handleOpenPicker = () => { try { openPicker({ clientId: REACT_APP_GOOGLE_CLIENT_ID, developerKey: REACT_APP_GOOGLE_API_KEY, viewId: 'DOCS_VIDEOS', showUploadView: true, showUploadFolders: true, supportDrives: true, multiselect: true, callbackFunction: (data) => { upload(data) }, }); } catch (error) { console.log(error); } }; return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '20px' }}> <h2>Select Videos from Google Drive</h2> <Button type="primary" onClick={() => handleOpenPicker()} style={{ marginBottom: '20px' }}> Open Drive Picker </Button> </div> ); }; export default Upload; I'm serving this using django, while running this in development (by running npm run start and opening http://localhost:3000) the google-picker works as expected. However when running running in in django by collecting static and serving it from http://localhost:8000, suddenly the popup will not open. Can anyone help me with what I'm missing here ? This is some of my django cors + … -
How to ignore the get_valid_name to sanitize the space and special characters
When we are uploading the files to azure storage via django, it's adding underscore if space or special characters are there in the filename and it's disturbing the functionality. Is there anyway we can ignore it or change it. I tried multiple suggestions but it's not working like custom storage options. If i'm trying the custom storage options, it's not uploading in blob storage but it's uploading project folder. Refer the code below i tried in custom storage, from django.core.files.storage import FileSystemStorage class CustomStorage(FileSystemStorage): def _save(self, name, content): return super(CustomStorage, self)._save(name, content) def get_valid_name(self, name): return name file_path = models.FileField(upload_to=get_upload_path, max_length=1000, storage=CustomStorage()) I have tried other suggestions, but nothing worked -
How to connect htmx with webstocket
I am building a real-time chatroom using htmx connect with webstocket in Django, when I try to send a message, the message is not showing and I am getting this error in the terminal "HTTP GET /?csrfmiddlewaretoken=frNekEsvdZ6jdJp7gYMF7pvXpnO11m3J3vOpJ7XCsAKLogIBuUpuKizmufpWRKxN&body=hi+aneeb 200 [0.04, 127.0.0.1:54773]" here my asgi.py file: import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from channels.security.websocket import AllowedHostsOriginValidator from channels.auth import AuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'a_core.settings') django_asgi_app = get_asgi_application() from a_realchat import routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns)) ), }) here my routing.py file: from django.urls import path from .consumers import * websocket_urlpatterns = [ path("ws/chatroom/chatroom_name",ChatroomConsumer.as_asgi()), ] here my consumers.py: from channels.generic.websocket import WebsocketConsumer from django.shortcuts import get_object_or_404 from .models import GroupChat,GroupMessage import json class ChatroomConsumer(WebsocketConsumer): def connect(self): self.user = self.scope['user'] self.chatroom_name = self.scope['url_route']['kwargs']['chatroom_name'] self.chatroom = get_object_or_404(GroupChat,group_name=self.chatroom_name) self.accept() def receive(self ,text_data): text_data_json = json.loads(text_data) body = text_data_json['body'] message = GroupMessage.objects.create( body=body, auther=self.user, group=self.chatroom, ) my .html file where i connecting the ws <form id="chat_message_form" class="w-full" hx-ext="ws" ws-connect = "ws/chatroom/TalkAboutPython" ws-send _="on htmx:wsAfterSend reset() me" > {% csrf_token %} {{ form }} </form> -
Django Language cookie issue
I'm trying to enable the secure and HttpOnly flags to the django cookies but not able to add it for the django_language. I have configured the following var in the settings file: CSRF_COOKIE_SECURE = True ### enabled secure flag CSRF_COOKIE_HTTPONLY = True ### enabled httponly flag SESSION_COOKIE_SECURE = True LANGUAGE_COOKIE_SECURE = True LANGUAGE_COOKIE_HTTPONLY = True -
How to implement voice activity detection and stop Twilio voice bot on customer interruption?
I am building a voice bot using Twilio and Django. I have set up an outbound call with media streaming, which is working fine. However, I want to implement voice activity detection so that if the customer interrupts while the voice bot is speaking, the bot stops speaking immediately. I am looking for guidance on how to achieve this using Twilio's Media Streams feature I have set up media streaming for the Twilio outbound call using the verb in the TwiML response. This is my view: class StartOutboundCallingView(APIView): client = Client(sid, token) def post(self, request, format=None): from_ = request.data.get("from") to = request.data.get("to") if "from" not in request.data or "to" not in request.data: return Response( {"Required Field": "from and to are required fields"}, status=status.HTTP_400_BAD_REQUEST, ) resp = VoiceResponse() call = self.client.calls.create( twiml=generate_twiml(), to=to, from_=from_, ) return Response({"call_id": call.sid}, status=status.HTTP_200_OK) this is how I am generating the twiml def generate_twiml(): return f''' ''' this is my websocket consumer class TwilioWS(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.grok_ai = None self.call_id = None self.stream_id = None self.transcriber = None self.tts = None self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1) self.loop = asyncio.get_event_loop() def connect(self): self.transcriber: DeepgramSTT = DeepgramSTT(self) self.transcriber.start_transcription() asyncio.run(self.init_grok()) return super().connect() async def init_grok(self) -> None: … -
Django models cannot be queried due to missing id field?
I currently am working on a django project for a discord bot. the issue that I am trying to resolve is that I cannot seem to query the data for one of my models. A piece of information that has been unclear to me that I am sure caused this issue was a series of migration issues I had trying to update my Character model with new relationships to the InventoryInstance model in a seperate app. when I boot up a django shell_plus session - I get this error when trying to query the Character Model: located in inventory.models In [1]: Character.objects.all() Out[1]: OperationalError: no such column: oblivionalchemy_character.inventory_instance_id Here is my Character and InventoryInstance models: located at oblivionalchemy.models class InventoryInstance(models.Model): character_name = models.ForeignKey('oblivionalchemy.Character', on_delete=models.CASCADE, null=True, related_name="character") items = models.JSONField(default=dict) class Character(models.Model): user = models.ForeignKey('discordbot.DiscordUser', on_delete=models.CASCADE, null=True, related_name="characters") name = models.CharField(max_length=40) strength = models.IntegerField(default=10) endurance = models.IntegerField(default=10) agility = models.IntegerField(default=10) speed = models.IntegerField(default=10) willpower = models.IntegerField(default=10) intelligence = models.IntegerField(default=10) personality = models.IntegerField(default=10) luck = models.IntegerField(default=10) alchemy = models.IntegerField(default=10) survival = models.IntegerField(default=10) blade = models.IntegerField(default=10) marksman = models.IntegerField(default=10) inventory_instance = models.OneToOneField('inventory.InventoryInstance', on_delete=models.CASCADE, related_name="character", null=True, blank=True) I cannot seem to figure out a way to even interact with this data to recreate records … -
How do I ensure my API can't process the same method simultaneously
I have a method in my API that handles the sync operations with the company's ERP. This method is called once every 30 minutes by a script I made to ensure that everything will be always up date. However, if someone wants, they also can make a request to the endpoint by themselves, but they also need to be informed if the operation is currently processing or not So, my solution is: I keep a flag on the database and set it to true when the transaction ongoing and false when it ends, so my application will check it and proceed/stop based on this condition There's just one problem: as I'm keeping everything in a single transaction, the flag is actually useless, since only inside this transaction it will be set to true. I thought about updating the flag before starting the transaction and reverting it whenever an error happens, but I can't ensure the reversal process will happen 100% the times (so there's a possibility to lock the operation) My code is the following one, if anyone needs it for reference: @api_view(['POST']) def syncErpItems(request): try: with transaction.atomic(): job = Jobs.objects.get(name='items') if job.updating: return Response({'message': 'Sync already ongoing'}) job.updating = … -
ChatConsumer() missing 2 required positional arguments: 'receive' and 'send', what's the mistake?
I can't understand why I'm getting an error. I've tried different approaches, but I still encounter an issue with consumers.py. What's the problem, and what am I doing wrong? messaging_users/routing.py from django.urls import path from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from messaging_users import consumers websocket_urlpatterns = [ path('ws/messaging_users/', consumers.ChatConsumer.as_asgi()), ] application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) messaging_users/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): data = json.loads(text_data) message = data['message'] await self.send(text_data=json.dumps({ 'message': 'Received message: ' + message })) js: <script> const socket = new WebSocket('ws://localhost:8000/ws/messaging_users/'); socket.onopen = function() { console.log('WebSocket connection established.'); }; socket.onmessage = function(event) { const data = JSON.parse(event.data); console.log('Received message:', data.message); }; function sendMessage(message) { if (socket.readyState === WebSocket.OPEN) { // WebSocket is ready to send a message socket.send(JSON.stringify({ 'message': message })); } else { console.error('WebSocket is not ready to send a message. Please wait until the connection is established.'); // You can add code here for retrying message sending or other error handling } } // Call sendMessage when clicking the send message button function handleSendMessageButtonClick() { const messageText = document.getElementById('id_body').value; sendMessage(messageText); } … -
Django Static files Permission Issue on nginx
i want to deploy my Django project on linux vps but i have a problem and the problem is my nginx denies the permission for opening the static files i found this error in error.log file: open() "/home/sam/testdjango/static/admin/js/nav_sidebar.js" failed (13: Permission denied>) this is my nginx.conf file: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/jav> ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } N/B: the user im loggined in is 'sam'. and this is my nginx sites-available: server { listen 80; server_name 185.8.174.180; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sam/testdjango; } location / { include proxy_params; proxy_pass …