Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django stripe expand data to webhook
i sending order data by post request to stripe and creating session and set my order data in line_items, problem is that i want this line_items data to expand to stripe webhook view and by this data creating order and payment history, i tryed first to set this data to metadata={"data": items} but i get error, because is limited count of keys, it's means that my data is too big to put in metadata, after that i found in that i can put my data in expand like that expand=['line_items'] but nothing happend i don't get this data in my webhook view, but i get this data on stripe website so here is my code i hope someone helps me :p from django.conf import settings from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from django.views.decorators.csrf import csrf_exempt import stripe from rest_framework.decorators import api_view from accounts.models import AppUser stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckoutView(APIView): def post(self, request): try: data = request.data['orderData']['orderItems'] items = [] for i in data.keys(): i = data[i] desc = ', '.join([i.get('name') for i in i.get('extra').values()]) + i.get('extra_info') name = ', '.join( filter(None, [ i.get('name'), i.get('pizzaDough', ''), f"{str(i.get('size', ''))} size" if … -
error while deploying Django project in virtual private server in hostinger
when i try to start nginx its works well but i cant see my site in my domain and when i looks for a error log its says this " gunicorn[313208]: [2024-08-14 05:56:29 +0000] [313208] [ERROR] Connection in use: ('0.0.0.0', 8000) " so i run this command " sudo lsof -i :80 " to check which process is using this port. I saw that these " COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 316452 root 6u IPv4 1073432 0t0 TCP *:http (LISTEN) nginx 316452 root 7u IPv6 1073433 0t0 TCP *:http (LISTEN) nginx 316453 www-data 6u IPv4 1073432 0t0 TCP *:http (LISTEN) nginx 316453 www-data 7u IPv6 1073433 0t0 TCP *:http (LISTEN) " process are using the port which are my nginx. even though i kill that ports using this sudo kill -9 316452 316453 command. Its still appearing again. can anyone help ? tried these codes already gunicorn[313208]: [2024-08-14 05:56:29 +0000] [313208] [ERROR] Connection in use: ('0.0.0.0', 8000) sudo lsof -i :80 sudo kill -9 316452 316453 -
I get an error when I want to save messages in a real-time chat application in Django
I don't get any error like this import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from .models import ChatRoom class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' await self.create_or_update_room(self.room_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Odayı terk et await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps({ 'message': message })) @database_sync_to_async def create_or_update_room(self, room_name): room, created = ChatRoom.objects.get_or_create(name=room_name) ############################################# (env) PS C:\Users\Serkan\Desktop\stock_trackings\stock_tracking> daphne -p 8000 stock_tracking.asgi:application "C:\Users\Serkan\Desktop\stock_trackings\env\Lib\site-packages\django\apps\registry.py", line 260, in get_containing_app_config self.check_apps_ready() File "C:\Users\Serkan\Desktop\stock_trackings\env\Lib\site-packages\django\apps\registry.py", line 138, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. I get an error when I checked the settings, I checked the applications, and when I continue without saving the messages, it works without any problems. -
In django in same web page i need to cnnect both firebase and sql databases. But it is not retrieving sql data when it done
Sql database can not taken to the django although i entered database credentials correctly. A way to connect my sql database with django and is it ok to do it creating models without using sql database Firebase also connected with credentials with its configuration.But if firebasedata loaded sq data not working.On the other hand sql data loaded firebase data not coming. When i place the configuration part to another place of the code it working -
Django Error: "'type' object is not iterable"
i'm a Django beginner and want to write a website for my friend who works as a painter. i wanted to write a rest-api so i can access the models in my frontend (which i didnt implement yet). when i try to call the subdomain for a model i wrote i get the error "'type' object is not iterable". i wanted to make it possible for users that are registered to leave a feedback, so i wrote a class Feedback. I also implemented a FeedbackSerializer and a FeedbackView. i was trying to use chatgpt but that was of no help. stackoverflow also didnt have any similar errors like the one that occured to me. so i came here for help. maybe you guys can help me out. here's what i came up with so far: # api/models.py class Feedback(models.Model): title = models.CharField(max_length=1000, null=False, blank=False) feedback = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) image = models.FileField( upload_to="image", default="default/default-user.jpg", null=True, blank=True) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)], null=False, blank=False) def __str__(self): return self.title def save(self, *args, **kwargs): super(Feedback, self).save(*args, **kwargs) # api/serializers.py class FeedbackSerializer(serializers.ModelSerializer): class Meta: model = api_models.Feedback fields = "__all__" # api/views.py class FeedbackView(generics.RetrieveAPIView): permission_classes = [AllowAny] serializer_class = api_serializer.FeedbackSerializer def get_object(self): … -
Struggling to control Django caching
My Django app is connected to a Postgresql database via the ORM abstraction. The tables in the database are refreshed every few hours via processes completely separate to the Django app. I am not aware of any database caching in the settings.py - I have not added any and am just using the template setup. However I have noticed that Django doesn't show the refreshed data. The only way to reflect this seems to be via a gunicorn restart on the server. I have read through the caching docs but am not sure where the caching is taking place - in the browser or in the django app. Ideally I would like caching to be used for performance purposes but whenever the browser is reloaded or refreshed the latest data is rendered. Any suggestions on how to do this or link useful documentation outside of the django caching doc? -
a Doctor Appointment Booking Using Django Forms
my booking <div class="accordion" id="accordionExample"> <div class="accordion-item"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> نزدیک ترین زمان </button> </h2> <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> ... </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header" id="headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> انتخاب دستی </button> </h2> <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample"> <div class="accordion-body"> {% for bookable in bookables %} <p>{{ bookable.day }} - {{ bookable.start_time }} - {{ bookable.end_time }} - {{ bookable.booking.date }}</p> {% empty %} <p>No bookables available.</p> {% endfor %} </div> </div> </div> </div> my bookable form <form class="modal-body" method="post"> {% csrf_token %} <div class="row justify-content-around"> <div class="col-lg-5"> <label for="{{ form.start_time.id_for_label }}" class="d-block w-100 text-muted"> زمان شروع </label> {{ form.start_time }} <label for="{{ form.end_time.id_for_label }}" class="d-block w-100 text-muted"> زمان پایان </label> {{ form.end_time }} </div> <div class="col-lg-5"> <label for="{{ form.day.id_for_label }}" class="d-block w-100 text-muted"> روز های ویزیت </label> {{ form.day }} <label for="{{ form.capacity.id_for_label }}" class="d-block w-100 text-muted"> ظرفیت </label> {{ form.capacity }} </div> </div> <button class="btn btn-success px-5 p-2 mt-4 rounded-md"> ذخیره </button> </form> my form class BookableForm(forms.ModelForm): class Meta: model = Bookable fields = "__all__" widgets = { 'start_time': forms.TimeInput( attrs={'class': 'form-control mb-3', 'data-jdp': 'data-jdp', 'autocomplete': 'off'} ), … -
Django Template Table custom cells?
I am playing around with django a bit and wanted to create a table which I'm filling with some whatever. I am very new to programming with django and html. I have 4 for loops (sounds like a lot) {% for row in rows %} <tr> {% for column in columns %} {% for item1 in items1 %} {% if item1.attribute == column.attribute and something %} <td>{{item1.name}}</td> {% endif %} {% endfor %} {% for item2 in items2 %} {% if something %} <td>{{item2.name}}</td> {% endif %} {% endfor %} {% endfor %} </tr> {% endfor %} So as you can see, only if one of the if conditions is true a cell is created. This is obviously not what I want and I know by doing <td> {% for column in columns %} <td> {% for item1 in items1 %} . . . {% endif %} {% endfor %} </td> there would be a cell for every row and column tuple. However I want to individualy add a different background to each of the item types (item.type exists) like <td bgcolor= "color_name | hex_number | rgb_number"> </td>. I first tried a variable {% with emptycell="yes" %} that I change … -
Import Errors for Custom Django Apps in XBlock Development on OpenEdX Palm Version
I’m having trouble importing custom Django apps in an Open edX XBlock. Even though the Django application is installed in the Open edX environment, I'm encountering errors. The video_rating custom Django application is installed and working perfectly in this environment. onlineoffline is my XBlock. 2024-07-22 10:43:36,866 WARNING 32 [xblock.plugin] [user None] [ip None] plugin.py:144 - Unable to load XBlock ‘onlineoffline’ Traceback (most recent call last): File “/openedx/venv/lib/python3.8/site-packages/xblock/plugin.py”, line 141, in load_classes yield (class_.name, cls.load_class_entry_point(class)) File “/openedx/venv/lib/python3.8/site-packages/xblock/plugin.py”, line 70, in load_class_entry_point class = entry_point.load() File “/openedx/venv/lib/python3.8/site-packages/pkg_resources/init.py”, line 2517, in load return self.resolve() File “/openedx/venv/lib/python3.8/site-packages/pkg_resources/init.py”, line 2523, in resolve module = import(self.module_name, fromlist=[‘name’], level=0) File “/openedx/venv/lib/python3.8/site-packages/onlineoffline/init.py”, line 1, in from .onlineoffline import OnlineOfflineClassXBlock File “/openedx/venv/lib/python3.8/site-packages/onlineoffline/onlineoffline.py”, line 4, in from openedx.features.video_rating.models import UserFeedbackSave,Questions,Type,Ratings ModuleNotFoundError: No module named ‘openedx.features.video_rating’ -
Use Custom Manager to Filter on a Reverse Relation
I have a set of users and a set of assignments each user submits. class User(models.Model): name = models.CharField() class Assignment(models.Model): user = models.ForeignKey( "User", related_name="assignments" ) status = models.CharField() approved = AssignmentActiveManager() rejected = AssignmentRejectedManager() ... I created custom managers to determine different states of assignments, as it's complex and should be internal to the model. For example: class AssignmentActiveManager() def get_queryset(self): return Assignment.objects.filter(status__in=["Approved", "Accepted"]) Now I want to get all users with an approved assignment, using the Assignment.approved manager, because I don't want to duplicate the filtering code. I can do Users.objects.filter(assignments__in=Assignments.approved.all()).all() However, this query involves a WHERE status IN (SELECT ...) subquery. This is going to be less efficient than the query generated if I had written the filtering explicitly: Users.objects.filter(assignments__status__in=["Approved", "Accepted"]).all() Which would do an INNER JOIN and WHERE status IN (Approved, Accepted). So my question is. Is there a way to select users by filtering on assignments using the Assignment custom managers efficiently? -
Django project on CS50dev IDE
I am currently working on the CS50 Web course and am focusing on Project 1. For my development environment, I decided to use the online CS50dev IDE because I cannot install Django on my PC due to administrative restrictions. One of the first tasks in the project is to set up routing for files. For example, if you type server_address/wiki/css, you should be able to view the css page (if it exists); otherwise, an error page should be rendered. However, when I run the server and try to view pages, the error page is always displayed instead of the css page (or any other existing page). I suspect the problem might be related to the storage configuration. When I use the debugger to test my get_entry function, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Requested setting STORAGES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Could you please help me figure out this bug? I’ve spent hours researching it, but nothing seems to be working. I tried to configure the storages but that didn't help. -
Django: How to solve multi-dev issue for database that should be populated
I'm working on a project with some people and we've been adding images and some text to the database (Postgres) through the django admin, they get added to the database but when someone commits to the GitHub repository and someone else pulls and runs he doesn't see any of the things added to the database. It looks like django doesn't leave instructions of what to populate to the database in the code itself so how can we get around this issue? Is there a standard method people already use? -
Modify available choices for a multiple Django from based on current selection
I have a form that works with these base choices: class ShockForm(forms.Form): sector = forms.ChoiceField(choices=[ ('c1', 'Choice 1'), ('c2', 'Choice 2'), ('c3', 'Choice 3'), ]) amount = forms.FloatField() the form is rendered a number of times depending on the user's previous selection, it displays n forms if n was inputed by the user on the previous screen. I want to make the forms dynamic, ie, if an user selects one choice in the first form that choice is not available on the other form and so on, so there cannot be duplicated choices. I belive JS is the solution for this as I am not saving every form one by one but all in one go (see views below). However I have very little knowledge of JS and all I tried did not work. Any guidance? Here is the template relevant content: <form method="post"> {% csrf_token %} {% for form in shocks_forms %} <h4>Sector {{ forloop.counter }}</h4> {{ form.as_p }} {% endfor %} <button type="submit">Submit</button> </form> And here the back end view: def simulation_shocks_view(request, pk): simulation = get_object_or_404(Simulation, pk=pk) number_of_sectors_to_shock = simulation.number_of_sectors_to_shock if request.method == 'POST': form_list = [ShockForm(request.POST, prefix=str(i+1), impact_area=simulation.impact_area) for i in range(number_of_sectors_to_shock)] if all(form.is_valid() for form in … -
I cannot figure out why I am still having pathing issues in Django for the Admin Panel as it is having trouble finding the static file
I have changed my Django folder structure quite late in the project, I am new to Django, so I did not prepare the folders at the beginning of the project which is my fault. I have been having issues with the static files, I managed to fix the static files for the project, but my Django Admin panel seems to have issues finding the static files for the admin panel. These are the types of errors that I am getting: WARNING 2024-08-14 09:27:03,080 log 10464 13992 Not Found: /static/admin/css/responsive.css WARNING 2024-08-14 09:27:03,080 log 10464 12416 Not Found: /static/admin/css/nav_sidebar.css WARNING 2024-08-14 09:27:03,080 basehttp 10464 13992 "GET /static/admin/css/responsive.css HTTP/1.1" 404 179 WARNING 2024-08-14 09:27:03,080 basehttp 10464 12416 "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 179 The admin panel does load it's just the aesthetic aspects of it not loading, such as the css. This is the folder structure: ├───api │ ├───migrations │ ├───utils ├───assets │ ├───css │ └───images ├───config │ ├───django (This is where the base.py, prod.py, test.py, dev.py files) │ │ └── base.py │ │ └── test.py │ │ └── dev.py │ │ └── prod.py │ ├───settings (This is for storing files such as celery.py) │ ├───env.py │ ├───urls.py ├───templates │ └───includes └───.env └───manage.py … -
Custom Permission Mixin Django Rest Framework
I am trying to create a custom mixim that handles additional permission checks in my views. This is what I have tried: class ProfilePermissionsRequiredMixin: required_permissions = [] def get_required_permissions(self): return self.required_permissions def dispatch(self, request, *args, **kwargs): # Check if the user is authenticated if not request.user.is_authenticated: raise PermissionDenied("You must be logged in to access this resource.") # Get the user's profile profile = request.user.profile # Check if the profile has all the required permissions if all(profile.has_perm(perm) for perm in self.get_required_permissions()): return super().dispatch(request, *args, **kwargs) # Return 403 Forbidden if any permission check fails raise PermissionDenied("You do not have permission to access this resource.") The issue here is that the request that I get is not authenticated. I use a custom authentication class and it is apparently not applied in the despatch. What can I do to fix this? -
Is there a way to fix AuthCanceled error in the google-sign in in Django?
I was just developing my website, adding CustomUsers, managing profiles, etc., and everything went well, but when I tried to add Google Sign In, I kept getting errors in mid-authentication, like: !error image(https://i.sstatic.net/JqgI0S2C.png) or a text description of it: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/accounts/complete/google-oauth2/?state=Ykq4uYjlm2UMCICLCaKNQtDFmb6hEeQf&code=4%2F0AcvDMrA19DF4z27cVgLBo0ZMua4bL0njYqz-XKFiX9cjZ4k_xf9qAAAD_thq74_ghMhRUw&scope=email+profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=consent Django Version: 4.2.14 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'social_django'] 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', 'social_django.middleware.SocialAuthExceptionMiddleware', 'django_user_agents.middleware.UserAgentMiddleware'] Traceback (most recent call last): File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapper_view_func response = view_func(request, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\utils.py", line 49, in wrapper return func(request, backend, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_django\views.py", line 31, in complete return do_complete( File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\actions.py", line 49, in do_complete user = backend.complete(user=user, redirect_name=redirect_name, *args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\base.py", line 39, in complete return self.auth_complete(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\utils.py", line 256, in wrapper return func(*args, **kwargs) File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\oauth.py", line 411, in auth_complete state = self.validate_state() File "C:\Users\norou\AppData\Local\Programs\Python\Python310\lib\site-packages\social_core\backends\oauth.py", line 101, in validate_state raise AuthStateMissing(self, "state") Exception Type: AuthStateMissing at /accounts/complete/google-oauth2/ Exception Value: Session value state missing. Please note that I … -
In Django, I would like to narrow a choice using a form to another form
I am trying to use the result of a selection as input to another selection. I have been working on this for three weeks, and I cannot find a simple answer. Here are my models: from django.db import models # Create your models here. class School(models.Model): id = models.CharField(primary_key=True, max_length=10) school_name = models.CharField(max_length=80) def __str__(self): return(f"{self.id} {self.school_name}") return self.id class Meta: ordering = ['id'] indexes = [ models.Index(fields=['id', 'school_name']), ] class Courses(models.Model): id = models.CharField(primary_key=True, max_length=12) created_at = models.DateTimeField(auto_now_add=True) school = models.ForeignKey(School, on_delete=models.PROTECT, related_name='school') name = models.CharField(max_length=150, null=True, blank=True) cost = models.CharField(max_length=75, null=True, blank=True) class Meta: ordering = ['id'] indexes = [ models.Index(fields=['school']), models.Index(fields=['name', 'id'])] def __str__(self): return(f"{self.school} {self.name}") return self.name class Student(models.Model): course = models.ForeignKey(Courses, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) student_id = models.CharField(max_length=20, null=True, blank=True) class Meta: ordering = ['course'] indexes = [ models.Index(fields=['course']), ] And my views: def choose_school3(request): if request.user.is_authenticated: aschool = Courses.objects.all() form=SelectSchoolForm(request.POST) if request.method == "POST": if form.is_valid(): data = form.cleaned_data choice = data['school'] selected_school = Courses.objects.filter(school=choice).values() context = {'choice': choice} return render(request, 'add_student2b.html', context) context = {'form': form, 'aschool':aschool} return render(request, 'choose_school3.html', context) else: messages.success(request, "You Must Be Logged In To View Records!") return redirect('main') def add_student2b(request, choice): chosen_school = Courses.objects.filter(school=choice).values() form = AddStudentForm(request.POST) context … -
How to create restore password function with Django rest framework?
I have a Django Rest Framework app. And I try to create reset password function. But the problem I am facing is that some functions are not called by the Django Rest Framework. So I have a module accounts--> templates --> registration and then the html templates in it. Like: password_reset password_reset_confirm password_reseet_done password_reset_form And in the accounts module I have a views.py file: from django.shortcuts import render from django.utils.http import urlsafe_base64_decode from django.utils.encoding import force_str from django.contrib.auth.tokens import default_token_generator from rest_framework import generics from .serializers import ChangePasswordSerializer class PasswordResetConfirmView(generics.GenericAPIView): serializer_class = ChangePasswordSerializer def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserModel.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): return render(request, 'registration/password_reset_confirm.html', {'validlink': True, 'user': user, 'uidb64': uidb64, 'token': token}) else: return render(request, 'registration/password_reset_confirm.html', {'validlink': False}) def post(self, request, uidb64, token, *args, **kwargs): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = UserModel.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response({"message": "Password has been reset successfully."}, status=status.HTTP_200_OK) else: return Response({"error": "Invalid link."}, status=status.HTTP_400_BAD_REQUEST) And a serializers.py file: from django.utils.translation import gettext as _ from … -
Is there any option to get "to-many" relation objects while saving "parent" object?
I have three models class Parent(models.Model): name = models.CharField(blank=True, max_length=20) ... # other fields def _get_childs(self): first_childs = [f'{child.name}' for child in self.one_childs.all()] second_childs = [f'{child.name}' for child in self.two_childs.all()] return [first_childs + second_childs] @classmethod def get_config(cls) -> str: try: instance = cls.objects.get() except cls.DoesNotExist: return '' config = {} for child in instance._get_childs(): config[child] = { 'interval': 1000, ... # other fields } return json.dumps(config, indent=4) class OneChild(models.Model): name = models.CharField(blank=True, max_length=20) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='one_childs') ... # other fields class TwoChild(models.Model): name = models.CharField(blank=True, max_length=20) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, blank=True, null=True, related_name='two_childs') ... # other fields I need to write get_config result to file ('/tmp/config' as example) on Parent save. everything works fine, but i get previous relations childs, not new. i tried to use it in post_save signal for Parent model, but it is does not help. there is a signal for example @receiver(post_save, sender=Parent) def update_config(sender, instance, **kwargs): config_json = instance.get_config() file_path = '/tmp/config.json' with open(file_path, 'w') as file: file.write(config_json) when I save Parent all values become valid except child.name's is there any option to achieve this? -
Deployment of containerized Reat Django app with nginx
I have an app: client in react. server in django. the app is containerized: backend-container and frontend-container as follows (docker-compose.yaml): version: '3.8' services: backend: build: context: ./backend dockerfile: Dockerfile args: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: ${POSTGRES_HOST} SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} CORS_ALLOWED_ORIGIN: ${CORS_ALLOWED_ORIGIN} REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} image: backend container_name: backend-container ports: - "8000:8000" environment: POSTGRES_USER: ${POSTGRES_USER} POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} POSTGRES_HOST: ${POSTGRES_HOST} SECRET_KEY: ${SECRET_KEY} DEBUG: ${DEBUG} CORS_ALLOWED_ORIGIN: ${CORS_ALLOWED_ORIGIN} REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} frontend: build: context: ./frontend dockerfile: Dockerfile args: REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} image: frontend container_name: frontend-container ports: - "3000:3000" environment: NODE_ENV: production REACT_APP_ALLOWED_HOST: ${REACT_APP_ALLOWED_HOST} and the app is hosted on an EC2 instance, deployed using github action: name: My workflow on: workflow_dispatch jobs: first-job: runs-on: self-hosted steps: - name: Checkout code uses: actions/checkout@v4 - name: Build the Docker backend image env: POSTGRES_USER: ${{ secrets.POSTGRES_USER }} POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} POSTGRES_HOST: ${{ secrets.POSTGRES_HOST }} SECRET_KEY: ${{ secrets.SECRET_KEY }} DEBUG: ${{ secrets.DEBUG }} CORS_ALLOWED_ORIGIN: ${{ secrets.CORS_ALLOWED_ORIGIN }} REACT_APP_ALLOWED_HOST: ${{ secrets.REACT_APP_ALLOWED_HOST }} run: | sudo docker-compose -p fullstack down sudo POSTGRES_USER=$POSTGRES_USER POSTGRES_PASSWORD=$POSTGRES_PASSWORD POSTGRES_HOST=$POSTGRES_HOST SECRET_KEY=$SECRET_KEY DEBUG=$DEBUG CORS_ALLOWED_ORIGIN=$CORS_ALLOWED_ORIGIN REACT_APP_ALLOWED_HOST=$REACT_APP_ALLOWED_HOST docker-compose -p fullstack up --build -d I can see the containers are running on my EC2 instance. I configured an nginx on the EC2 instance: server { listen 80; server_name _; location / … -
Review table for two different profile types in Django and PostgreSQL DB
I have a question how I should design this relational database. I have a main profile, which has 2 sub-profiles, which are weak entities. These sub-profiles represent counterparts of a business process, an Employee and an Employer. Given I want to have tables that are related to these sub-profiles, such as "Review" or "Job Posting" (Similar to LinkedIn), which approach would be the most suitable: Creating a separate table for each profile type, e.g., EmployerReview and EmployeeReview Creating a single unified table, which has fields to determine which sub-profile type is sending and receiving the data. e.g., Review sender models.ForeignKey(Profile...) receiver models.ForeignKey(Profile...) sender_type models.CharField(max_length=15, choices=PROFILE_TYPES) receiver_type models.CharField(max_length=15, choices=PROFILE_TYPES) My main concern is the performance issues, e.g., when wanting to query all EmployerProfiles and the related Reviews of that profile. Now, If I have understood correctly, in method 2. you would have to do filter query, which is obviously slower than select_related (Similar to SQL Join?). The gain would be more flexibility and simple complexity, but there would be performance loss. Which of these methods would be more standardized or optimized way for such a problem? I tried creating both of the solutions, and they both work, but I am not … -
SequenceField to share unique IDs across multiple tables and more
Hello Django community, I recently faced a case where I had to have multiple models/tables having unique IDs coming from the same postgresql sequence. I was amazed to see how difficult it is to this from Django and I couldn't find a nice package doing this neither. So I developed django-sequencefield to address this limitation.: https://github.com/quertenmont/django-sequencefield Cherry on the cake, django-sequencefield could also be used to generate uniqueId containing additional data. I showcase a model using an id that is composed of a date (2 bytes) and a unique sequence id (6 bytes). This is useful to cluster the table simultaneously by date and Id while guaranteeing unicity and avoiding the use of composed primary key (not supported by Django). I would like to have feedback on this work, so feel free to try and comment. Thank in advance Loïc -
Can't install Python Imaging Library "Pillow"
I have tried to install pillow library for my Django project it won't install. I have tried many times there are no specific answer for problem on internet. First Try Terminal Input: (venv) PS C:\Users\Samsung\Desktop\lms-django> pip install pillow Terminal Output: Fatal error in launcher: Unable to create process using '"c:\users\samsung\desktop\lms\venv\scripts\python.exe" "C:\Users\Samsung\Desktop\lms-django\venv\Scripts\pip.exe" install pillow': The system cannot find the file specified. Second Try: Terminal Input: (venv) PS C:\Users\Samsung\Desktop\lms-django> python3 -m pip install Terminal Output: The term 'python3' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:8 + python3 <<<< -m pip install + CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException I want to find a way to install the python pillow library. -
Django losing connection with Postrgres creating a tenant
Developing a Django project using django-tenants. In the moment of new user registration, the tenant has to be created on the host domain with address "project-url.ru/username/..." Here is view.py with registration def create_user_tenant(request): user = UserClass.objects.get(username=request.POST['username']) schema_name = f'{user.username}_schema' try: with transaction.atomic(): tenant = Tenant(schema_name=schema_name, user=user) tenant.save() logger.debug(f'Tenant {tenant} created') domain = Domain(domain=HOST_NAME, tenant=tenant, is_primary=True) domain.save() logger.debug(f'Domain {domain} created for tenant {tenant}') logger.info(f'Tenant for {user.username} was created.') except IntegrityError as e: logger.error(f'Error creating tenant or domain for user {user.username}: {e}') except Exception as e: logger.error(f'Unexpected error creating tenant or domain for user {user.username}: {e}') def registration(request): error_msg = '' with transaction.atomic(): if request.POST: logger.debug(f"Registration request") form = UserRegistrationForm(data=request.POST) if form.is_valid(): user = form.save() logger.debug(f"User {user.username} has been registered") create_user_tenant(request) return redirect('login') else: error_msg = form.error_messages logger.debug(f"Registration form is invalid. Error {error_msg}") context = { 'form': UserRegistrationForm(), 'error_msg': error_msg, } return render(request, 'users/registration.html', context) However, when saving the tenant tenant.save() I get an error: The connection 'username_schema' doesn't exist. At the same time, if I do the same via ./manage.py shell everything works correctly. DB settings in settings.py: DATABASES = { "default": { 'ENGINE': "django_tenants.postgresql_backend", ..... } } DATABASE_ROUTERS = ( 'django_tenants.routers.TenantSyncRouter', ) MIDDLEWARE = [ 'django_tenants.middleware.main.TenantMainMiddleware', ... ] Postgres runs … -
Serving Static Files with Nginx and Django in Docker
Despite seeing many similar issues in other threads, I've been unable to configure Nginx to serve static files from my Django project. Here are my two static variables in my settings.py: STATIC_URL = '/static/' STATIC_ROOT='/opt/django/portfolio/collectstatic' Here is my dockerfile to build project image: FROM python:3.11-slim WORKDIR opt/django/ COPY pyproject.toml . RUN python -m pip install . COPY ./portfolio/ ./portfolio/ WORKDIR portfolio/ RUN python manage.py collectstatic --noinput RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8000 CMD ["gunicorn", "portfolio.wsgi:application", "--bind", "0.0.0.0:8000"] Here is the docker-compose.yml: services: web: build: context: . dockerfile: ./docker/Dockerfile_django container_name: webserver volumes: - static_data:/opt/django/portfolio/collectstatic expose: - "8000" ports: - "8000:8000" depends_on: - db networks: - docker_network db: image: postgres:15 container_name: db_postgres expose: - "5432" ports: - "5432:5432" volumes: - postgres_data:/var/lib/postgresql/data environment: POSTGRES_DB: postgres POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres networks: - docker_network nginx: image: nginx:latest container_name: nginx ports: - "80:80" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - static_data:/opt/django/portfolio/collectstatic depends_on: - web networks: - docker_network volumes: postgres_data: static_data: networks: docker_network: driver: bridge name: docker_network And finally, here is my nginx.conf: events {} http { server { listen 80; server_name localhost; location /static { alias /opt/django/portfolio/collectstatic; autoindex on; } # skip favicon.ico location /favicon.ico { access_log off; return 204; } location / { proxy_pass …