Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
I am getting a no such column error only when running tests
Perhaps this is leaving out some key detail and exposing my relative newness to django, but I tried to isolate my issue to the fewest steps to reproduce the problem. Starting state: App running fine, tests all passing. Add one nullable column to an existing model. makemigrations migrate New state: App runs fine, running tests produces an error. Creating test database for alias 'default'... Found 23 test(s). Installed 5 object(s) from 1 fixture(s) Traceback (most recent call last): File "/home/f/.virtualenvs/mgmt/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/f/.virtualenvs/mgmt/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: recommended_for_text recommend_for_text is the name of the new column. recommended_for_text = models.CharField(null=True, blank=True, max_length=256) It shows up in my view in the app as expected, just running the tests is causing me an issue. -
Why is django class-based_view not seeing my uploads?
class MultipleFileInput(forms.ClearableFileInput): """ Work around for `widget=forms.ClearableFileInput(attrs={'multiple': True})` >> `widget=MultipleFileInput(attrs={'multiple': True})` """ input_text = 'Select' clear_checkbox_label = 'Clear' initial_text = 'Current' allow_multiple_selected = True class UserUploadForm(forms.ModelForm): file = forms.FileField( widget=MultipleFileInput(attrs={'multiple': True}), required=True, validators=[FileExtensionValidator(allowed_extensions=['csv'])], ) class Meta: model = UserUpload fields = ['file'] class MyFilesView(FormView): template_name = 'data_related/my_files.html' form_class = UserUploadForm success_url = reverse_lazy('my_files') def post(self, request, *args, **kwargs): self.object = None form = self.get_form() files = self.request.FILES.getlist('file') print(files) print("Files received:", request.FILES.getlist('file')) # Debug output to confirm files are received if form.is_valid(): print("Form is valid") # Debug statement return self.form_valid(form) else: print("Form is not valid") # Debug statement for field, errors in form.errors.items(): for error in errors: print(f"Error in {field}: {error}") messages.error(request, f"Error in {field}: {error}") return self.form_invalid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_files = UserUpload.objects.filter(user=self.request.user) files = [{'short_name': file.file.name, 'file_size': file.file_size, 'uuid': file.uuid} for file in user_files] # Pagination paginator = Paginator(files, 10) # Show 10 files per page page_number = self.request.GET.get('page') page_obj = paginator.get_page(page_number) context.update({ 'user_files': files, 'page_obj': page_obj, 'form': self.get_form(), #form_class((self.request.POST, self.request.FILES) or None) # show UserUploadForm, must instantiate form with POST and FILES }) 2024-04-26 03:53:45 [] 2024-04-26 03:53:45 Files received: [] 2024-04-26 03:53:45 Form is not valid 2024-04-26 03:53:45 Error in file: This field is … -
Filtering DataFrames in a Django Dashboard
I am trying to build a Dashboard with Django... I wish to filter the dashboard with category, month and Year. The dataFrame is coming from python code than I am adding the charts with JS. I don't know how to proceed to be able to filter it as I want. views.py: def get_expense_api_data(request, *args, **kwargs): sort_order = ['January','February','March','April','May','June','July','August','September','October','November','December'] exp_df = pd.DataFrame(Expenses.objects.filter(user=request.user).all().values('date_created', 'amount')) categories = dict() if exp_df.empty: default_items_exp = [0] labels_exp = [0] else: categories['expenses'] = pd.unique(pd.DataFrame(Expenses.objects.filter(user=request.user).all().values('categories')).categories.values).tolist() exp_df['date_created'] = pd.to_datetime(exp_df['date_created']) exp_df = pd.DataFrame(exp_df.groupby(exp_df['date_created'].dt.strftime('%B'))['amount'].sum()) exp_df["date_created"] = exp_df.index exp_df.index = pd.CategoricalIndex(exp_df["date_created"], categories=sort_order, ordered=True) exp_df = exp_df.sort_index().reset_index(drop=True) default_items_exp = exp_df.amount.tolist() labels_exp = exp_df.date_created.tolist() inc_df = pd.DataFrame(Incomes.objects.filter(user=request.user).all().values('date_created', 'amount')) if inc_df.empty: default_items_inc = [0] labels_inc = [0] else: categories['incomes'] = pd.unique(pd.DataFrame(Incomes.objects.filter(user=request.user).all().values('categories')).categories.values).tolist() inc_df['date_created'] = pd.to_datetime(inc_df['date_created']) inc_df = pd.DataFrame(inc_df.groupby(inc_df['date_created'].dt.strftime('%B'))['amount'].sum()) inc_df["date_created"] = inc_df.index inc_df.index = pd.CategoricalIndex(inc_df["date_created"], categories=sort_order, ordered=True) inc_df = inc_df.sort_index().reset_index(drop=True) default_items_inc = inc_df.amount.tolist() labels_inc = inc_df.date_created.tolist() try: net_df = pd.merge(inc_df, exp_df, how='outer', on='date_created') net_df = net_df.fillna(0) net_df['amount'] = net_df['amount_x'] - net_df['amount_y'] net_df.index = pd.CategoricalIndex(net_df["date_created"], categories=sort_order, ordered=True) net_df = net_df.sort_index().reset_index(drop=True) default_items_net = net_df.amount.tolist() labels_net = net_df.date_created.tolist() except KeyError: if inc_df.empty: net_df = exp_df elif exp_df.empty: net_df = inc_df net_df.index = pd.CategoricalIndex(net_df["date_created"], categories=sort_order, ordered=True) net_df = net_df.sort_index().reset_index(drop=True) default_items_net = net_df.amount.tolist() labels_net = net_df.date_created.tolist() savings_df = pd.DataFrame(Savings.objects.filter(user=request.user).all().values('date_created', 'amount')) if savings_df.empty: … -
raise ImproperlyConfigured("SECRET_KEY setting must not be empty")django.core.exceptions.ImproperlyConfigured:The SECRET_KEY setting must not empty
I published my Django project into github and I had a lot of variables that stored in .env for secure. And when anyone clone that project and migrate its not reading variables in my .env file that saved in .gitignore. is there any solution without showing these value of the variables, or it's ok and no danger to show this info? ``` import os from pathlib import Path from dotenv import load_dotenv load_dotenv() SECRET_KEY = os.getenv('SECRET_KEY') CURRENT_HOST = os.getenv('CURRENT_HOST') DATABASE_NAME = os.getenv('DATABASE_NAME') DATABASE_USER = os.getenv('DATABASE_USER') DATABASE_PASSWORD = os.getenv('DATABASE_PASSWORD') DATABASE_HOST = os.getenv('DATABASE_HOST') DATABASE_PORT = os.getenv('DATABASE_PORT') HOST_EMAIL = os.getenv('EMAIL_HOST') EMAIL_USER = os.getenv('EMAIL_HOST_USER') EMAIL_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') PORT_EMAIL = os.getenv('EMAIL_PORT') EMAIL_TLS = os.getenv('EMAIL_USE_TLS') SOCIAL_AUTH_GOOGLE_KEY = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_KEY') SOCIAL_AUTH_GOOGLE_SECRET = os.getenv('SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET') ``` .gitignore has .env inside, So I thought that it's may be related to the one in my device. I know that it's impossible but i did not find any solution so i hope that anyone can help me, Thanks. -
html button not work on each click - hot to debug it? (chrome)
I've got a (django) app, that displays a page with videojs-record, with ability to record something and send to backend. In general both recording and sending works fine. But - after recording there is a button to send (button with id=submit), and the click there works sometimes immediately, sometimes, I need to click it two or three times, to make it work. After sending, the button is hidden, and another one is showed to move to next question. And the behaviour is similar - it works sometimes, and sometimes needs to be clicked couple of times. I've no idea how to debug it... {{questionText}} <video id="myAudio" playsinline class="video-js vjs-default-skin"></video> <button class="btn btn-sm btn-primary" id="submit" disabled>sent</button> <a href="{% url 'video2_module:NextQuestion' %}" id="next" style="display: none;" class="btn btn-sm btn-primary" >next-> </a> <input type="hidden" id="myVar" name="variable" value="{{ file_name }}"> <script> $(document).ready(function () { var options = { controls: true, bigPlayButton: false, loop:false, width: 480, height: 360, fluid: false, plugins: { record: { audio: true, video: { // video media constraints: set resolution of camera width: { min: 480, ideal: 480, max: 480 }, height: { min: 360, ideal: 360, max: 360 } }, // dimensions of captured video frames frameWidth: 480, frameHeight: 360, maxLength: … -
Which way is better to store data about Transactions? (Django)
I need to store data about Transactions in Django (Postgres). There are different type of transactions (replenishment of balance, withdrawal from balance, payment of salaries, purchase of equipment, parking expenses, bonuses and etc.). Depend on type of transaction I need to store different data, for example: For replenishment of balance and withdrawal from balance - customer (Id of customer, can be empty), date, comment, total For salaries - employee (Id of employee), date, comment, sub total and total (there may be bonus or fine) For purchase of equipment - provider (Text), date, comment, total For parking expenses - date, comment, total Also I need to implement API (to retrieve salaries, transactions of client, all transactions, sum of all expenses, sum of all income and etc.) Also it will be good if Admin would be able to add custom transaction types (I think that it's not a good idea to store transaction type as a String, because it may cause some problems if Admin put wrong data (For example: "Salari" instead of "Salary")) So, here are my questions: Is it a good approach to store all Transactions in one table (Model) or it's better to split them and why? Any ideas … -
How do I display the list items on the site as links
This is my question and I'm just starting to learn django ^-^ these are urls from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('<int:days_week>/', views.get_info_week_intoviy), path('<str:days_week>/', views.get_info_week, name = 'day-week'), path('type/', views.teplt, name='types'), ] def teplt(request, types): dnay = ['CHETNIY', 'NECHETNIY'] rez = '' for typess in dnay: new_ser = reverse('types', args = (typess,)) rez += f'<li><a href="{new_ser}">{typess}</a></li>' response = f''' <ol> {rez} </ol> ''' return HttpResponse(response) this is the part of the code that should output as links along such a path http://127.0.0.1:8000/HOROS/type CHETNIY NECHETNIY I tried to fix the url and view somehow, but all attempts were in vain and returned to the previous code -
I keep on getting GET http://127.0.0.1:8000/room/f5428fc5 404 (Not Found):
Im making a Next.js and Django full stack app with Spotify api, and Im having trouble fetching the get-room api, when ever I click on the button to create a room in the create page the room is created and a unique code is generated but the room is not found. can anyone help me?: from create page const handleRoomButtonPressed = () => { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ votes_to_skip: votesToSkip, guest_can_pause: guestCanPause, }), }; fetch("/api/create-room", requestOptions) // Update the URL path .then((response) => response.json()) .then((data) => router.push("/room/" + data.code)) .catch((error) => setErrorMsg("Error creating room...")); }; const renderCreateButtons = () => { return ( <div className="flex flex-col items-center mt-2"> <button className=" bg-spotifyGreen text-white rounded-lg px-4 py-2 mb-2 hover:bg-spotifyLight " onClick={handleRoomButtonPressed} > Create A Room </button> <button className="bg-red-500 text-white rounded-lg px-4 py-2 hover:bg-red-400" onClick={() => router.push("/")} > <ArrowBackIcon /> Back </button> </div> ); }; from the room page: const [roomDetails, setRoomDetails] = useState({ votesToSkip: 2, guestCanPause: false, isHost: false, spotifyAuthenticated: false, song: {}, }); const { roomCode } = router.query; const getRoomDetails = () => { fetch("/api/get-room" + "?code=" + roomCode) .then((response) => { if (!response.ok) { leaveRoomCallback(); navigate("/"); } return response.json(); }) … -
I want to link my subcategory to related category in forms.py. How to do that?
I'm currently working on a Python project where I'm trying to get category from its own related subcategories. However, I'm encountering an issue where the subcategory field, it doesn't show anything. There are 4 files that i'm uploading: This is models.py class Category(models.Model): category_name=models.CharField(max_length=100,unique=True,null=False) def __str__(self): return self.category_name class Subcategory(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE) subcategory_name=models.CharField(max_length=100,null=False) This is forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Ad,Photo,Subcategory,Category class UserRegistrationForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] def clean_email(self): email = self.cleaned_data.get('email') if User.objects.filter(email=email).exists(): raise forms.ValidationError("This email is already taken.") return email class AdForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label=None) subcategory = forms.ModelChoiceField(queryset=Subcategory.objects.none()) class Meta: model = Ad fields = ['title', 'description', 'category', 'subcategory', 'price', 'location'] This is my views.py def publish_ad(request): if request.method == 'POST': form = AdForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('index') # Redirect to a success page or any other URL else: form = AdForm() return render(request, 'market/publish_ad.html', {'form': form}) This is a html file {% extends "market/base.html" %} {% load static %} <!-- publish_ad.html --> {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Publish Ad</button> </form> {% endblock content %} ** … -
Django does not access PostgreSQL Database using Docker
Here is the error message: Got an error checking a consistent migration history performed for database connection 'default': connection failed: could not receive data from server: No route to host Here is my .env POSTGRES_DB=ibm_skiller POSTGRES_PASSWORD=mYP@sSw0rd POSTGRES_USER=ibm_skiller POSTGRES_HOST=172.19.0.2 POSTGRES_PORT=5432 Here is my docker-compose.yml: postgres: container_name: postgres env_file: - ./.env image: postgres:alpine3.19 ports: - 5432:5432 volumes: - postgres16:/var/lib/postgresql/data # - ./ibm_skiller_init.sql:/docker-entrypoint-initdb.d/ibm_skiller_init.sql healthcheck: test: ["CMD-SHELL", "pg_isready -U ibm_skiller"] interval: 5s timeout: 5s retries: 5 networks: - skillernet Here is the output of the docker ps command: docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a2d40d97e3f0 postgres:alpine3.19 "docker-entrypoint.s…" 3 hours ago Up 3 hours (healthy) 0.0.0.0:5432->5432/tcp postgres f86b9bacd25e bd43f03c087b "./entrypoint.sh" 5 hours ago Up 5 hours 0.0.0.0:8000->8000/tcp, 0.0.0.0:9000->80/tcp skiller -
Serialize a nested object with Django Rest Framework
I'm currently trying to serialize the following object into the models listed below, the current relationship is A Category has many quizzes, a quiz belongs to one category, while containing many questions, a question belongs to a quiz, while containing many choices. Any help would be much appreciated! { "category": 1, "title": "Basic Java", "question": { "title": "Boolenas", "text" : "adafasad", "correct_words": [], "choice_type": "SINGLE", "choices": [ { "text": "asdadawd", "is_correct": true }, { "text": "adwasda", "is_correct": false }, { "text": "asdawd", "is_correct": false } ] } } The models are the following: class Category(models.Model): title = models.CharField(max_length=50) def __str__(self) -> str: return self.title class Meta: verbose_name_plural = 'Categories' class Quiz(models.Model): title = models.CharField(max_length=100) created_date = models.DateTimeField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self) -> str: return self.title class Meta: verbose_name_plural = 'Quizzes' class Question(models.Model): title = models.CharField(max_length=100, default='placeholder') text = models.CharField(max_length=200, null=True) correct_words = ArrayField(models.CharField(max_length=255), blank=True, null=True) # choice_type = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) quiz = models.ForeignKey(Quiz, related_name='questions', on_delete=models.CASCADE) class Choice(models.Model): text = models.CharField(max_length=200, null=True) is_correct = models.BooleanField(default=False) created_date = models.DateTimeField(auto_now_add=True) question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE, default=1) And lastly these are my serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields= ('id', 'title') def validate(self, data): if Category.objects.filter(title=data.get('title')).exists(): raise serializers.ValidationError("Category …