Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when creating zoom i am getting invalid access token error when my keys are valid
import requests import json API_KEY = 'API KEY' API_SEC = 'SECRET KEY' zoom_api_url = 'https://api.zoom.us/v2/users/me/meetings' meeting_details = { "topic": "The title of your Zoom meeting", "type": 2, "start_time": "2024-02-27T10:00:00", "duration": "45", "timezone": "Europe/Madrid", "agenda": "Test Meeting", "settings": { "host_video": "true", "participant_video": "true", "join_before_host": "False", "mute_upon_entry": "False", "watermark": "true", "audio": "voip", "auto_recording": "cloud" } } headers = { 'Content-Type': 'application/json', } auth = (API_KEY, API_SEC) response = requests.post(zoom_api_url, headers=headers, auth=auth, data=json.dumps(meeting_details)) print(response.json()) after I am getting access token but its saying invalid access token i have added keys and allowed authentication on zoom i have tested it with postman as well as through my django app From every platform i am getting same error ** Invalid Access Token** I tried to create access with jwt.io too but still its not working if anyone can help what is wrong? -
How can I assign a url to a button that redirect users to an external website when the data is split up into two data frames?
I have function in my view that fetches data from multiple spreadsheets and normalizes said data into one single data frame via Pandas. This df1 is eventually rendered and displayed in a webapp in the form of a bootstrap table using Django. For the sake of simplicity, let’s say this table has two columns: “Games” and “Link”. “Games" shows all the soccer matches for today and “link” simply has a button for each of the games. This button does nothing for now. Now, I have another function that fetches data from a different source and again, normalizes the data using Pandas creating a df2 with three columns: “Games”: shows some soccer matches for today (this column has some but not all the games in df1 with exactly the same format). “Id”: a 4-digit identifier that is unique to each of the games above. “Url”: a url that contains the “id” and redirects the user to an external website that provides the user with extra information about that particular match. I’m trying to figure out a way where the users can click on the buttons available in the webapp (which are linked to the games in df1) and get redirected to … -
Django display DateFormat as dd/mm/yyyy
I have a form in Django where the user needs to select the date. When the user selects the date the date is displayed in the following format mm/dd/yyyy (eg. 02/29/2024). I want the date in the form to be displayed as dd/mm/yyyy (eg. 29/02/2024 ). This is the date field in my form: date = forms.DateField( widget=forms.DateInput(format='%d/%m/%Y', attrs={'type': 'date', 'min': str(timezone.now().date()), 'max': str((timezone.now() + timedelta(days=365)).date())}), help_text='Select a date', input_formats=['%d/%m/%Y'], validators=[validate_future_date], ) I also tried: In settings.py: DATE_INPUT_FORMATS = ('%d-%m-%Y',) USE_I18N = True USE_L10N = True In the form: input_formats=settings.DATE_INPUT_FORMATS, After both of these approaches the format was still displayed as dd/mm/yyyy. -
Django View to return template with refreshed modal window
I'm using Django form in modal window where core content (in container) generated by JS. On submit django model instance saved without any issues if form.is_valid() == True a modal window closes with switching focus on current background page. However if form.is_valid() == False the modal content just opens in separate URL instead and takes all browser screen as View renders just a short code fragment in .html file. The goal is to refresh the modal window on current condition in case if form_is_valid() == False with form errors. Template "accounts/profile_settings.html" contains a form and submit button which renders inside <div class="preferences_content"> {% comment %} JS generated dynamic content depends on tab pressed. {% endcomment %} </div> My JS knowldge is very basic so I appreciate any suggestion on this topic. The View : def profile_update_view(request): """ Updates current Profile instance.""" if request.method == "POST": current_profile = request.user.profile profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=current_profile) if profile_form.is_valid(): profile_form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER', "/")) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) else: profile_form = ProfileUpdateForm() return render(request, "accounts/profile_settings.html", {'profile_form': profile_form}) document.addEventListener("DOMContentLoaded", function() { var openModalLink = document.getElementById("openPreferencesModal"); var modal = document.getElementById("preferencesModal"); var span = modal.querySelector(".close"); var preferencesContent = modal.querySelector(".preferences_content"); var tabs = modal.querySelectorAll(".tab"); … -
Django losing session state?
I have a VPS running apache. Apache is serving two domains, my homepage (django, django-cms, zinnia) and a prod site (django, oscar). I use falkon browser. When I change the items in site's admin (I change values in a row, it's list_editable, and then click Save), sometimes (quite often), the response returned is a redirect to login, as if the session cookie is not passed. What is interesting, if I save the POST request as curl and retry it, it succeeds. Since there are several redirects after I hit save, I've seen it failing on the first one (so the item is not saved), or the second one (the item is therefore saved, but I find myself not on the list page, but on the main admin page). How do I debug it? I suspect it may be a browser issue, I'll try mitmproxy now to see what's really hitting the network. But maybe someone has seen this behaviour before. -
Migrate project from Django 1.8 to 1.11 and TemplateDoesNotExist at /accounts/login/
i am beginner in Python and Django. I must update project from Django 1.8 to 1.11 (and in past to 2,3,4). I make update my requirements file and pip. When I write in WSL: ./.venvs/bin/python3 manage.py runserver I have error i browser: TemplateDoesNotExist at /accounts/login/ _accounts/login.html Request Method: GET Request URL: http://127.0.0.1:8000/accounts/login/?next=/ Django Version: 1.11 Exception Type: TemplateDoesNotExist Exception Value: _accounts/login.html my urls.py: from django.conf import settings from django.views.generic.base import TemplateView from django.conf.urls import include, url from django.contrib.auth.views import login from go.accounts.decorators import check_login_abuse from go.accounts.forms import AuthenticationForm, PasswordResetForm from go.insurance.views import index urlpatterns = [ url(r'^$', index), url(r'^accounts/login/$', check_login_abuse(login), {'template_name': 'accounts/login.html', 'authentication_form': AuthenticationForm}), url(r'^accounts/logout/$', logout, {'template_name': 'accounts/logout.html'}), ] How can i repair this problem? I use Python 3.8 -
Static files on EC2 instance, AWS
I recently deployed my project to an Ubuntu EC2 instance and I noticed that the static files (css) don't seem to be loading(same with the images from sqLite3-database). For my website I use django: What I'm getting: When I enter my website, my css and media doesn't load. What's more I can't access one of my slug-pages, because I always get 500 bad request: [27/Feb/2024 09:53:36] "GET /about-me/ HTTP/1.1" 500 145 [27/Feb/2024 09:53:58] "GET / HTTP/1.1" 200 12343 [27/Feb/2024 09:53:58] "GET /static/css/home.css?%201709027638 HTTP/1.1" 404 179 [27/Feb/2024 09:53:58] "GET /media/images/Crawler_Post_Picture.png HTTP/1.1" 404 179 *my setup: ├── core ├── db.sqlite3 ├── home ├── manage.py ├── media ├── requirements.txt ├── static ├── staticfiles ├── templates └── venv What I've already tried: collectstatic migrate change my settings.py into: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR,'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'staticfiles'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' 5)urls.py: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) add this in my homepage.html template <head>: <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}?{% now " U" %}" /> I'm a newbie, so thanks in advance! -
Django mocking a function in a View does not work
Ok so here is the situation. I'm using Django, DRF and for tests django.test and unitest.mock I have a View which executes a method inside a post request sending a message to Kafka (send_message_to_kafka). This method is not in a viewset and I am trying to mock it. I wrote 2 tests. to call a method wrapper_send_message_to_kafka() which calls send_message_to_kafka inside it. self.client.post("/viewset/", data=payload). Both of these tests mocks the function send_message_to_kafka bypassing the actual publish to Kafka. @mock.patch('utils.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) But the first works as expected and the second is not mocked. View @api_view(["POST"]) def example_view(request): if request.method == "POST": ... result = send_message_to_kafka(json.dumps((message))) Tests from django.test import TestCase import unittest.mock as mock ... @mock.patch('utils.pubsub.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) def test_send_message_to_kafka(self, send_message_mock): result = wrapper_send_message_to_kafka() self.assertTrue(result["success"]) @mock.patch('utils.send_message_to_kafka', return_value={"success": True, "message": "Message sent to Kafka successfully!"}) def test_start_run(self, send_message_mock): response = self.client.post( "/execute/", data=payload, format="json", ) -
Django Register View not Saving User Model to Database
I built a registration form + view + template, but when I try to register, the user is not being saved to the database, neither does it log me in. I expected my form to register my user and save it to the database. This is my code (Register form) from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class UserRegistrationForm(forms.ModelForm): email = forms.EmailField() password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email'] def check_password(self): if self.cleaned_data['password'] != self.cleaned_data['password2']: raise forms.ValidationError('Passwords do not match!') return self.cleaned_data['password2'] (Register view) def register_view(request): if request.method == 'POST': register_form = UserRegistrationForm(request.POST) if register_form.is_valid(): user = register_form.save(commit=False) user.set_password = register_form.cleaned_data['password'] # Automatically log in the user after registration username = register_form.cleaned_data['username'] password = register_form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page or home page return redirect('home1:index') # Adjust 'home' to your home page URL name else: register_form = UserRegistrationForm() return render(request, 'register.html', {'register_form': register_form}) (Register Template) <form class="form" method="post"> {% csrf_token %} <label class="label" for="email">Email:</label> <input class="input" type="text" id="email" name="email"> <label class="label" for="username">Username:</label> <input class="input" type="text" id="username" name="username"> <label class="label" for="password">Password:</label> <input … -
I issue with my Django project recognizing mysqlclient module installed with xampp
I got this error on trying to install Xampp: 'Important! Because an activated User Account Control(UAC) on your system some functions of Xampp are possibly restricted. With UAC please avoid to install Xampp to C:\Program Files(missing write permissions). Or deactivate UAC with msconfig after this setup' If i go ahead and install xampp, then mysqlclient module is not seen by the project. I also get the warning that xampp doesn't have admin previledges. If I give xampp admin previledges, I see 'x' mark on my xampp interface against Apache, Mysql & Tomcat. Even installing in another directory hasn't worked either. I don't know what I am doing wrong. If i go ahead and install xampp, then mysqlclient module is not seen by the project. I also get the warning that xampp doesn't have admin previledges. If I give xampp admin previledges, I see 'x' mark on my xampp interface against Apache, Mysql & Tomcat. Even installing in another directory hasn't worked either. I don't know what I am doing wrong. -
Factory boy field for self-referential field in django abstract model
`class BaseOrganization( OrganizationModelMixin, TimeStampedModel, OrganizationWidgetsMixin ): name = models.CharField(max_length=255, verbose_name="Nomlanishi", null=True) juridical_address = models.CharField( max_length=150, verbose_name="Yuridik manzili", null=True, blank=True ) phone_number = models.CharField( max_length=150, verbose_name="Telefon raqami", null=True, blank=True, validators=[phone_regex], ) parent = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="%(class)s_children", verbose_name="Yuqori tashkilot", ) class Meta: abstract = True class BaseOrganizationFactory(factory.django.DjangoModelFactory): """Base organization factory""" name = factory.Faker("company") juridical_address = factory.Faker("address") phone_number = factory.Faker("phone_number") parent = factory.SubFactory( "myapp.tests.factories.BaseOrganizationFactory", ) @pytest.mark.django_db class TestBaseOrganization: @pytest.fixture(autouse=True) def setup(self): self.base_organization = BaseOrganizationFactory( parent=None ) ` if i call BaseOrganizationFactory in setup method it caused RecursionError: maximum recursion depth exceeded while calling a Python object -
Django web application cannot load a page
I am currently building a Django web app(A toy store). But some pages just won't load. After I log in or register to the web app, and I choose the category of ages 10-14, there appears the toys available, when I click on a toy it is supposed to take me to the details page but, for some reason it keeps loading and never opens. It worked yesterday when I ran it. I run it on localhost. Here is all the code for my project: https://github.com/MosheM123/Toys -
Parsing nested JSON in Django Rest Framework
I am trying to serialize a geometry dict which also contains a location dict and map that dictionaries values to my model. The data comes in two levels deep and is mapped to a single model, because its from an external API. How I've done it so far is with source='*' but this requires a new ModelSerializer for every nested object. Is there a way to "skip" to the nested object I want? For example here is some input data: { ... geometry: { location: { lat: ..., lng: ..., } } ... } Then I map it to a model like this: class MyModel(models.Model): ...other attributes from 1 level deep latitude = CharField() longitude = CharField() And my current serializer do that like this: class GeometrySerializer(serializers.ModelSerializer): latitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES) longitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES) class Meta: model = models.Location fields = ['latitude', 'longitude'] class GeometryLocationSerializer(serializers.ModelSerializer): location = GeometrySerializer(source='*') class Meta: model = models.Location fields = ['location'] class LocationSerializer(serializers.ModelSerializer): # Nested obj from json req, geometry: { location: { lat: ..., lng: ...} ....} #latitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES, source='geometry.location.lat') #longitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES, source='geometry.location.lng') geometry = GeometryLocationSerializer(source='*') class Meta: model = models.Location fields = ['id', 'addr_address', 'business_status', 'formatted_address', 'formatted_phone_number', 'icon', … -
DateTime conversion (March 5, 2024, 5:33 a.m. to datetime.datetime(2024, 3, 5, 5, 33))
i have raw date = March 5, 2024, 5:33 a.m. is it possible to convert it in datetime.datetime(2024, 3, 5, 5, 33) using python I have tried from datetime import datetime date_string = "March 5, 2024, 5:33 a.m." date_object = datetime.strptime(date_string, "%B %d, %Y, %I:%M %p") desired_datetime = datetime(2024, 3, 5, 5, 33) print(desired_datetime) -
Expected out is not coming in Django python
I am new to python! I was trying to scrap menu structure of any website! the out is coming fine when I tried in VScode! here is the code for i in menu_items('https://natureshair.com.au/'): print(json.dumps(i, indent=6)) And this is the output, Script can scrap all the menu Now I am trying to collect this website and display results using Django! the strange thing is if I use the same website the output is empty! here is the code : def product(request): finaldata=request.GET["title"] finaldata1=request.GET["title1"] finaldata2=request.GET["title2"] results = list( item #for link in ('https://natureshair.com.au/', 'https://www.trafficradius.com.au/') for link in (finaldata,finaldata1,finaldata2) for item in menu_items(link)) return JsonResponse({'results': results}) Output: Note: it not working for a few websites like 'https://natureshair.com.au/' and this is working fine in VS code! Not sure where I am wrong here is the link to my project My projrct -
module 'django.apps' has no attribute 'get_model'
I am writing a funciton to delete object, with only by sending it's app_name and model_name in from url. here is my function. def deleteobject(request, app_name, model_name, id): print(app_name, model_name, id) print(type(app_name), type(model_name), type(id)) try: model_class = apps.get_model(app_name,model_name) except LookupError: model_class = None print(model_class) if model_class: try: obj = model_class.objects.get(id=id) print(obj) obj.delete() except model_class.DoesNotExist: return HttpResponseBadRequest("Object not found.") else: return HttpResponseBadRequest("Invalid model name.") return redirect(request.META.get('HTTP_REFERER', '/'))` it returns this error message: AttributeError at /projectmanagement/delete/ProjectManagement/task/1 module 'django.apps' has no attribute 'get_model' -
can we apply date range filter on date if date data type or dtype is text or str?
models- `class RocCharge(models.Model):` `charge_id = models.IntegerField(blank=True, null=True)` `chname = models.CharField(max_length=100, blank=True, null=True, db_index=True)` `date_of_creation = models.TextField(default=date.today)` views- `from_date = request.GET.get('fromdate')` `to_date = request.GET.get('Todate')` `if from_date and to_date: combined_data = combined_data.filter(date_of_creation__gte=from_date, date_of_creation__lte=to_date)` my date of creation in mysql as well as in models in text format , but i want to perform date range filter from to range without changing date data type , my date in mysql like-21-12-2019 -
Why am I getting 'OperationalError at /account/me/ no such table: main_enroll' if I have the table clearly in main/models? [duplicate]
This question is getting flagged as a duplicate, however the other question's problem is very different than mine in that the person did not run migrations. I have gotten the error 'Operational Error: No Such Table main_enroll' In Django, and I do not understand why as I have defined it properly: Main/Models.py: from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models class Course(models.Model): course_name = models.CharField(max_length=30) course_slug = models.CharField(max_length=70) # Other course-related fields def __str__(self): return self.course_name class Enroll(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey('main.Course', on_delete=models.CASCADE) Accounts/Models.py: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Screenshot of error: Copy & Paste view of error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/me/ Django Version: 5.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'welcome', 'userprofile', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: main_enroll) was the direct cause of the following exception: File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = … -
Why am I getting 'OperationalError at /account/me/ no such table: main_enroll' if I have the table clearly in main/models? [duplicate]
I have gotten the error 'Operational Error: No Such Table main_enroll' In Django, and I do not understand why as I have defined it properly: Main/Models.py: from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models class Course(models.Model): course_name = models.CharField(max_length=30) course_slug = models.CharField(max_length=70) # Other course-related fields def __str__(self): return self.course_name class Enroll(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey('main.Course', on_delete=models.CASCADE) Accounts/Models.py: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Screenshot of error: Copy & Paste view of error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/me/ Django Version: 5.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'welcome', 'userprofile', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: main_enroll) was the direct cause of the following exception: File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\skeleton\userprofile\views.py", line 19, in account_page Enroll.objects.create(user=user, course=course) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\models\query.py", … -
Incoming file from post is "fakepath"
Brand new to react. My file is sending as a fakepath. I know this is for browser sercurity but I expected it to be different in my view. When I deserialize the request.body with json.loads I get this FileNotFound error. fitz.FileNotFoundError: no such file: 'C:\fakepath\HW 3 CPSC 332.pdf' When I deserialize the body with my own serializer it returns that the object is not valid. I am assuming this is due to the same issue with the fake file path. request.body b'{"title":"sdfg","content":"","file":"C:\\\\fakepath\\\\HW 3 CPSC 332.pdf"}' views.py @api_view(['POST']) def createPost(request): serializer = SinglePostSerializer(data=request.body) if serializer.is_valid(): serializer.save() return Response({'message': 'File uploaded successfully'}, status=status.HTTP_201_CREATED) else: return Response({'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class SinglePostSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' models.py # Create your models here. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=50) likes = models.IntegerField(default=0) comment_count = models.IntegerField(default=0) pdf_file = models.FileField(upload_to='media/pdfs/') images = models.ManyToManyField(SheetMusicImage) comments = models.ManyToManyField('Comment', blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pdf_file.name CreatePostPage.js import React, { useState, useEffect} from 'react' const CreatePostPage = () => { const [formData, setFormData] = useState({ // Initialize form fields here // For example: title: '', content: '', }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; … -
Websocket connection doesn't work with redis cluster
I'm trying to establish a websocket connection but it doesn't seem to work due to my redis server which is a cluster from elasticache. Here are the logs: Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels/consumer.py",> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await handler(message) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels/generic/webso> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.connect() Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/shipninja/shipninja/shipninja/consumers.py", line 36, in> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.channel_layer.group_add("inventory", self.channel_name) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels_redis/core.py> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await connection.zadd(group_key, {channel: time.time()}) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/client.p> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: conn = self.connection or await pool.get_connection(command_name, **optio> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.ensure_connection(connection) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await connection.connect() Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: raise ConnectionError(self._error_message(e)) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: redis.exceptions.ConnectionError: Error -2 connecting to rediss://clustercfg.> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: Future exception was never retrieved Feb 27 03:54:24 ip-172-31-40-162 python[12684]: future: <Future finished exception=gaierror(-2, 'Name or service not known')> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: socket.gaierror: [Errno -2] Name or service not known Feb … -
Django - Problem with posting new date value to a class from models.py
I'm trying to save a date value to a datefield from the django default database but it always return a None value even if the query to add this value isn't None. I tried to convert this date to string and datetime.date type and that didn't solve my problem. I'll post the html, models.py and views.py files. -
Django sitemap.xml shows plain text
I have added sitemaps following Django 2.0 (I cannot upgrade for now) official documentation. When accessing my production site I get all the correct links with dates but as plaintext, without xml formatting. The google search console is not accepting this format. My sitemap.py code: from blog.models import Post from django.contrib.sitemaps import Sitemap from courses.models import Course, Interview, Lesson class PostSitemap(Sitemap): changefreq = 'weekly' priority = 0.9 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.updated ... My urls.py code: path( "sitemap.xml", sitemap, {"sitemaps": { "courses": CourseSitemap, "posts": PostSitemap, "lessons": LessonSitemap, "podcasts": InterviewSitemap, }}, name="django.contrib.sitemaps.views.sitemap", ), How can I change it to XML format? -
Websocket connection with uvicorn/django/nginx not working
I am trying to establish a websocket connection in my app but I'm getting different errors. I'm using elasticache redis cache and my settings.py looks as follows: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["rediss://redis-m0rn9y.serverless.use1.cache.amazonaws.com:6379"], }, }, } I've configured my channel_layers numerous times but this one allows me to establish a connection at least before it closes: Feb 26 23:54:37 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/api/get_user_inventory/ HTTP/1.0" 200 OK Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/api/check_session/ HTTP/1.0" 200 OK Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Not Found: /app/inventory/styles.css.map Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Not Found: /app/inventory/styles.css.map Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/inventory/styles.css.map HTTP/1.0" 404 Not Found Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: ('128.6.36.223', 0) - "WebSocket /ws/inventory/" [accepted] Feb 26 23:54:38 ip-172-31-40-162 python[9623]: WebSocket connected to the group 'inventory'. Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: connection open Feb 26 23:54:38 ip-172-31-40-162 python[9623]: ERROR: Exception in ASGI application Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Traceback (most recent call last): Feb 26 23:54:38 ip-172-31-40-162 python[9623]: File "/home/ubuntu/venv/lib/python3.10/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 255> Feb 26 23:54:38 ip-172-31-40-162 python[9623]: result = await self.app(self.scope, self.asgi_receive, self.asgi_send) Feb 26 23:54:38 ip-172-31-40-162 python[9623]: File "/home/ubuntu/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ Feb … -
Expose host port 80 of a Dockerized Django app deployed on AWS Fargate
I have a very simple Django rest framework (DRF) app that is dockerized and deployed on AWS ECS with Fargate. I created a security group to expose the port 8000 on the inbound rules and was able to see the app at public IP 12.34.56:78:8000/ I wanted to have the app run on port 80, but don't know how to. Do I need to expose 80 on the Dockerfile and specify that port when creating the task definition? Or do I need to set up nginx to pass HTTP requests to port 8000 internally? Dockerfile: # Pull base image FROM python:3.12 # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Expose the Django development server port EXPOSE 8000 # # Start the Django development server CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Task definition: { "taskDefinitionArn": "arn:aws:ecs:us-west-1:123:task-definition/app-task:12", "containerDefinitions": [ { "name": "container-name", "image": "dockerhub/app:latest", "cpu": 0, "portMappings": [ { "name": "default", "containerPort": 8000, "hostPort": 8000, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [], "mountPoints": [], "volumesFrom": [], "logConfiguration": { "logDriver": "awslogs", "options": …