Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Loop through enum in Django?
I have a model in Django class Order(models.Model): class Gender(models.IntegerChoices): Male = (1,), _("Male") Female = (2,), _("Female") I want to send male and female in context context["genders"] = Order.Gender I use that in template like this {% for gender in genders %} <p>{{ gender }}</p> {% endfor %} I want to show male and female in front -
Cannot create list of objects in django rest framework
I am using ListSerializer for updating and creating list of objects, update() works fine but cannot create list of objects (bulk_create). models.py class TutorUser(models.Model): tutor_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tutor') full_name = models.CharField(max_length=255, blank=True) phone_number = models.CharField(max_length=14, blank=True) class WorkExperiance(models.Model): tutor_work = models.ForeignKey(TutorUser, related_name='tutor_work', on_delete=models.CASCADE) organization = models.CharField(max_length=255, blank=True) start_year = models.IntegerField(null=True, blank=True) serializers.py class WorkExperianceListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): tutor_work_mapping = {tutor_work.id: tutor_work for tutor_work in instance} data_mapping = {item['id']: item for item in validated_data} ret = [] for tutor_work_id, data in data_mapping.items(): print(tutor_work_id) tutor_work = tutor_work_mapping.get(tutor_work_id, None) # print(tutor_work_id) if tutor_work is None: ret.append(self.child.create(data)) # print(ret) else: ret.append(self.child.update(tutor_work, data)) for tutor_work_id, tutor_work in tutor_work_mapping.items(): if tutor_work_id not in data_mapping: tutor_work.delete() class WorkExperianceSerializer(serializers.ModelSerializer): id = serializers.IntegerField(read_only=False) class Meta: list_serializer_class = WorkExperianceListSerializer model = WorkExperiance fields = [ 'id', 'organization', 'start_year', ] def update(self, instance, validated_data): instance.organization = validated_data.get('organization', instance.organization) instance.start_year = validated_data.get('start_year', instance.start_year) instance.save() return instance views.py class TutorWorkExperiance(APIView): def get_object(self, request): tutor = TutorUser.objects.get(tutor_user__id=request.user.id) tutor_work = WorkExperiance.objects.filter(tutor_work=tutor) return tutor_work def put(self, request): serializer = WorkExperianceSerializer(self.get_object(request), data = request.data, partial = True, many=True) if serializer.is_valid(raise_exception=True): serializer.save() return Response(serializer.data) return Response({"data": "Not valid"}) In my opinion the problem is here with ID, because WorkExperiance model foreign key with TutorUser model, and … -
Django Dynamic Nested Formsets
I have 3 models Clinic, Doctor, DoctorHours I want to create a dynamic form which will allow me to create those instances in one form something like this: ClinicForm add_doctor_button DoctorForm DoctorHoursForm DoctorHoursForm DoctorForm DoctorHoursForm DoctorHoursForm DoctorHoursForm Please help -
Cache for django restframwork API
I have cache settings in settings.py CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': 'django_cache', } } in view.py from django.views.decorators.cache import cache_page from rest_framework.response import Response @cache_page(60*15) @api_view(['POST', 'GET']) def get_route(request): res = {} # some calculation. return Response(res) post with this json { "ids_item":[4,1,2,3], "id":10 } At first access, cache file is made under django_cache directory, (OK it's cool and smooth.) However second access with same json, it calculates again and makes another cache file. I want to use cache when the json is the same. How can I make this?? -
How to add celery settings to django?
I would like to add the following celery setting modification to the django app worker_send_task_event = False task_ignore_result = True task_acks_late = True worker_prefetch_multiplier = 10 In my celery.py, I got import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings') app = Celery('server') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() And my tasks.py @shared_task def some_task(): pass Celery is executed using the following command: celery -A server worker -Ofair — without-gossip — without-mingle — without-heartbeat I have added them directly to the Django settings.py but I am not sure if Celery actually picked those settings up. So I am wondering if there is another way to add them or someone has a similar experience? I am using celery==5.2.1 Django==3.2.5 -
Django how to append current logged in user to request.data
How do I append current logged in user to request.data when making post call to create a new chat. I tried append it to the request.data but its a querydict and immutable // models.py class ChatLog(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) participants = models.ManyToManyField(Profile, related_name='chatlogs') def __str__(self): return str(self.id) class Message(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) chat_log = models.ForeignKey(ChatLog, on_delete=models.CASCADE, related_name='messages') sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='sentmessages') body = models.TextField() is_read = models.BooleanField(default=False, null=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) class Meta: ordering = ['-created'] // views.py class ChatList(generics.ListCreateAPIView): serializer_class = ChatSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user.profile return user.chatlogs.all() def post(self, request, *args, **kwargs): serializer = ChatSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
How do I get children from parent in a category?
How can I use a filter to get exactly those children who are related to a given parent? I'm use MPTT, but don't use recursetree, because he don't worked with images. Models.py class Category(MPTTModel): parent = TreeForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE) title = models.CharField(max_length=50) image=models.ImageField(blank=True,upload_to='images/') Sample html: {% for category in categories %} <div> <div> <h1>{{ category.title }}</h1> </div> <div> <img src="{{ category.image.url }}"> </div> </div> <div> <ul> {% for subcategory in subcategories %} <li><a href="#">{{ subcategory }}</a></li> {% endfor %} </ul> </div> {% endfor %} views.py def index(request): categories = Category.objects.filter(parent__isnull=True) subcategories = Category.objects.filter(???) # how take self context={'categories': categories, 'subcategories': subcategories } return render(request,'index.html',context) -
Django : How do we automatically hide the parts of a form that requests information that we have already entered?
Saying that, I have two classes (service and product) which are linked with a foreign key. Each class contains a number of forms. I want that each information entered in the form of the product class is no longer requested in the form of the service class and if it has detected it I want to hide the fields which request it in the template! (to avoid repetition) Do you have a method for doing this pleaaaaaase? Product : model.py class Product : name = models.CharField(max_length=100, null=True) length = models.CharField(max_length=2, null=True) type = models.CharField(max_length=2, null=True) Service : model.py class Service : date_creation = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True, blank=True) -
load more buttons javascript
I need your help. How to get different button for all posts, now only first button works and it loads comments for all posts. First getting document.querySelector('#loadmore'); then set I set addEventListener and now how get specific elements for every post [...document.querySelectorAll()] My html code priciple is like this. <div class='post'> <div class='comments'> <div class='comment'> </div> </div> <button id="loadmore">load more</button> </div> -
TypeError when rendering page
I don't understand why it keeps saying that the int object is not iterable.. any help guys?? I'm trying to: 1) get the list of users that are following us 2) initialize an empty posts list and set qs equal to none 3) loop through the users list 3A) for each user that we are following - grab it's profile 3B) for every profile that we know have - grab the posts 3C) add the posts to the post list 4) grab our posts 5) if posts list isn't empty sort the posts by created date Error during template rendering In template C:\Users\Khaled\Desktop\social\project4\network\templates\network\profile_test.html, error at line 12 'int' object is not iterable 2 3 {% block title %} 4 Profiles 5 {% endblock title %} 6 7 {% block body %} 8 <p><b>My Posts: </b> {{profile.get_my_posts}}</p> 9 <p><b>My Posts number: </b> {{profile.get_num_posts}}</p> 10 <p><b>Following Profiles: </b> {{profile.get_following}}</p> 11 <p><b>Following Profiles List: </b> {{profile.get_following_users}}</p> 12 <p><b>My Posts and Posts of Following Users: </b> {{profile.get_all_posts}}</p> 13 {% endblock %} 14 def get_all_posts(self): users = [user for user in self.get_following()] posts = [0] qs = None for u in users: p = Profile.objects.get(user=u) p_posts = p.post_set.all() posts.append(p_posts) my_posts = self.post_set.all() posts.append(my_posts) if len(posts) … -
Django crispy forms removes my initial values from a dynamic model form
I have a model for a 'page' that has a many-to-many relation through an intermediate model with something called 'elements'. I want to make the elements editable from the page edit form. Therefore I dynamically generate ModelChoiceFields. This works well (meaning all selects have the correct initial value), until I apply render_crispy_form to the form in the Jinja2 template. This sets the first value from the dropdown to all select elements, except to the 3rd, where it sets the fourth element as the initial value. The form definition looks like this: class CreatePageForm(ModelForm): class Meta: model = Page fields = [ 'name', ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance') elements = Element.objects.all() if instance is not None: for page2element in kwargs.get('instance').pageelements_set.all(): fieldname = f"element_{page2element.position}" self.fields[fieldname] = ModelChoiceField(elements, initial=page2element.element) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Save')) -
maximum recursion depth exceeded while calling a Python object in Django 3.0
I have updated my code from Django 1.8 to Django 3.0 I guess here my issue is with get_context_data and calling get_context_data in gemethodt_form_kwargs Here is my views.py class JobShiftCreateView(CreateView): template_name = 'contract_worker/job_shift_form.django.html' form_class = JobShiftForm context_object_name = "job_shift" model = ShiftBooking def get_context_data(self, **kwargs): self.user_id = self.request.GET.get('user_id') tomorrow = (datetime.date.today() + datetime.timedelta(days=1)).strftime("%d/%m/%Y") self.due_date = self.request.GET.get('due_date', tomorrow) self.corporate_identity = self.request.GET.get('corporate_identity') date = datetime.datetime.strptime(self.due_date, '%d/%m/%Y').strftime('%Y-%m-%d') context = super(JobShiftCreateView, self).get_context_data(**kwargs) context['shift'] = WorkerAvailableShift.objects.filter(client=self.request.user.client, worker_id=self.user_id, date=date) context["is_create_view"] = True context["corporate_identity"] = self.corporate_identity context["due_date"] = self.due_date context["user_id"] = self.user_id return context def get_form_kwargs(self): kwargs = super(JobShiftCreateView, self).get_form_kwargs() context = self.get_context_data() print("CONTEXT IS",context) kwargs["client"] = self.request.user.client kwargs["is_update_view"] = False kwargs["corporate_identity"] = context['corporate_identity'] kwargs["due_date"] = context['due_date'] kwargs["user_id"] = context['user_id'] kwargs["request"] = self.request kwargs['new_shift_status'] = (('Pending', 'PENDING'),('Accepted', 'ACCEPT'),('Rejected', 'REJECT'),('NoShow', 'NoShow'), ('Cancelled', 'CANCELLED'),) return kwargs def get_work_time(self, shift): if shift.start_time > shift.end_time: dateTime3 = datetime.datetime.combine(datetime.date.today( ), shift.end_time)+datetime.timedelta(hours=24) - datetime.datetime.combine(datetime.date.today(), shift.start_time) else: dateTime3 = datetime.datetime.combine(datetime.date.today( ), shift.end_time) - datetime.datetime.combine(datetime.date.today(), shift.start_time) dateTimeDifferenceInHours = (float(dateTime3.seconds) / 3600) return dateTimeDifferenceInHours - shift.break_time def form_valid(self, form): addtional_days = form.cleaned_data['addtional_days'] booked_with = form.cleaned_data['booked_with'] or None print("BOOKED WITH",booked_with) date = form.cleaned_data['date'] location = form.cleaned_data['location'] week_start = date - datetime.timedelta(days=(date.weekday())) x = datetime.datetime.strftime(week_start, '%d-%m-%Y') week_start = datetime.datetime.strptime( x, '%d-%m-%Y').strftime('%d-%m-%Y') self.object = form.save(commit=False) # work_time = self.get_work_time(self.object) … -
How to create an asynchronous REST API in DJango?
I have a DJango application and am using djangorestframework for my API. Now the problem is I want to create a report which takes about 5 minutes to generate. So what is the best way to create an endpoint which when requested will give the user a status (in progress, completed) of the job and return the final file once its completed? I am confused between using Celery, RabbitMQ, Amazon SQS, Kafka, etc. -
Fetch API post data not receiving in Django view
What I am trying to do ? I am trying to send a post request with data to a Django view using fetch API like this: javascript: const data = { search_text: "", months: 6, property_type: "all" }; const headers = { 'Accept': 'application/json', 'Content-Type':'application/json', 'X-Requested-With':'XMLHttpRequest' } fetch("some-url", { method: "POST", headers: headers, body: JSON.stringify(data) }) .then((response) => response.json()) .then((data) => console.log(data)); view: class MyView(View): def post(self, request, *args, **kwargs): print("request: ", request.POST) # do stuff with post data urls: re_path(r"^my_view/$", login_required(csrf_exempt(MyView.as_view())), name="my_view"), Problem When I try to access the post data in my Django view I get empty QueryDict and the output of the terminal is this: request: <QueryDict: {}> [06/Jan/2022 06:48:19] "POST /my_app/my_view/ HTTP/1.1" 200 114 Forbidden (CSRF token missing or incorrect.): /inbox/notifications/api/unread_list/ [06/Jan/2022 06:48:22] "{"search_text":"","months":"6","property_type":"all"}GET /inbox/notifications/api/unread_list/?max=5 HTTP/1.1" 403 12291 I have tried looking it up and nothing seems to work. We are using react and i know axios can also be used but it should work with fetch api why isn't it working please help. -
How to prevent user from creating new content until currently created content is verified by admin
So i have this CreateShopView a view for seller type users to simply register their shops. the Shop model has a status field which is set to 'processing' by default, and obviously i didn't include the field in my ShopCreateForm so every time a seller registers a shop it's saved in the database with the status of 'processing'. my question is how can i prevent sellers from registering new shops while they still have a shop with 'proccesing' status. thanks in advance. -
Can't render template, getting page not found (404) Django
I can't seem to find the error, site works fine but when I request http://127.0.0.1:8000/test I get the 404 error, I feel so stupid I'm really stuck on this, please help:( Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/test Using the URLconf defined in project4.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] posts-json/ [name='posts-view-json'] ^network/static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, test, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my urls from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views from .views import post_view_json, profile_test_view urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("test/", profile_test_view, name="test"), # endpoints path("posts-json/", post_view_json, name="posts-view-json") ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It's a social website and I'm trying to render the posts and user's profiles on a page. My views from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.http.response import JsonResponse from … -
Django Unit Test Case for Models, Serializers, URL's & Views
I'm a newbie to Unit testing. As I need to perform test case for following models, serializers, views & urls. Can anyone please help. Models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth import get_user_model # Create your models here. class User(AbstractUser): """This Class is used to extend the in-build user model """ ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS')) GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER')) date_of_birth = models.DateField(verbose_name='Date of Birth', null=True) profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='media/profile_images/default.webp', blank=True) bio = models.TextField(verbose_name='Bio') role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES) gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES) Serializers.py class UserSerializer(serializers.ModelSerializer): following = serializers.SerializerMethodField() followers = serializers.SerializerMethodField() class Meta: model = User fields = ('first_name','last_name','username','password','email','date_of_birth', 'profile_image','bio','role','gender', 'following','followers') extra_kwargs = {'is_active':{'write_only':True}, 'password':{'write_only':True}} def create(self, validated_data): logger.info('Information Incoming!') return User.objects.create_user(**validated_data) def update(self, *args, **kwargs): user = super().update( *args, **kwargs) p = user.password user.set_password(p) user.save() return user def get_following(self, obj): return FollowingSerializer(obj.following.all(), many=True).data def get_followers(self, obj): return FollowersSerializer(obj.followers.all(), many=True).data Views.py class UserAPI(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] I tried implementing unit test case but getting an error self.assertEquals(user.get_last_name(), "Johnson") - AttributeError: 'User' object has no attribute 'get_last_name' tests.py class UserTests(TestCase): def setUp(self): User.objects.create( first_name='Louis',last_name='Johnson',username='louis.johnson', email='louis@mail.com',date_of_birth='1994-12-12', bio='Hello I am Louis', role='MODERATOR',gender='MALE') def test_users_model(self): user = User.objects.get(first_name='Louis') self.assertEquals(user.get_last_name(), "Johnson") self.assertEquals(user.get_username(), … -
Select time field dynamically in django forms
I am working on a project of a website to reserve football fields by using Django. In the project, I have 3 models: football field (name, address), team (information about the captain of the team) and reservation (football field, team, date and time of reservation): class Team(models.Model): team_name = models.CharField('Team Name', max_length=60) captain_first_name = models.CharField('Captain Name',max_length=30) captain_second_name = models.CharField('Captain Second Name', max_length=30) captain_email = models.EmailField('User Email', blank = True) captain_phone = models.CharField('Captain Phone', max_length=9) def __str__(self): return self.team_name class Football_Field(models.Model): name = models.CharField('Field name', max_length=120) address = models.CharField('Field address', max_length=120) def __str__(self): return self.name class Reservation(models.Model): team = models.ForeignKey(Team, blank = True, on_delete = PROTECT) football_field = models.ForeignKey(Football_Field, blank = True, on_delete = PROTECT) reservation_date = models.DateField('Reservation Date') reservation_time = models.TimeField('Reservation Time', default=dt.time(00, 00)) I create a reservation form as well, like this: class ReservationForm(ModelForm): class Meta: model = Reservation fields = "__all__" labels = { 'team': 'Select your team', 'football_field': 'Select football field', 'reservation_date': 'Select reservation date', 'reservation_time': 'Select time of reservation' } widgets = { 'team' : forms.Select(attrs={'style': 'width:500px', 'class': 'form-select'}), 'football_field' : forms.Select(attrs={'style': 'width:500px', 'class': 'form-select'}), 'reservation_date' : forms.DateInput(attrs={'class': 'form-control', 'style': 'width:200px', 'type': 'date'}), 'reservation_time': forms.Select(choices=HOUR_CHOICES, attrs={'format':'%H', 'class': 'form-control', 'style': 'width:200px', 'type': 'time', 'required step':"3600"}) } The … -
How to group these base on same address?
{'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': 'Valuation'}, {'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': 'Inspection'} Group these values by address ? for example output should be like: {'street_number': '3', 'street_name': 'Raycraft', 'street_type': 'Dr', 'municipality': 'Amherstview', 'postal_code': 'K7N1Z1', 'type_of_reports': ['Valuation',Inspection]} -
Django - for each field value
I have a question. In my view, I return a dataset which includes: Category Product Price I want to say something like the below, where I show UI elements related to a category as a whole. is it possible? {% for item.category in products %} -
Can't submit image via forms (django)
I'am trying to submit a form and register it on database but imagefield is not working. Everytime i try to upload an image and hit save it just refreshes and tells me that 'This field is required'. Here is my code: models.py: from django.db import models class Photos(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True, null=True) photo = models.ImageField(upload_to='images/') forms.py: from django import forms from .models import Photos class PhotosForm(forms.ModelForm): class Meta: model = Photos fields = [ 'title', 'description', 'photo' ] views.py: from django.shortcuts import render from .models import Photos from .forms import PhotosForm def photo_create_view(request): form = PhotosForm(request.POST, request.FILES or None) if form.is_valid(): form.save() context = { 'form': form, } return render(request, "photos/photo_create.html", context) setting.py: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' template: {% extends 'home.html'%} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> {% endblock %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>website</title> </head> <body bgcolor="pink"> {% block content %} {% endblock %} </body> </html> also my filetree photo: https://i.stack.imgur.com/dmyDM.png -
Save file as zip through django-storage
I am able to store file in S3 but i want to store .zip files instead of file Reference for django-storage : https://testdriven.io/blog/storing-django-static-and-media-files-on-amazon-s3/ storage_backends.py class PrivateMediaStorage(S3Boto3Storage): location = 'private' default_acl = 'private' file_overwrite = False custom_domain = False Model.py class Upload(models.Model): upload_file = models.FileField(storage=PrivateMediaStorage()) using ClearableFileInput field in Admin.py, I am able to upload and download the file but I want to create a .save() method in model to convert my file to zip first and then save to field so it store as zip in S3 bucket -
Not able to install django-allauth in ubuntu 18.04.6 LTS
I'm trying to add social authentication in my project but when I try to install django-allauth it is giving me error I've tried this post but no luck it's giving me another error related to setuptools_rust I've given commands I've tried and errors related to each command. $ pip3 install django-allauth Error : Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 1, in File "/tmp/pip-build-7e3fgl32/cryptography/setup.py", line 14, in from setuptools_rust import RustExtension ModuleNotFoundError: No module named 'setuptools_rust' =============================DEBUG ASSISTANCE========================== If you are seeing an error here please try the following to successfully install cryptography: Upgrade to the latest pip and try again. This will fix errors for most users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip =============================DEBUG ASSISTANCE========================== ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-7e3fgl32/cryptography/ Then I tried to install setuptools_rust as it causing error $ pip3 install setuptools_rust This package does not give me any error it installed successfully Then I've tried to install some commands from this post $ sudo apt-get install build-essential libssl-dev libffi-dev python-dev It did not change anything check response of command Reading package lists... Done Building dependency tree Reading state information... Done build-essential is already the newest … -
What are the setting we can specify in the dajngo setting file for multi-tenant testcses?
I want to run the testcase of multi-tenant without using default schema.So please anyone can help? -
failed to connect with Postgres container in Django
django.db.utils.OperationalError: connection to server at "db" (172.18.0.2), port 5432 failed: FATAL: the database system is starting up I have an issue connecting to the Postgres contaner. I was trying in different ways like setting passwords only in the docker-compose file. Still am stuck. docker-compose.yml version: '3' services: db: image: postgres:alpine environment: - POSTGRES_PASSWORD=password - POSTGRES_USER=user - POSTGRES_DB=userdb volumes: - django_db:/var/lib/postgresql/data container_name: db singup: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 container_name: singup depends_on: - db volumes: django_db: database setting DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'userdb', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'db', } }