Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove session id in logout?
I have a problem: when I do logout in Django I can still see a session id cookie in my browser and even after login I can acess an index page which is decorated with login_required. Please see the code below. @login_required(login_url='signin') def logout(request): auth.logout(request) return redirect('signin') @login_required(login_url='signin') def index(request): return render(request, 'index.html') I am quite frustrated and do not get what is misconfiured, chat gpt is suggesting some garbage(as ususal) Tried to remove session manually, tried to flush and so on - nothing works in chrome and safari -
Error Encountered: OrganizationFromTenantGuidNotFound
Error Encountered: OrganizationFromTenantGuidNotFound We are encountering an error related to Microsoft Graph API integration in our Django application. Specifically, the error message is: { "error": { "code": "OrganizationFromTenantGuidNotFound", "message": "The tenant for tenant guid 'e01c8511-af06-4cad-9b24-a63b9da7b0fc' does not exist.", "innerError": { "oAuthEventOperationId": "8b058e01-f527-4afe-9294-ee28aec98e19", "oAuthEventcV": "D3A3Bd+uExjl4MwXmDgIqw.1.1", "errorUrl": "https://aka.ms/autherrors#error-InvalidTenant", "requestId": "fda9cb55-b436-4590-b3b3-3d847ee7e931", "date": "2024-09-16T18:42:41" } } } This happens when trying to authenticate using Azure AD and fetch emails via Microsoft Graph API. The decoded token shows a valid tenant_id, client_id, and permissions, but we suspect there might be an issue with the tenant configuration or app registration on Azure. At the moment, using the token, I can get a list of all users. However, when I go to the information on a specific user, an error occurs. However, on the application side, no errors are displayed. My main task is to configure the functionality of sending messages from my application, so that messages sent to the user's address are visible in the application (also when sending a message to a user). https://graph.microsoft.com/v1.0/users/ { "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users", "value": [ { "businessPhones": [], "displayName": "Demo Mail", "givenName": null, "jobTitle": null, "mail": "demotest@tester.com, "mobilePhone": null, "officeLocation": null, "preferredLanguage": null, "surname": null, "userPrincipalName": "---", "id": "d028f0d4-0838-4925-8eeb-5f6651b6cfb1" }, ] … -
Setting up React with DRF?
Currently, I'm following some lessons on my course and building a social media website project for assessment in future. I am currently stuck with getting my React App built within a Django Rest Framework App to display even the default React page when hosting Live Server, I will link my repo below if it helps I feel like I have gone in circles now as I'm not fully clued in on a full stack project yet (hence trying to get it together). Very much appreciate if anyone could take a look and help me out. I am a bit of a noob so may be obvious and I'm missing something entirely. https://github.com/conor-timmis/Better-You So far I've been dabbling with the Views & urls of the main app, but not sure where to go from there. Lessons have not really explained this so much, only creating the apps separately then linking them together, but mention building within one repo instead with a full app but I am building from scratch so that's not really an option. (I have tried building my app and putting them into static as I read that in another thread but didn't have any luck with that). -
How do you serve a generated file using Django?
For example, the Django sitemap middleware, generates a sitemap and then serves it from localhost:8000/sitemap.xml. If I were to serve a file in a similar manner, following the same url structure, how would I do this? I have a view and urls file: class FileView(View): def get(self, request): return HttpResponse(open('myfile.xml').read(), content_type='text/xml') # urls.py urlpatterns = [ path( '/myfile.xml', PageView.as_view() ) ] This will fail to render with a 404, and will constantly append a / to the url, so it looks for localhost:8000/myfile.xml/. However, if I change my urlpatterns to use '/myfile', without the file extension, it renders the file correctly. Is there a correct way to serve this using the file exentsion without resorting to dropping it into static files? -
Not able to serve React build files with Django
I have been trying to serve my dist files of React frontend app to my Django project. However, the browser keeps refusing to serve static files and throws the error described below: > Refused to apply style from 'http://localhost:8000/static/my-react-app/assets/index-CgY6hLMH.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. > Refused to apply style from 'http://localhost:8000/static/my-react-app/assets/index-CgY6hLMH.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. > index-LlsxC_Wu.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. Here's how my Django repository looks: enter image description here All my CSS and JS static files are inside assets while index.html is the template I want to serve. My settings.py file looks like this: enter image description here I already tried rebuilding the dist files and copying them to the static directory and made changes to static paths as well but all in vain. -
When sending a request to the local django server, it returns a 404 error, although the correct parameters and the correct url are passed
I need to make a view class so that I can export a file in xlsx or csv format, depending on what is passed in the parameters, and I got this code: class ExportXLSXandCSV(APIView): def get(self, request, model_name, format): models = { 'Country': Country, 'Car': Car, 'Manufacturer': Manufacturer, 'Comments': Comments } if model_name not in models: return Response({"detail": "Invalid model."}, status=400) model = models[model_name] data = model.objects.all() serializer = serializers.serialize('python', data) if format == 'xlsx': df = pd.DataFrame(serializer) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename={model_name.lower()}_export.xlsx' df.to_excel(response, engine='openpyxl', index=False) return response elif format == 'csv': response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = f'attachment; filename={model_name.lower()}_export.csv' serializer.serialize_csv(response, data) return response Также вот код моей url: path('api/export/str:model_name/str:format/', ExportXLSXandCSV.as_view(), name='export_data') И вот какую ошибку я получаю в терминале при отправке запроса http://127.0.0.1:8000/api/export/?model_name=Car&format=xlsx ошибка в терминале: "GET /api/export/http://127.0.0.1:8000/api/export/?model_name=Car&format=xlsx HTTP/1.1" 404 6238 Я пробовал менять параметры, а также пробовал отправлять их по-другому (в postman), я только начинаю и пока не могу знать куда дальше следует смотреть для того, чтобы решить эту проблему, прошу помочь мне -
Can I configure multiple timeouts for pgbouncer from my django settings?
I am trying to add pgbouncer to my architecture. I know that I can set various pgbouncer configuration settings in the pgbouncer.ini file. I want to replace postgresql with pgbouncer in my django settings, however, my django configuration currently uses different timeouts depending on the purpose of the connection. For example, I want a longer timeout for connections intended to perform database migrations. DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", # <Other settings ...> "OPTIONS": { "options": f"-c statement_timeout={90 * 1000}", }, }, "migration": { "ENGINE": "django.db.backends.postgresql", # <The same other settings as above ...> "OPTIONS": { "options": f"-c statement_timeout={120 * 1000}", }, }, } I have read the pgbouncer documentation and I 1haven't found anything that quite solves this problem. -
Displaying images with Detailview
I'm having some problems with the DetailView in django and sqlit3, I have tree options in my home page there you can chose 1 of 3 and you get a list of images this works but only the Studio option I can get Detailed views. thanks.. Link to site ahoogzand.com Have 3 models "Studio, Street, Travel" I'm not very good at this just picked up bits and pieces from the net but can't find any thing for my problem -
How can I solve NoReverseMatch error in Django?
I'm making the website using Django. I have a comment section for every post. But I am getting the following error. NoReverseMatch at /comment/create/the-art-of-self-care-prioritizing-your-well-being/ Reverse for 'comment-create' with arguments '('',)' not found. 1 pattern(s) tried: ['comment/create/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] Request Method: POST Request URL: http://localhost:8000/comment/create/the-art-of-self-care-prioritizing-your-well-being/ Django Version: 5.0.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'comment-create' with arguments '('',)' not found. 1 pattern(s) tried: ['comment/create/(?P<slug>[-a-zA-Z0-9_]+)/\\Z'] Exception Location: C:\Users\shafa\PycharmProjects\CampusConnect\.venv\Lib\site-packages\django\urls\resolvers.py, line 848, in _reverse_with_prefix Raised during: comments.views.CommentCreateView Python Executable: C:\Users\shafa\PycharmProjects\CampusConnect\.venv\Scripts\python.exe Python Version: 3.12.1 Python Path: ['C:\\Users\\shafa\\PycharmProjects\\CampusConnect', 'C:\\Users\\shafa\\PycharmProjects\\CampusConnect', 'C:\\Program Files\\JetBrains\\PyCharm ' '2023.2.5\\plugins\\python\\helpers\\pycharm_display', 'C:\\Python312\\python312.zip', 'C:\\Python312\\DLLs', 'C:\\Python312\\Lib', 'C:\\Python312', 'C:\\Users\\shafa\\PycharmProjects\\CampusConnect\\.venv', 'C:\\Users\\shafa\\PycharmProjects\\CampusConnect\\.venv\\Lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm ' '2023.2.5\\plugins\\python\\helpers\\pycharm_matplotlib_backend'] Server time: Mon, 16 Sep 2024 12:56:05 +0000 models.py class Comment(models.Model): content = models.TextField() author = models.ForeignKey('users.User', related_name='comments', on_delete=models.CASCADE) post = models.ForeignKey('posts.Post', related_name='comments', on_delete=models.CASCADE) date_posted = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.author.username + " -> " + self.post.title views.py class CommentCreateView(LoginRequiredMixin, CreateView): model = Comment fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user form.instance.post = Post.objects.get(slug=self.kwargs['slug']) return super().form_valid(form) def get_success_url(self): return reverse('post-detail', kwargs={'slug': self.object.post.slug}) urls.py urlpatterns = [ path('create/<slug:slug>/', views.CommentCreateView.as_view(), name='comment-create'), ] comment_form.html <form action="{% url 'comment-create' post.slug %}" method="post"> {% csrf_token %} <div class="flex flex-col gap-2"> <label for="comment" class="text-lg">Comment</label> <textarea name="comment" id="comment" cols="30" rows="4" class="textarea" placeholder="Write your thoughts..."></textarea> </div> <button … -
DRF getting AttributeError while trying to post data
I'm creating a user registration API in DRF using a Profile model with a OneToOne relationship with Django's default User Model. I have created a serializer with User model and defined the fields of Profile as serializer fields. The problem is when I post the data, though the user and profile are saved in the database I'm getting this error error AttributeError at /auth/registration Got AttributeError when attempting to get a value for field address on serializer UserRegistrationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'address'. using write_only with address seems to solve the problem but I want to understand why is this happening and how this view accessing this address field why it ignores the phone_number and date_of_birth and doesn't give me errors on those. Any input will be helpful. Thanks! Here is my code for the model, serializer, and view. #models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_of_birth = models.DateField(null=True) phone_number = models.CharField(null=True, max_length=30) address = models.CharField(max_length=250) def __str__(self): return f'Profile of {self.user.username}' #Serializer.py class UserRegistrationSerializer(serializers.ModelSerializer): phone_number = serializers.CharField(required=False, max_length=30) date_of_birth = serializers.DateField(required=False) address = serializers.CharField(max_length=250) password = … -
How should I approach in developing this computer vision project? Dog Pooping/Elimination/Urination Detector w/ alerts through RTSP camera, Web App
I am currently developing a project which aims to develop a Dog Pooping/Elimination/Urination Detector using YOLOv8, with sound alerts to deter from designated spots in which the camera's vision range allows. This application would be viewable through a web page w/ a login portal. Stack: Python, Django, YOLOv8, OpenCV, HTML, CSS, JS I'm having a number of problems first is I'm not sure whether I'm using the right model for this project, I'm currently doing transfer learning using yolov8s.pt and training on a dataset with 1 class, pooping dogs. Here's how it looks: results = model.train(data="config.yaml", epochs=100, patience=15, batch=4, workers=6, device=[0]) However, over numerous attempts and curating the dataset I seem to always get no detections at all, and when I do get detections they're always of false positives. Could it be that object detection is the wrong choice, would pose estimation be better given the goal of the project? Second, I can't find a way to make the RTSP camera be publicly available, I tried looking up port-forwarding but it wasn't possible to the limitations of my router and my ISP. And lastly, aside from a dog pooping/elimination/urination, I would also want the system to be able to identify … -
Webhook Configuration Issue in Twilio
I have configured a webhook in Twilio to receive messages. I tested the webhook using Ngrok, and initially, I receive 2-3 message requests, and everything works fine. However, after that, I stop receiving webhook requests. How can I fix this and debug the issue? Please guide me. -
Why the Django static files are not loading after deployment?
I know this question has similar ones but nothing has been able make it for me. I've tried everything and every possible solution yet nothing helped including running all commands like python manage.py collectstatic. I've attached the necessary screenshots. Please help me out ASAP! PS. Check the console screenshots thoroughly. Thank you! Here are the codes you might want to check: settings.py: # Media files (Uploaded files) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] urls.py: from django.urls import path from .views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', home, name="home"), path('signup/', signup_view, name='signup'), path('activate/<uidb64>/<token>/', activate, name='activate'), path('login/', login, name='login'), path('logout/', logout, name='logout'), path('myprofile/', profile, name='profile'), path('myprofile/update', PROFILE_UPDATE, name='profileupdate'), path('reservation', reservation, name='reservation'), path('checkout/', checkout, name='checkout'), # Cards path('vegndaal/', vegndaal_page, name='vegndaal_page'), path('chicken/', chicken_page, name='chicken_page'), path('mutton/', mutton_page, name='mutton_page'), path('rice/', rice_page, name='rice_page'), path('tandoor/', tandoor_page, name='tandoor_page'), path('paratha/', paratha_page, name='paratha_page'), path('breakfast/', breakfast_page, name='breakfast_page'), path('fish/', fish_page, name='fish_page'), path('wrapsandsandwiches/', wrap_page, name='wrap_page'), path('burgersandwiches/', burger_page, name='burger_page'), path('combosandwiches/', combo_sandwiches, name='combo_sandwiches'), path('clubsandwiches/', club_sandwiches, name='club_sandwiches'), path('freshjuices/', juices_page, name='juices'), path('salads&softdrinks/', salad_page, name='salad'), path('milkshakes/', milk_shakes, name='milkshakes'), path('tea&coffee/', teancoffee, name='tea&coffee'), path('bbq/', bbq_page, name='bbq_page'), path('desserts/', desserts_page, name='desserts'), path('plateitems/', plate_items, name='plateitems'), … -
Djoser Login dosn't work with Docker-compose, Worker terminated with Signal 11
I Currently working on a Data warhouse with Django and React. For the Authentification is use Djoser, what worked realy well when i dont deploy it with Docker. When i Deploy it with my Docker-Compose i can Create(register) a User and Activate it but when i try to Login the Worker terminate itself with Signal 11. At the same time when i use a wrong Password, i get 401 Wrong Password. i'm pretty overwhelmed because it looks like it can accsess the DB (i use SQLite) because i can create the User. First i tryed to login with Postman becaus i thougt it would be a Frontend Problem, but it's not. Then i lookt at the Network Timing on my browser and it looks like it fails at the Initial connection when i use the right Parametes, with wrong Parameters the Request is ok withour errors (just the 401) When i turn on the Loggin feature it looks like this: evse_v4_sprint-current-backend-1 | [2024-09-16 08:01:59 +0000] [33] [INFO] Booting worker with pid: 33 evse_v4_sprint-current-backend-1 | (0.001) SELECT "user_useraccount"."id", "user_useraccount"."password", "user_useraccount"."last_login", "user_useraccount"."is_superuser", "user_useraccount"."email", "user_useraccount"."name", "user_useraccount"."is_active", "user_useraccount"."is_staff", "user_useraccount"."is_creator" FROM "user_useraccount" WHERE "user_useraccount"."email" = 'me@mail.com' LIMIT 21; args=('me@mail.com',); alias=users evse_v4_sprint-current-backend-1 | [2024-09-16 08:02:02 +0000] … -
Change the format of ValidationError in DRF for one specific serializer only
I have a serializer: class EmployeeExcelDataSerializer(serializers.ModelSerializer): employee_id = serializers.CharField( max_length=20, required=True, allow_null=False, error_messages=get_error_messages("employee_id", ["null"]), ) first_name = serializers.CharField( max_length=50, required=True, allow_null=False, error_messages=get_error_messages("first_name", ["null"]), ) middle_name = serializers.CharField(max_length=50, required=False, allow_null=True) last_name = serializers.CharField( max_length=50, required=True, allow_null=False, error_messages=get_error_messages("last_name", ["null"]), ) email = serializers.EmailField( max_length=150, required=False, allow_null=False, error_messages=get_error_messages("email", ["null"]), ) designation = serializers.CharField( max_length=50, required=True, allow_null=False, error_messages=get_error_messages("designation", ["null"]), ) joined_date = serializers.DateField( required=True, allow_null=False, error_messages=get_error_messages("joined_date", ["null"]), ) bank_name = serializers.CharField(max_length=100, required=False, allow_null=True) account_number = serializers.DecimalField( max_digits=16, decimal_places=0, required=True, allow_null=False, error_messages=get_error_messages("account_number", ["null"]), ) salary_gross = serializers.FloatField( required=True, allow_null=False, error_messages=get_error_messages("salary_gross", ["null"]), ) gender = serializers.ChoiceField( choices=Gender, required=True, allow_null=False, error_messages=get_error_messages("gender", ["null"]), ) marital_status = serializers.ChoiceField( choices=MaritalStatus, required=True, allow_null=False, error_messages=get_error_messages("marital_status", ["null"]), ) cit = serializers.FloatField(required=False, allow_null=True) health_insurance = serializers.FloatField(required=False, allow_null=True) life_insurance = serializers.FloatField(required=False, allow_null=True) house_insurance = serializers.FloatField(required=False, allow_null=True) current_month_leave_days = serializers.FloatField(required=False, allow_null=True) current_month_overtime_hours = serializers.FloatField( required=False, allow_null=True ) class Meta: model = Employee fields = [ "employee_id", "first_name", "middle_name", "last_name", "email", "designation", "joined_date", "bank_name", "account_number", "salary_gross", "gender", "marital_status", "cit", "health_insurance", "life_insurance", "house_insurance", "current_month_leave_days", "current_month_overtime_hours", ] def _email_in_db_exists(self, email: str): employee = Employee.objects.filter(email=email) user = User.objects.filter(email=email) if employee.exists() or user.exists(): return True return False def validate_joined_date(self, value): if value > datetime.date(datetime.today()): raise ValidationError("Date cannot be in future.") if isinstance(value, datetime): value = value.date() elif isinstance(value, str): try: parsed_date … -
Test crashes after Django version update
I encountered a problem after upgrading from django 3.1 to 4.2. There is a test for creating a device twice in a row with identical data: @parameterized.expand([(MOBILE_APP_KIND.INSPECTOR,), (MOBILE_APP_KIND.VOLUNTEER,)]) def test_double_create_device(self, app_kind): if app_kind == MOBILE_APP_KIND.INSPECTOR: url = self.url_inspector InspectorFactory(user=self.user) else: url = self.url_volunteer response = self.client.post(url, self.data, format="json") print(response.data) self.assertEqual(response.status_code, 201) devices = self.user.fcm_devices self.assertEqual(devices.count(), 1) response = self.client.post(url, self.data, format="json") print(response.data) self.assertEqual(response.status_code, 201) self.user.refresh_from_db() devices = self.user.fcm_devices self.assertEqual(devices.count(), 1) When adding a second device, the view should simply return the last device from the DB instead of creating it, to avoid registration_id uniqueness issues. class FCMViewSet(FCMDeviceAuthorizedViewSet): serializer_class = CommonFCMDeviceSerializer http_method_names = ["post", "delete"] def get_object(self): return get_object_or_404( FCMDevice, registration_id=self.kwargs.get("registration_id"), user=self.request.user, active=True, ) def destroy(self, request, *args, **kwargs): instance = self.get_object() instance.active = False instance.save() return Response(status=status.HTTP_204_NO_CONTENT) class CommonFCMDeviceSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) app = serializers.ChoiceField( choices=MOBILE_APP_KIND, required=True, write_only=True ) class Meta(FCMSerializer.Meta): model = FCMDevice fields = ( "user", "app", "name", "registration_id", "device_id", "active", "type", ) def create(self, validated_data): devices = FCMDevice.objects.filter( user=validated_data["user"], app=validated_data["app"], registration_id=validated_data["registration_id"], active=True, type=validated_data["type"], ) if devices.exists(): return devices.last() return FCMDevice.objects.create(**validated_data) ====================================================================== FAIL: test_double_create_device_0_inspector (api.mobile.common.v2.test.test_fcm_device.FCMCreateTestCase.test_double_create_device_0_inspector) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\xacla\AppData\Local\pypoetry\Cache\virtualenvs\core-2EZgQNjY-py3.11\Lib\site-packages\parameterized\parameterized.py", line 533, in standalone_func return func(*(a + p.args), **p.kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\xacla\Desktop\Work\Work\DobroFon.Core\core\www\api\mobile\common\v2\test\test_fcm_device.py", line 89, in … -
How to handle two IDs for one endpoint in Django URL patterns and templates?
How to manage two primary keys when constructing urlpatterns in django for one endpoint(i.e involve two primary keys) def records(request, patient_id, record_id): patient = get_object_or_404(PatientProfile, pk=patient_id) medical_record = get_object_or_404(MedicalRecord, pk=record_id) record_url = reverse('doctor_app:record', kwargs={'patient_id': patient.id, 'record_id': medical_record.id}) print(f"Generated URL: {record_url}") return render(request, 'doctor_app/medical_record.html', { 'patient': patient, 'medical_record': medical_record, 'record_url': record_url }) Exception Type: NoReverseMatch Exception Value: Reverse for 'record' with arguments '('', '')' not found. 1 pattern(s) tried: ['medical_record/(?P<patient_id>[0-9]+)/(?P<record_id>[0-9]+)/\Z'] path('medical_record/int:patient_id/int:record_id/', views.records, name='record'), "{% url 'doctor_app:record' patient.id medical_record.id %}" -
Passing an Array of Objects returned from a fetch command back to the calling function (Django and JS)
I've spent days and days on this trying various techniques I have red on here and other forums but just cant get my head a round it. I've tried .map(), I've tried global variables, I've tried everything I can think of. steep learning curve I have split one long function into several smaller functions to make the code more readable and just more functional, the below code is called by a main function I'm using for mapping, the purpose of the code below is to go and fetch data from a model (via views.py) and then pass it back to the main function, it will be a data containing names, cities, towns, countries, it worked fine before I split the long function but now wont pass variables. Where I console.log 'the objects the towns' it looks ok in the console but once outside of that fetch Im lost, Ive tried to return the data from within the fetch function mappointobject (which I believe is an array of objects) but it wont, Ive tried to put a 'await' on final console.log but nothing, it seems no matter what I've tried fails after the closing fetch function brackets }), the main function … -
ECS task timeouts connecting to RDS
My ECS container will connect to my RDS database initially and can even run a query. However very quickly after boot up, the connection will time out. The error sometimes looks like a DNS one with the error message of: OperationalError('[Errno -3] Temporary failure in name resolution') Sometimes its a connection timeout: OperationalError('connection timeout expired') Notes and things I've tried: Security group has 5432 open, but I've tried having all ports open. Same VPC and different VPC My App Runner app can connect to the DB flawlessly (same code) My computer can connect to the database (same code) EC2 instances can connect to the database (same code) ECS container's role with RDS access, which doesn't make sense but I'm grasping at straws RDS is publicly accessible I'm running Django 5.1 on Python 3.12. I'm seriously out of solutions and am considering migrating off ECS to something else. -
Django redirect is blocked by CORS
My django redirects are blocked by CORS, even though I did everything to set up CORS: I installed django-cors-headers in the virtual environment, I added corsheaders to the INSTALLED_APPS and I added corsheaders.middleware.CorsMiddleware to the top of MIDDLEWARE, I also added this to the bottom of my settings.py file: CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = [ 'content-type', 'authorization', 'x-csrftoken', ] CORS_ALLOW_METHODS = [ 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', ] CORS_ALLOW_CREDENTIALS = True As well as refreshing my page, restarting the server and VSCode, clearing my cache, and using an incognito window, nothing works. The redirect is redirect("https://google.com/") The result is always the same, it says that localhost:8000 was blocked by CORS, and that the preflight request doesn't pass the access control check, because it doesn't have an ACAO header. -
How to Handle CSRF for iFrames in Django with Multiple Whitelabel Sites Without Using a Domain Whitelist?
I’m building a whitelabel solution using Django, where my clients can embed forms from my application within their websites using iFrames. However, I’m running into a problem with CSRF protection when the form is submitted from these external sites, resulting in a 403 Forbidden error due to "CSRF verification failed." My Setup: **Framework: ** Django 4.x with CSRF protection enabled. Use Case: Multiple clients embed our form (rendered via Django templates) into their websites. Users submit the form from these external domains. Issue: Since the CSRF token relies on cookies and cross-origin policies, the CSRF token isn’t included in the form submission, leading to a verification failure. Constraints: No API Calls: The form is rendered server-side using Django templates, and we’re not using a frontend framework like React or Vue, so API-based solutions aren’t suitable. Dynamic Embedding: There’s no fixed number of client websites that can use the form, so maintaining a domain whitelist for CSRF exemption is not scalable. Security: I still want to maintain CSRF protection for security purposes. What I've Tried: Disabling CSRF Middleware: Works, but it compromises security, so it's not a viable long-term solution. Setting CSRF_COOKIE_SAMESITE to None: No effect due to cross-origin restrictions. Allowing … -
Custom authorization restriction in django view
I have an app. The app has users, posts, comments to post etc(it's kinda blog). The task is to limit users from editing objects, that do not belong to the user. Like User can not edit posts made by another one(or comments). I want to write a decorator for it in order to authorize user's actions. So i did, but now i got an error ValueError: The view blog.views.wrapper didn't return an HttpResponse object. It returned None instead. My code: def authorize(func): def wrapper(*args, **kwargs): if kwargs.get('post_id'): instance = get_object_or_404(Post, id=kwargs.get('post_id')) if not args[0].user.id == instance.author_id: return redirect( 'blog:post_detail', post_id=kwargs.get('post_id') ) kwargs.update({'instance': instance}) elif kwargs.get('comment_id'): instance = get_object_or_404(Comment, id=kwargs.get('comment_id')) if not args[0].user.id == instance.author_id: return redirect( 'blog:post_detail', post_id=kwargs.get('post_id') ) kwargs.update({'instance': instance}) func(*args, **kwargs) return wrapper @login_required @authorize def edit_post(request, post_id, instance=None): instance = get_object_or_404(Post, id=post_id) form = PostForm(request.POST or None, instance=instance) context = {'form': form} if form.is_valid(): form.save() return render(request, 'blog/create.html', context) What am i doing wrong? -
New branch in github cannot run manage.py - ImportError: Couldn't import Django
I have a perfectly working static Django site on my main branch in Github. But as soon as a make a second branch branch2 off that exact Django site of my main branch python manage.py runserver gives me this error (but the venv activates with no issues on the new branches before running manage.py) : ** "ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?"** How can I setup my Django/python across these successive branches to run without issues? I am using Django 5.1 and Python 3.12.1 I just want the manage.py server to run on each successive branch I create -
How do calls of models.Manager and custom managers work?
The following question was asked by a different user that subsequently removed the question. But I think it is useful to "dig" a bit in how Django's manager logic works. I extended the models.Manager class and created a custom manager. class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Post.Status.PUBLISHED) It's more than understandable, BUT how do calls of managers work? objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. I don't address get_queryset() method, I just call constructors. Then how does it work? -
How to do aggregate raw sql with julian date in sqlite (with django)
I'm using sqlite3 and django. I wish to calculate the average for all the number of days between last_played and now. (Last_played is just a datetime field). I have so far: avg_days_last_played_sql = """ AVG(julianday('now') - julianday(played_at)) """ # Annotate the average days last played average_days_last_played = Song.objects.aggregate( avg_days_last_played=RawSQL(avg_days_last_played_sql, []) )['avg_days_last_played'] But it gives the error: TypeError: avg_days_last_played is not an aggregate expression