Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count of records created in each hour interval starting from midnight to present time
I need to retrieve count of records created in each hour duration from midnight to present time. To do so the model contain a created_at timestamp field which will record the created time. The model definition is given bellow. class Token(models.Model): customer_name = models.CharField(max_length=50) created_at = models.DateTimeField(auto_now_add=True) remarks = models.TextField(null=True,blank=True) modified_at = models.DateTimeField(auto_now =True) The result am looking for like the following in SQL output Intervel | count| -----------------| 01:00 AM | 0 | # 00:00 to 01:00 AM 02:00 AM | 0 | ....... 10:00 AM | 20 | 11:00 AM | 5 | ........ 03:00 PM | 5 | ------------------ I need to get model query that can do the above operation at the database end without loading all the records created in the day since from midnight to now then getting the count by running a forloop in the application. Kindly Help me in this.. -
Field 'id' expected a number but got 'add'
I'm working on a Django project where I have an API endpoint for adding PC parts, and I'm encountering an issue when trying to access the URL /parts/add. I'm getting the following error: ValueError: Field 'id' expected a number but got 'add'. This error seems to be related to my Django model's primary key field, which is an AutoField called 'id.' I'm not explicitly providing an 'id' when adding a new PC part, and I expect Django to generate it automatically. here is my model: from django.db import models # Create your models here. class PCparts(models.Model): id = models.AutoField( primary_key=True) name = models.CharField(max_length=128) type = models.CharField(max_length=50) price = models.DecimalField(max_digits=10, decimal_places=2) release_date = models.IntegerField() # Unix epoch timestamp core_clock = models.DecimalField(max_digits=5, decimal_places=2) boost_clock = models.DecimalField( max_digits=5, decimal_places=2, null=True, blank=True) clock_unit = models.CharField(max_length=5) TDP = models.IntegerField(default=0.0) part_no = models.CharField(max_length=20) class Meta: ordering = ['-price'] def __str__(self) -> str: return self.name here is my view from rest_framework import status from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.db.models import Avg from .models import PCparts from .serializers import partSerializer # Import the serializer class from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods from django.db.utils import IntegrityError # Create your … -
Trouble Sending POST Data for Google Calendar Scheduling in Django: Ajax Newbie
I'm building an app to schedule events on Google Calendar using Django, and I'm encountering an issue with sending data via a POST request to a Django view. Here's my Django view code for CreateEventFunc: from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def CreateEventFunc(request): # For debugging purposes, write data to a file with open('output.txt', 'w') as file: file.write("CreateEventFunc\n") if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) therapist_id = data['therapist_id'] start_time = data['start_time'] end_time = data['end_time'] # Create the event using your utility function (e.g., create_event) # Replace this with your actual implementation created_event = create_event(therapist_id, 'Appointment', start_time, end_time) # Return a response (you can customize this based on your needs) response_data = {'message': 'Event created successfully', 'event_id': created_event['id']} return JsonResponse(response_data) On the frontend, I have a JavaScript function scheduleMeeting that sends a POST request to this view when a meeting is scheduled: <script> function scheduleMeeting(startTime, endTime, therapistId) { if(confirm("Do you want to schedule a meeting from " + startTime + " to " + endTime + "?")) { // Create a data object to send with the POST request var eventData = { 'start_time': startTime, 'end_time': endTime, 'therapist_id': therapistId, }; // Send a POST request to … -
How can I get a django form value and display it back to the user before the form is submitted?
I have done some research...and found a suggestion to create a function on a form to get a field value...get form value I tried this and for some reason I can't get it to work. I've used the clean function on the form as part of the submit process and that works great. The difference here is that I'm essentially trying to inspect the field values well before the form gets submitted. I want the user to click a button and see the values that have been populated in the "approvers" field in this case. I've got the button working...but can't seem to get the "approvers" value to populate. It just shows []. I defined the function on my form... def get_invitee_name(self): invitees = self.cleaned_data.get('approvers') return invitees But when I try to call the function in my template as {{ invitees }} ...nothing shows up. Do I need to define this as a context variable as well? Do I have to do this using Javascript instead or is there a way to do this with pure Django/Python? I'm using a ModelForm if it matters. Thanks in advance for any thoughts. -
How can I prevent django from claiming localhost port 80 via httpd after I've removed my project?
My problem is that my localhost port 80 is taken by an auto-reloading Django proc that I no longer need and I cannot kill the Django proc(s) because they auto-reload upon being killed. I did Django a while ago for an interview assignment so it's not trivial to get back into that and manage it that way. Is there a way simply on macos to prevent this process from coming back? I've tried using launchctl but it's unclear which item would be facilitating the auto-reloading. I have 2 mystery django process that get auto-reloaded whenever I kill it with sudo kill {PID}. i.e. I kill the procs, I check to make sure port 80 is not being used anymore with sudo lsof -i :80, and it shows 2 new procs that have auto-reloaded. I am hoping to do anything at all so that when I run sudo lsof -i :80 I get no results. -
django channels hadling connection
I get trouble with django channels i guess its with hadling connection on client, but maybe isnt. So my code look like this: class ExternalDataConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.active_connections = {} async def connect(self): self.room_group_name = f"external_{self.scope['user'].id}" # Match the group name from the signal await self.channel_layer.group_add(self.room_group_name, self.channel_name) logger.info(f"Connected to group: {self.room_group_name}") await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): try: data = json.loads(text_data["text_data"]) if data: asyncio.ensure_future(await self.start_external_stream(data)) else: asyncio.ensure_future(await self.stop_extenal_stream(data)) # start or stop external stream except Exception as e: logger.error(f"ERROR receiving websocket: {e}") async def start_external_stream(self, data): # do something with data, send payload and get data from stream async def stop_external_stream(self, data): # stop existing steam for data async def send_notification(self, data): # sending notification to user So issue is when i start getting data from external stream its double each time when user reload page. On client im just like get data from django channels websocket like this: if (isWebSocketConnected === 'true') { socket = new WebSocket('ws://0.0.0.0:8000/ws/binance_consumer/'); } else { socket = new WebSocket('ws://0.0.0.0:8000/ws/binance_consumer/'); localStorage.setItem('websocketConnected', 'true'); } const notifications = []; // Handle WebSocket events socket.addEventListener("open", (event) => { console.log("WebSocket connected"); }); socket.addEventListener("message", (event) => { const data … -
Can't reallocate empty Mat with locked layout error in django view
I'm trying to do an image upscaling app using OpenCV and i have an error says that : OpenCV(4.8.1) D:\a\opencv-python\opencv-python\opencv\modules\core\src\matrix_wrap.cpp:1286: error: (-215:Assertion failed) !(m.empty() && fixedType() && fixedSize()) && "Can't reallocate empty Mat with locked layout (probably due to misused 'const' modifier)" in function 'cv::_OutputArray::create' and in the terminal say that : [ WARN:0@3.616] global loadsave.cpp:248 cv::findDecoder imread_('/media/images/wolf_gray.jpg'): can't open/read file: check file path/integrity wolf_gray.jpg is the name of the image that the user uploads it from the form this is the project tree ├───AISystem │ └───__pycache__ ├───img_upsc │ ├───images │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───images │ └───__pycache__ ├───media │ └───images ├───static │ ├───css │ ├───imgs │ │ ├───cards │ │ ├───myfont │ │ └───result │ └───js ├───XOXOXOAPP │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───XOXOXOXOApp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ └───XOXOXOXOXOAPP ├───migrations │ └───__pycache__ ├───templates └───__pycache__ and this is the app files img_upsc app folder view.py def img_upscaler(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) selection = request.POST.get('mod_sel') enter image description here if form.is_valid(): form.save() image_name = str(form.cleaned_data['Image']) if(selection == "EDSR_x4"): sr = dnn_superres.DnnSuperResImpl_create() path = r'img_upsc\EDSR_x4.pb' sr.readModel(path) sr.setModel('edsr', 4) imgloc = f'/media/images/{image_name}' image = cv2.imread(imgloc) upscaled = … -
for loop in django templates not working as expected
I am creating a django app and am iterating through the images list. I've been at it for hours to no avail. I looked everywhere for help and still couldn't fix it. I successfully got the POST request with ajax and when I print it to the console the images sources are there in the list. But, upon iterating it in the django templates, it doesn't show up. It's funny because it does show up when I click the buy button for that request. Also, I am creating a bookmarklet that upon clicking will send the data of the URL of the current page to views.py. I am using that add the images data src into the list. base.html (template) <body> {% csrf_token %} {% load static %} <script src="{% static 'js/onload.js' %}" type="text/javascript"></script> <img width='100px' src="https://i.ibb.co/37ybzSD/neom-V1-NTz-Srn-Xvw-unsplash.jpg"> <img src="https://i.giphy.com/media/tsX3YMWYzDPjAARfeg/giphy.webp"> {% load socialaccount %} <h1>Billionaire Shopping Game</h1> {% if user.is_authenticated %} <p>Welcome, {{ user.username }} !</p> <a href="logout">Logout</a> {% else %} <a href="{% provider_login_url 'google' %}">Login with Google</a> {% endif %} <a href="javascript:(function() {let script = document.createElement('script'); script.src = '{% static '/js/bookmarklet.js' %}'; document.body.appendChild(script);})();">Bookmarklet</a> <a href="javascript: (() => {alert('Hello');})();">Helo alert</a> <img width="100px" src="{% static 'images/heart.png' %}"> <div> <form method="POST" action="/"> <label … -
Having problem with apache2 w/Django ASGI, WSGI & Postgres on Linode Server
Okay so I have built a social media app with django channels asgi w/POSTGRES database. Test on port 80 Type "help" for help. postgres=# CREATE DATABASE xxxxxxx postgres-# \l List of databases Name | Owner ` | Encoding | Collate | Ctype | Access privileges-----------+----------+----------+-------------+-------------+----------------------- postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (3 rows) postgres=# CREATE DATABASE fetishfun; CREATE DATABASE postgres=# GRANT ALL PRIVILEGES ON DATABASE fetishfun TO django postgres-# CREATE DATABASE fetishfun; postgres=# \q (venv) smoke@django-server:~/fetish_fun$ python3 manage.py runserver 0.0.0.0:8000 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 30 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): account, admin, auth, contenttypes, sessions, sites, socialaccount. Run 'python manage.py migrate' to apply them. October 20, 2023 - 17:35:56 Django version 4.2.6, using settings 'socialnetwork.settings' Starting ASGI/Daphne version 4.0.0 development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. I have it successfully running on port 8000 … -
How to substitute a value into a form field from a database
I have related models; when they are saved, some data is saved in the first model, others in the second. Now I'm trying to update the data so that when a button is pressed, the data from the two models is updated since the fields in the form 'client_name' and 'phones' are not connected to anything, I partially achieved this, they are updated and saved, but when the form is opened, the fields 'client_name', 'phones', I need to somehow substitute previously saved values into these fields so that they can be edited in the field. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Person(models.Model): client_name = models.CharField(max_length=100, verbose_name='Фио клиента') def __str__(self): return self.client_name class Meta: verbose_name = 'Клиент' verbose_name_plural = 'Клиенты' class Phone(models.Model): phone = models.CharField(max_length=50, verbose_name='Телефон') contact = models.ForeignKey(Person, on_delete=models.CASCADE, related_name='phones', verbose_name='Контакт', null=True) def __str__(self): return self.phone class Meta: verbose_name = 'Телефон' verbose_name_plural = 'Телефоны' class Orders(models.Model): # Основная база данных objects = None author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, verbose_name='Принял', blank=True) date_of_creation = models.DateTimeField(auto_now=True, verbose_name='Дата создания') execution_date = models.DateField(verbose_name='Дата исполнения') address = models.CharField(max_length=200, verbose_name='Адрес') service = models.CharField(max_length=100, verbose_name='Услуга') master = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='master', null=True, verbose_name='Мастер', blank=True) client = models.ForeignKey(Phone, on_delete=models.SET_NULL, related_name='client', null=True, … -
Move DB cursor id after manual insert
I'm facing a case where I have to manually insert data from old DB into a new one. The new one is a DB that'll be used by a Django application. For that I have CSV file or whatever that I iterate over, and the thing is that I also use the id from this file, because I need to keep it. For instance I do : from django.db import connections cursor = connections["default"].cursor() cursor.execute("INSERT INTO my_table (id, name) VALUES (3, 'test')") If I use such ID (3), the next time I'll want to insert data through my django application, it'll create a record with ID 1, then ID 2, then I'll have an error because it'll try to create data for ID 3. How can I make it skip existing ID ? Thanks in advance ! -
When websocket in django, url not found occurs
I'm going to proceed with WebSocket in django. However, url not found occurs, but I can't find the cause. CMS/CMS/settings.py ... INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CMS', 'main', ] ASGI_APPLICATION = 'CMS.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } CMS/CMS/routing.py from django.core.asgi import get_asgi_application from django.urls import path,re_path from . import consumers websocket_urlpatterns = [ path('ws/alarm_endpoint/', consumers.JpConsumer.as_asgi()), ] CMS/CMS/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.layers import get_channel_layer class JpConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() async def disconnect(self, close_code): await self.close() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.send(text_data=json.dumps({ 'message': message })) main/static/common/notification.js var socket = new WebSocket("ws://" + window.location.host + "/ws/alarm_endpoint/"); socket.onopen = function () { console.log('WebSocket connection opened.'); // 연결이 열리면 서버로 데이터를 보낼 수 있습니다. socket.send(JSON.stringify({ 'message': 'Hello, Server!' })); }; socket.onmessage = function (e) { var data = JSON.parse(e.data); console.log('Received message from server:', data.message); // 서버로부터 받은 데이터를 처리할 수 있습니다. alert('Received message from server: ' + data.message); }; socket.onclose = function (event) { if (event.wasClean) { console.log('Connection closed cleanly, code=' + event.code + ', reason=' + event.reason); } else { console.error('Connection died'); } }; socket.onerror = function (error) { console.error('WebSocket Error: ' + … -
why is Django not correctly routing my urls?
I am trying to put together a simple website with django. I have my routes defined and they work provided that if i want to go to home i have to localhost/home/home rather than just it being localhost/home. It is the same for my about page. localhost/home/about. If its of any help when i try to go to localhost/home or about django says the page cannot not be found. essentially a 404 error. This what Django spits out at me. For the life of me I cannot figure out why i have 4 routes when i should only have 3. Admin, Home and About. It may also be worth mentioning that if i route to localhost/about/home i will get the home page and if i route to home/home i also get the homepage, same as about, i can route to localhost/about/about and get the about page. Using the URLconf defined in bbsite.urls, Django tried these URL patterns, in this order: admin/ about/ home/ home/ [name='home'] home/ about/ [name='about'] The current path, home/, didn’t match any of these. -
Django ManyToManyField with model matching the custom through table
I have a situation similar to the Membership example from the Django documentation (https://docs.djangoproject.com/en/4.2/topics/db/models/#extra-fields-on-many-to-many-relationships). class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) persons = models.ManyToManyField(Person, through="Membership") class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) While this works fine to get all Persons of a Group via g1.persons I would like to get all Memberships. Conceptually something like the following: class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Membership, through="Membership") Except that this doesn't work because obviously Membership has no foreign key for itself. Is there a way to set up what I want (i.e. a convenience access to members via g1.members)? Or is the only solution to manually go through Membership.objects.filter(group=g1.pk)? -
TEMPLATE - GET PARAMETER LIST
class ParametroProducto(models.Model): parametros_producto = models.CharField(max_length = 30) tipo_parametro = models.CharField(max_length = 80) class FamiliaProducto(models.Model): nombre_familia = models.CharField(max_length = 100) parametro_familia = models.ManyToManyField(ParametroProducto) class Producto(models.Model): nombre = models.CharField(max_length=100, unique=True) proveedores = models.ManyToManyField(Proveedor, null=True, blank=True) familia = models.ForeignKey(FamiliaProducto, on_delete=models.CASCADE) procedencia = models.CharField(max_length=100) class Recepcion_Envase_Insumo(models.Model): proveedor = models.ForeignKey(Proveedor, on_delete=models.CASCADE) responsable = models.ForeignKey(Empleado, on_delete=models.CASCADE) producto = models.ForeignKey(Producto, on_delete=models.CASCADE) deposito = models.CharField(null=False,max_length=30) fecha = models.DateField(null=False,default=date.today) cantidad = models.IntegerField(null=False) observaciones = models.TextField() class ControlEnvIns(models.Model): envase_insumo = models.ForeignKey(Recepcion_Envase_Insumo, on_delete=models.CASCADE) parametro_env_ins = models.ForeignKey(ParametroProducto, on_delete=models.CASCADE) resultados = models.CharField(max_length=100) observacion = models.CharField(max_length=80) Forms.py class FormEnvIns(forms.ModelForm): proveedor= forms.ModelChoiceField(queryset=Proveedor.objects.filter(activo=True), widget=forms.Select(),required=True) producto=forms.ModelChoiceField(queryset=Producto.objects.filter(activo=True), widget=forms.Select(),label='Insumo') responsable=forms.ModelChoiceField(queryset=Empleado.objects.filter(activo=True), widget=forms.Select()) class Meta: model = Recepcion_Envase_Insumo fields = [ 'fecha', 'proveedor', 'responsable', 'cantidad', 'deposito', 'producto', 'observaciones', ] labels = { 'fecha':'Fecha de recepcion', 'proveedor':'Proveedor', 'responsable' : 'Responsable', 'cantidad':'Cantidad recibida', 'deposito':'Deposito', 'producto':'MP', } widgets = { 'fecha':forms.DateInput(attrs={'readonly':'readonly'}), 'cantidad':forms.NumberInput(), 'deposito':forms.TextInput({'class': 'form-control'}), 'observaciones':forms.Textarea(attrs={'cols': 100, 'rows': 3}), } class FControlEnvIns(forms.ModelForm): parametro_env_ins=forms.ModelChoiceField(queryset=ParametroProducto.objects.all(), widget=forms.Select(),label='Parametros') class Meta: model = ControlEnvIns fields = [ 'parametro_env_ins', 'observacion', 'resultados', ] labels = { 'observacion':'Observacion', 'resultados':'Resultado ', } widgets = { 'observacion':forms.TextInput(attrs={'class':'form-control'}), 'resultados':forms.TextInput(attrs={'class':'form-control'}), } View.py def registro_envase_insumo(request): if request.method == 'POST': recepcion_form = FormEnvIns(request.POST) detalle_form = FControlEnvIns(request.POST) if recepcion_form.is_valid() and detalle_form.is_valid(): envase_insumo = recepcion_form.save(commit=False) producto_seleccionado = envase_insumo.producto parametros = producto_seleccionado.familia.parametro_familia.all() envase_insumo = recepcion_form.save() for parametro in parametros: envase_insumo_det = detalle_form.save(commit=False) … -
ls: cannot access '../.pip-modules/lib': No such file or directory
I cannot find the files I am looking for and when I try to list them they are not available. I have python3.12.0 installed specifically for a walkthrough project. I installed AllAuth for it and once I enter this command ls ../.pip-modules/lib I get the ls: cannot access '../.pip-modules/lib': No such file or directory I am not sure where to look to find this and I am not sure what I am doing wrong. -
Open layers and django
I'm new to django and open layers but I tried to create a project using both. I search the internet and found a way to make them both work with webpack but I didn't like that so much, because of 2 things, the first is the bundling process and the second is after importing the bundled file debugging wasn't that clear. I was thinking maybe there is a way to work it out without using webpack? I tried including the node_modules/ol/dist/ol.js but didn't work for me. also, I thought maybe including all node_modules in the STATICFILES_DIRS but didn't work as well, i needed later to include each file staticly. Is there a solution to this or am I bounded to work with webpacking? Thank you! -
Django Ajax toastr not display when success
I encounter a problem with ajax toastr, i'm using bootstrap 5 also so that might be cause style problem. My Ajax: {% load humanize %} {% load static %} <link rel="stylesheet" href="{% static 'style.css' %}"> <link href="toastr.css" rel="stylesheet"/> {% block extra_js %} <script src="toastr.js"></script> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script> <script type="text/javascript"> let csrftoken = '{{ csrf_token }}' $(document).on('submit','#add-to-favourite',function(e){ e.preventDefault(); $.ajax({ type: $(this).attr('method'), headers:{'X-CSRFToken':csrftoken}, url: $(this).attr('action'), data: $(this).serialize(), success: function (response) { alert("Succes"); toastr.options.closeButton = true; toastr.success('Added to Favourite'); } }) }); </script> {% endblock extra_js %} the alert message display ok so ajax function return success. -
registers same email which is alreday registerd Django Login Signup Project
I have a Django project login and signup it gives error when a new user enters same username which is already registered but accept the email which is already registered , how to avoid email if it is already registred ??? Can someone help in this issue? I AM USING CRUD AND LOGIN SIGNUP IN SAME PROJECT . My views.py code def signup_page(request): # try: if request.method == 'POST': uname = request.POST.get('username') email = request.POST.get('email') pass2 = request.POST.get('password2') pass1 = request.POST.get('password1') if pass1 != pass2: return HttpResponse("Your password and confirm password are not Same!!") else: my_user = User.objects.create_user(uname,email,pass1) my_user.save() messages.info(request,"Signup is Succesfully") return redirect(reverse('login_page')); return render (request,'registartion.html') # except Exception as e: # raise ValueError("Account With this Username or Email is already registered") def login_page(request): try: if request.method == 'POST': username = request.POST.get('username') pass1 = request.POST.get('pass') user = authenticate(request,username=username,password=pass1) if user is not None: login(request,user) messages.add_message(request,messages.INFO,"Succesfully Login") return redirect(reverse('dashboard_page')) else: return HttpResponse ("INCORRECT USERNAME OR PASSWORD") return render (request,'login.html') except Exception as e: raise ValueError("Incorrect Username Or Password !!!") MY MODELS.PY class Members(models.Model): GENDER_CHOICEs =( ('Male','Male'), ('Female','Female') ) user = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20,null=True,blank=False) email = models.EmailField(null=True,blank=False,unique=True) phone = models.CharField(null=True,blank=False,max_length=10) gender = models.CharField(choices=GENDER_CHOICEs, max_length=10) role = models.CharField(max_length=10) is_deleted = models.BooleanField(default=False) … -
How to Integrate a Standalone Django Live Chat App into Main Website Views?
I'm currently learning Django and have an existing website built in HTML, CSS, JS with a Java Spring backend. I am in the process of migrating it to Django. I've successfully migrated the site and now want to add a new feature: live chat groups between users. I have implemented the live chat functionality as a standalone Django app using Django Channels and Redis, following multiple tutorials. The chat app works as expected when isolated. The issue I'm facing is how to integrate this chat functionality into the main views of my existing website. Specifically, I want the chat to appear in a small window at the bottom right corner of the screen, similar to how chat features work on Facebook or other social media sites. I tried using Django's {% include ... %} tag to include the chat functionality in base.html, thinking it would behave similarly to other globally-included elements like the navigation bar. However, this approach doesn't seem to work, and there appears to be some form of communication issue between the two apps. Here is a Gist containing my project structure, base.html, room.html, and index.html for context. -
how to process Django form?
i have an app and i need to process an image that send from the user. my image is stored in the database and linked with django form. i need to get the image name that uploaded by the user with the format of the image example: (image.png) view.py def img_upscaler(request): if request.method == 'POST': form = ImageForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('imgupscaler.html') else: form = ImageForm() return render(request, "upsc_main.html",{'form': form}) forms.py from django import forms from .models import imgUpscalling class ImageForm(forms.ModelForm): class Meta: model = imgUpscalling fields = ('Image',) model.py from django.db import models class imgUpscalling(models.Model): Image = models.ImageField(upload_to='images/' thank you. -
Unable to write data to AWS RDS PostgreSQL database?
In my Django application, I'm utilizing AWS RDS PostgreSQL as my database backend. I've encountered an issue when attempting to send a POST request to store data in the database. After a period of loading, I receive a '502 Bad Gateway' error. Interestingly, I can successfully read data from the database. I also have a mobile app and a separate front-end application developed in Vue.js. When making POST requests from the mobile app, all operations work flawlessly, except for the one related to OTP, which also gives a '502' error. Other CRUD operations from the app are functioning as expected. In addition, reading and writing data works properly from the Django admin panel and the dashboard, both of which are built in Django. Within the front-end application, I can write data successfully, but I encounter a '502' error when attempting to write. This issue specifically occurs when I add CNAME of Application Load Balancer's DNS point to the domain. However, if I use an IP address in the A record to point to the domain, everything functions as expected. What could be the source of this issue and how can it be resolved? -
Is the FCM module in fcm-django removed in the latest version version 2.0.0?
Is the FCM module in fcm-django removed? I could use the fcm_send_message and fcm_send_bulk_message functions upto version 0.3.11 of fcm-django but in the latest versions the 'fcm' module is missing. This is my import statement that had been working fine upto versions 0.3.11 of fcm-django: from fcm_django.fcm import fcm_send_message How to use those functions in the new versions of fcm-django? Please help as this is an urgent requirement, thanks! -
In HTMX making an image clickable to delete itself (issue with created URL interference)
I have a page that under this URL http://localhost:8000/dashboard/myobjects/ shows me the products that I have. For each product I have a button that takes me to a page where I can change the pictures (deleting them or upload them) It takes me to this URL http://localhost:8000/dashboard/changepictures/5/built/ where 5 is the row number of the products table and built is a field header that defines the category. So far so good. Then I have this HTMX snippet that would delete the picture upon clicking: <div class="grid-wrapper"> {% for x in all_pictures_of_a_property %} <div class="grid-item"> {% if x.images %} <img src='{{x.images.url}}' width="200" height="100" name="pictures" hx-post="{% url 'deletepicture' x.id 'built' %}" hx-trigger="click" hx-target="this"> <a href="{% url 'deletepicture' id=x.id property='built' %}" class="btn btn-primary">Delete</a> {% endif %} </div> {% endfor %} </div> It would delete it and would be clickable when I click on the href link BUT this creates me two problems: a) It changes the URL of my browser page to something like this: http://localhost:8000/dashboard/deletepictures/37/built/ where 37 is the id of the picture, it of course changes to 37, 38 etc depending on which picture I hover. b) Because on the same page I have an upload button to add more pictures, … -
Textarea adding whitespaces when I use it again after I submit it
I have a form with textarea and everytime I click the submit button and use it again, it adds whitespaces. EDIT PAGE This is the edit page where the textarea is located. {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>Edit Page</h1> <form method="POST" action="{% url 'edit' title=title %}"> {% csrf_token %} <div id="title"> <label>Title:</label> <textarea name="title" class="form-control" style="width: 600px; height: 50px;">{{ title }}</textarea> </div> <div id="body"> <label>Body:</label> <textarea name="content" class="form-control" rows="5" style="width: 600px; height: 400px;">{{ content }}</textarea> </div> <input type="submit" class="btn btn-primary" value="Edit" style="margin-left: 546px; margin-top: 10px;"> </form> {% endblock %} TEMPLATE {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> <a href="{% url 'create' %}">Create New Page</a> </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %}{% endblock %} </div> </div> </body> </html> VIEWS This is my …