Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering in Django admin for multiple conditions on the same record
This is linked to my other question here, which I thought I had resolved. Nevertheless, when applying a filter by school, I get any project where any person belongs to that school. I want, instead, to filter only projects with persons that are both "Principal investigator" (role) and belong to a specific school. Right now the code below outputs a project that has any person linked which belongs to the filtered school, regardless of its role. My models.py: class School(models.Model): name = models.CharField(max_length=200) class Person(models.Model): surname = models.CharField(max_length=100, blank=True, null=True) forename = models.CharField(max_length=100, blank=True, null=True) school = models.ForeignKey(School, null=True, blank=True, on_delete=models.CASCADE) class PersonRole(models.Model): ROLE_CHOICES = [ ("Principal investigator", "Principal investigator"), [...] ] project = models.ForeignKey('Project', on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) person_role = models.CharField(choices=ROLE_CHOICES, max_length=30) class Project(models.Model): title = models.CharField(max_length=200) person = models.ManyToManyField(Person, through=PersonRole) My admin.py: class PISchoolFilter(admin.SimpleListFilter): title = 'PI School' parameter_name = 'school' def lookups(self, request, model_admin): return ( ('Arts & Humanities Admin',('Arts & Humanities Admin')), [...] ) def queryset(self, request, queryset): if self.value() == 'Arts & Humanities Admin': return queryset.filter( person__personrole__person_role__contains="Principal investigator", person__personrole__person__school=5 #5 is 'Arts & Humanities Admin' pk school. ).distinct() [...] def choices(self, changelist): super().choices(changelist) return ( *self.lookup_choices, ) class ProjectAdmin(NumericFilterModelAdmin, ImportExportModelAdmin): list_filter = [PI_SchoolFilter] Why … -
Using nested objects with react-hook-form
I am trying to send data to my backend using react-hook-form and this is the FormData interface: interface FormData { title: string; // other things location: { country: string | null; city: string | null; address: string | null; }; } The problem is that when I submit the form and observe it in my backend (django) it's something like it: <QueryDict: {'title': ['CCC'], 'location': ['[object Object]']}> So that the backend will not set location for the object -
Default avatar doesn't show up in my django-project profile
I tried to load a default avatar image in my profile page but it doesn't show up. However, new avatar photos actually does. Explain me, what did i worng? HTML template of profile page: {% extends 'movieapp/base.html' %} {% load static %} {% block content %} <h1>Данные пользователя</h1> <form method='post' enctype="multipart/form-data"> {% csrf_token %} {% if user.photo %} <p><img src="{{ user.photo.url }}"> {% else %} <img src="{% static 'default_image' %}"> {% endif %} {% for f in form %} <p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }}</label>{{ f }}</p> <div class="form-error">{{ f.errors }}</div> {% endfor %} <p><button type="submit">Отправить</button></p> </form> <hr> <p><a href="{% url 'password_change'%}">Сменить пароль</a></p> {% endblock %} forms.py: class ProfileUserForm(forms.ModelForm): username = forms.CharField(disabled='Логин', widget=forms.TextInput(attrs={'class': 'form-input'})) email = forms.CharField(disabled='E-mail', widget=forms.TextInput(attrs={'class': 'form-input'})) this_year = datetime.date.today().year date_birth = forms.DateField(widget=forms.SelectDateWidget(years=tuple(range(this_year - 100, this_year - 5)))) class Meta: model=get_user_model() fields=['photo','username','email','date_of_birth','first_name','last_name',] labels={ 'first_name':'Имя', 'last_name':'Фамилия', } widgets={ 'fist_name':forms.TextInput(attrs={'class': 'form-input'}), 'last_name':forms.TextInput(attrs={'class': 'form-input'}) } models.py: from django.contrib.auth.models import AbstractUser from django.db import models # Create your models here. class User(AbstractUser): photo=models.ImageField(upload_to='users/%Y/%m/%d/',blank=True,null=True,verbose_name='Фото') date_of_birth=models.DateTimeField(blank=True,null=True,verbose_name='Дата рождения') views.py: class ProfileUser(UpdateView): model=get_user_model() form_class = ProfileUserForm template_name = 'user/profile.html' success_url = reverse_lazy("profile_changed.html") extra_context = {'title': 'Профиль пользователя', 'default_image':settings.DEFAULT_USER_IMAGE} settings.py: STATIC_URL = '/static/' MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/users/' DEFAULT_USER_IMAGE = MEDIA_URL + 'profile/chad.jpg' … -
ModuleNotFoundError: No module named 'config' gunicorn
I'm trying to run a django project on docker project ├── manage.py ├── config │ ├── settings.py │ ├── wsgi.py │ └── ... ├──__init__.py Dockerfile docker-compose.yml entrypoint.sh Dockerfile ... WORKDIR /app ... COPY project project EXPOSE 8000 COPY entrypoint.sh ./entrypoint.sh RUN chmod a+x ./entrypoint.sh ENTRYPOINT ["./entrypoint.sh"] docker-compose.yml version: '3.9' services: ... web: build: . container_name: web restart: unless-stopped ports: - '8000:8000' depends_on: - db ... entrypoint.sh #!/usr/bin/env bash set -e RUN_MANAGE_PY='poetry run python project/manage.py' echo 'Collect static files...' $RUN_MANAGE_PY collectstatic --no-input echo 'Running migrations...' $RUN_MANAGE_PY migrate --no-input echo 'Starting server...' exec poetry run gunicorn project.config.wsgi:application --bind 0.0.0.0:8000 wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = get_wsgi_application() when I run the command docker-compose up I get an error web | ModuleNotFoundError: No module named 'config web | [2024-04-12 20:07:47 +0600] [15] [INFO] Worker exiting (pid: 15) web | [2024-04-12 20:07:47 +0600] [1] [ERROR] Worker (pid:15) exited with code 3 web | [2024-04-12 20:07:47 +0600] [1] [ERROR] Shutting down: Master web | [2024-04-12 20:07:47 +0600] [1] [ERROR] Reason: Worker failed to boot. collectstatic and migrate are successful I tried changing the gunicorn command to ... gunicorn project/config.wsgi:application ... I also tried removing the project from the command and tried … -
I am unable to fetch data line email from mongodb database in django framework while creating password reset page
Keyword: None Sub SQL: None FAILED SQL: ('SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" WHERE ("auth_user"."email" iLIKE %(0)s AND "auth_user"."is_active")',) Params: (('mohanrajjj.learn@gmail.com',),) -
i am deploying my Django app on vercel but then after deployment is successful i get a 404: NOT_FOUND Code: NOT_FOUND when i open the link
I am deploying my Django app on Vercel but then after deployment is successful I get a 404: NOT_FOUND Code: NOT_FOUND when I open the link. I'm deploying to Vercel. I expected my app to run but is not. i don't know the cause of this error. can anyone help me. -
Django GRPC Framework Issues
I am trying to use GRPC frameowrk in Django (latest version). I am facing an error that says: TypeError: requires_system_checks must be a list or tuple. After commenting the below code in base.ppy, the error gets resolved. if ( not isinstance(self.requires_system_checks, (list, tuple)) and self.requires_system_checks != ALL_CHECKS ): raise TypeError("requires_system_checks must be a list or tuple.") But is there any other work around for this so that we are not needed to make changes in the environment. -
In django how can i do listing of the data which has been user forignkey key in this
In my Django project, I have implemented two models: one for the vendor and the other for the user. The user model serves as the main authentication model and has been configured with specific permissions. Additionally, the user model includes a foreign key referencing the vendor model, enabling users to log in with their own credentials in the Django admin interface. Furthermore, users possess the permission to create entries in the User model. However, a challenge arises when attempting to assign a foreign key in the users model's company field, as it currently retrieves all available vendors. Instead, the objective is to retrieve only the vendor associated with the user How i can i achive this? i have tried with admin configs using this @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserAdminChangeForm add_form = UserAdminCreationForm fieldsets = ( ( _("Personal info"), {"fields": ("username", "password", "name", "first_name", "last_name", "email", "role", "vendor")}, ), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) list_display = [ "uuid", "username", "name", "email", "get_vendor_name", "role", "is_superuser", "is_active", "created", ] search_fields = ["name", "uuid", "email"] def get_vendor_name(self, obj): return obj.vendor.name if obj.vendor else None get_vendor_name.short_description = "Vendor Name" def … -
Adjust Stripe Subscription Billing Interval
I aim to modify the billing interval of a subscription in Stripe to include a one-time complimentary extension of 3 months when a user subscribes to a product. The regular billing interval for the plan is 1 year, resulting in a 15-month billing period with the extension. However, after this extended period, it should revert back to the original 1-year billing interval. This isn't a trial period; it's a complimentary 3-month extension for which I want to charge the user immediately. Below is my current implementation for the checkout session view, and I manage all changes using Stripe webhook `class CreateCheckoutSessionView(View): def post(self, request, *args, **kwrgs): ... checkout_session = stripe.checkout.Session.create( success_url=protocol + domain + reverse('payment_success')+'?session_id={CHECKOUT_SESSION_ID}', cancel_url = protocol + domain + reverse('payment_failed'), payment_method_types=['card'], mode='subscription', customer=customer.id, line_items=[{ 'price': price_id, 'quantity': 1, 'metadata': { } }], allow_promotion_codes = True, subscription_data={ 'default_tax_rates': [STRIP_TAX_ID], }, ) return redirect(checkout_session.url, code=303) ` -
Nginx Timeouts getting status code 502 when using Gunicorn
AM currently having an issue here. My Django application is timing out i.e 502 when i place it behind a proxy like nginx. I have tried to increase the timeouts but still not thing has change any help will be highly appreciated. Am using gunicorn as my production server. Any help will be highly appreciated. """ For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ['SECRET_KEY'] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['192.168.43.78', 'localhost'] CSRF_TRUSTED_ORIGINS = ['https://192.168.43.78:8094'] INSTALLED_APPS = [ 'tickets', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'notifications', 'widget_tweaks' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'tickets.middleware.SessionTimeoutMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'tickets.middleware.UserDashboardMiddleware', ] ROOT_URLCONF = 'ticket_resolution.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ticket_resolution.wsgi.application' DATABASES = { 'default': … -
How to make an HTML form be permanent after filling out the field, but before submitting?
Context: I think that filling out a form in a paper with a pen brings the person to pay more attention to what it writes and I wonder if there is a way to bring that to a html form. Expected Behaviour: The person clicks on a checkbox and it stays like that unless the person reloads the page, it cannot be "unclicked", or a person writes a settence in a text field and, after it presses enter (or tab) the field can't be edited. Doesn't have to behave exactly like that, any suggestion close to it will be helpful. It can be in HTML, Js, Python (for Django) or whatever, just wondered if there is a "simple" way or it would be a separate project all throughout. Tried searching on google but didn't find anything close to that. -
Django Installable App. Abstract class with dependencies on it's implementation
In my installable Django application, I have a class called Timer which I intend for users to implement: class Timer(models.Model): class Meta: abstract = True @abstractmethod def finish(self): raise NotImplementedError Additionally, I have a class for recording results: class TimerResults(models.Model): timer1 = models.ForeignKey(settings.TIMER_MODEL) parameter1 = models.IntegerField() parameter2 = models.IntegerField() parameter3 = models.IntegerField() My plan is for users to create their own Timer, implement finish method, which should then create TimerResults. However, this approach isn't working as intended. When I implement Timer in other app, django try to autodiscover other models, and eventually found TimerResults which has a foreign key referencing settings.TIMER_MODEL. However, TIMER_MODEL is not yet created, resulting in the following error message: "The field installable_app.TimerResults.timer was declared with a lazy reference to 'app.timer', but app 'app' doesn't provide model 'timer'." I found a solution where I can make the TimerResults class abstract and force the user to implement it, which solves the problem. However, I'm wondering if there are other ways to solve it. -
Django Allauth Instagram Authentication: Invalid Redirect URI Error
I'm integrating Instagram as a third-party login option into my Django app using Django Allauth. I've set up an Instagram Basic Display API app and configured ngrok to provide my website with an HTTPS scheme. Additionally, I've set up the redirect URIs for authorization, deauthorization, and deletion in the Instagram app settings as shown in the images below: app configuration picture redirect uris i also created an Instagram test user and accept it from the instagram apps and websites page instagram test users In my Django project's settings.py, I've configured Allauth to use the Instagram provider with the following setup: INSTALLED_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.instagram', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': {'access_type': 'online'} }, 'instagram': { 'APPS': [ { 'client_id': '463389002.....', 'secret': 'd34b120.....', 'redirect_uri': 'https://6112-196-179-81-60.ngrok-free.app/account/oauth/instagram/login/callback/', }, ], 'SCOPE': [ 'user_profile', ], } } AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8000', 'https://6112-196-179-81-60.ngrok-free.app', ] ALLOWED_HOSTS = [ 'localhost', '127.0.0.1:8000', '6112-196-179-81-60.ngrok-free.app', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', 'https://6112-196-179-81-60.ngrok-free.app', ] My urlpatterns in urls.py are configured as follows: urlpatterns = [ path('account/oauth/', include('allauth.urls')), ] On my home.html page, I've included the Instagram authentication URL as follows: {% load socialaccount %} <div> <form id="instagram_form" … -
How to connect MySQL Workbench to an AWS EC2 instance
I managed to connect a Django project of mine to an Ubuntu AWS instance. It runs pretty well so far, but now I want to know if it's possible to connect my MySQL Workbench application to it. -
Renaming relational tables on existing schema in Django
Due to a migration from django 2.x to django 4.x, I had to rename my project to fix the intial name containing '-' and no '_'. The initial project name was DEMANDE-PROJET In a Model called DEMANDE ( DEMANDE-PROJET_DEMANDE ), I have a foreign key ( field created_by ) to a model called UserDemandeMapper created_by = models.ForeignKey('UserDemandeMapper', related_name="demande_createur", on_delete=models.SET_NULL, null=True, blank=True) Django is handling this table on its own and on my DB browser I can see it on the name DEMANDE-PROJET_USERDEMANDE2573 Now I renamed my project, django want to request DEMANDE_PROJET_* instead of DEMANDE-PROJET_* I couldn't request anything anymore. I added : class Meta: db_table = "DEMANDE-PROJET_DEMANDE" to link my django model to the tables that gets a fixed name. And now I can request Demande without any problem. The problem comes from my created_by foreign key. I have the value of the ID but not the Model Object of the foreign model. I tried to add UserDemandeMapper a meta class with a db_name but nothing worked. As I'm not a migration expert and this side of django is a bit nebulous, I would like help on it. Thanks by advance. Damien -
How to retrieve the form data in Python using "POST" method
Recently I made a login form using HTML and JS (the JavaScript validating the form), and I have made an action in the form tag in HTML for where I would like to send and store the form data, which is a Python page because it is a server-side language (when I learned that JavaScript is not the best for storing sensitive data because it is client-side). This means I am playing with a language (PY), that I am not very familiar with but have used in the past. So How do I retrieve the form data on my PY script page and maybe I could use Django to get it? Thanks -
how to transfer/move products between inventory management tables using Django
Consider that I have a three database models, one for the backstore, another for the store(mainstore) and another for damaged products and i want to transfer product between these tables at the click of a button. My question is how can I move products that exist in one table to another. The operations should be simple addition and subtraction operation i.e., when I transfer product from the bacstore to the store, I want to deduct from the bacstore and add to the store and vice versa, same for damaged products I haven't tried anything yet too complex yet, overthinking about the logic mostly -
Autocomplete field in django inline admin overwrites filtered queryset
I have this inline admin: class AnalysedSampleInline(admin.TabularInline): formset = AnalysedSampleInlineForm model = SampleDataRelationship extra = 0 show_change_link = True autocomplete_fields = ("sample",) def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "sample": kwargs["queryset"] = ( Sample.objects.select_related("person__family", "file") .order_by("person__family_id") .distinct() .filter(file__type=File.TYPE_BED) ) return super().formfield_for_foreignkey(db_field, request, **kwargs) The filter .filter(file__type=File.TYPE_BED) works fine without the autocomplete field but not with it. I found suggestions saying I should modify the "get_search_results" method. But this method does not exist for inline admins and is never called. How can I apply a filter to the autocomplete queryset of an inline admin? -
How to send an image to Django using Flutter web?
I'm working on a project that uses Flutter web as the client and Django as the backend server. I'm currently working on a registration form that requires to send an image + additional data. My problem is that it seems that there is an issue concerning the file upload, my view is working correctly in Django (I tested it many times) and wen i remove the file field from the django server, the request works perfectly, so I geuss the problem is in the file upload. final reader = html.FileReader(); reader.readAsArrayBuffer(logo); await reader.onLoad.first; final imageData = reader.result as List<int>; final request = http.MultipartRequest("POST", url); final multipartFile = http.MultipartFile.fromBytes('logo', imageData, filename: 'Any_name'); request.files.add(multipartFile); request.fields["nom"] = nom; request.fields["secteur_activite"] = secteurActivite; request.fields["description"] = description; request.fields["email"] = email; request.fields["first_name"] = firstname; request.fields["last_name"] = lastname; request.fields["phone"] = phone; request.fields["password"] = password; request.fields["password2"] = password2; final response = await request.send(); I've worked before with file uplaod between Django and Flutter and I always had problem using the .fromBytes method, the .fromPath method works fine but this method isn't available for Flutter web. Here is my Django code: class EntrepriseRegistrationView(GenericAPIView): serializer_class = EntrepriseSerializer parser_classes = (MultiPartParser,) def post(self, request): request.data serializer = self.serializer_class(data=request.data) if serializer.is_valid(raise_exception=True): serializer.save() data … -
Editing Django default two factor auth login page
So, is it possible to edit of the default Django two factor authentication login page ? I copied the files from my virtual environment to my project directory but it still uses the the default Django template. I have the correct paths and everything. How can I solve this issue I want to able to edit the Django two factor authentication login page to follow the rest of my web app, I want to get rid of the back and next buttons and have only a login button so when the user logs in, they can be taken to the token page(if they have 2 factor auth) -
Many-to-many relationship query in django
I have a many-to-many relationship like this in django, how do I make it so that I can execute the query "get all books written by the author Mattia" class Autore(models.Model): nome = models.CharField(max_length=100) def __str__(self): return self.nome class Libro(models.Model): titolo = models.CharField(max_length=100) autori = models.ManyToManyField(Autore, related_name="libri") def __str__(self): return self.titolo In views.py i try to do this but i can't get the right object. @api_view(["GET"]) def libri_autore(request, nome_autore): # Recupera l'autore dal database (si presuppone che il nome sia unico) autore = Autore.objects.get(nome=nome_autore) serializer = LibroAutoreSerializer(autore) print(autore) # Recupera tutti i libri associati a quell'autore libri = autore.libri.all() print(libri.values()) return HttpResponse("Libri recuperati con successo") -
Form is only submitted when there are two duplicate forms
I am trying to build a site using Django where users can submit coupon codes for their orders to get discounts. So I have a form in my cart.html file where user can enter Coupon Code and avail discount. But the bizarre thing is, the Apply Coupon function is only working when there are two duplicate forms on top of each other. If I remove even one of them and have a single form, as I should have, the code is not working, coupon is not applied, the page url gets stuck at http://127.0.0.1:8000/cart/?csrfmiddlewaretoken=ey3yy96SxX8msYViSD5aiT8TwCwyK5sCRJ9h48TMf3LQeGOmXFl05i2p7gLKta9s&coupon_code=SM20#. I have no idea why it only works when there are two forms and why it gets stuck when there is only one form. Can somebody help me out here please? Thanks in advance! My models.py: class CartItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='cart_items') course = models.ForeignKey(Course, on_delete=models.CASCADE) added_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user.username} added {self.course.title}" class Coupon(models.Model): code = models.CharField(max_length=20, unique=True) discount_percentage = models.PositiveIntegerField(null=True, blank=True) fixed_discount = models.PositiveIntegerField(null=True, blank=True) is_active = models.BooleanField(default=True) users_used = models.ManyToManyField(User, related_name='used_coupons', blank=True) def __str__(self): return self.code My views.py: @login_required def apply_coupon(request): if request.method == 'POST': coupon_code = request.POST.get('coupon_code') try: coupon = Coupon.objects.get(code__exact=coupon_code, is_active=True) if coupon.users_used.filter(id=request.user.id).exists(): messages.error(request, 'You have already used … -
Processing the a image when it got uploaded from admin site
I want to upload some transparent background png through the django admin site. But around the uploading I wish to processing them like making the background to be black. I have a class from models.py like this: class AllClass(models.Model): name = models.CharField(max_length=40, unique=True, help_text="Name of this class(e.g. Wardancer)") archetype = models.ForeignKey('Archetype', on_delete=models.RESTRICT, null=True) icon = models.ImageField(upload_to='icons',default='media/default/default_icon.jpg') A function like this should be called during or after the uploading: def recolor(url): image = Image.open(url).convert("RGBA") new_image = Image.new("RGBA", image.size, "BLACK") new_image.paste(image, mask=image) return new_image.convert("RGB") I tried this approach by adding it into my models.py file: @receiver(post_save, sender=Image) def crop_image(sender, instance, **kwargs): imgage = instance.image original = Image.open(imgage.src.path).convert("RGBA") new_image = Image.new("RGBA", original.size, "BLACK") new_image.paste(original, mask=original) instance.image = new_image It did not work maybe I did not do it the right way. To conclude, I want the image to be processed and preferably replaced with the processed image before the url got stored into the database -
Conditional filling of dropdown in Django backend with list_filters
My models.py: from smart_selects.db_fields import ChainedForeignKey class Funder(models.Model): name = models.CharField(max_length=200) scheme = models.ManyToManyField('Scheme', blank=True) class Scheme(models.Model): name = models.CharField(max_length=200) class Project(models.Model): funder = models.ForeignKey(Funder, on_delete=models.PROTECT) scheme = ChainedForeignKey( Scheme, chained_field="funder", chained_model_field="funder", show_all=False, auto_choose=True, sort=True, null=True, blank=True) As you can see I'm already using smart-selects for getting only the schemes that belong to that specific funder available in the Project dropdown selection in the admin back-end. smart-selects, though, doesn't take care of what happens in the list_filters section of the Admin. What I'd like to achieve: have two 'chained' dropdown filters in my Project admin table, where I'm filtering for projects that have a specific funder, and once I've filtered such projects I want to see only the schemes that belong to that specific funder in the schemes dropdown, with the ability of furter filtering the projects with that specific scheme. My failing attempt so far (admin/py): from admin_auto_filters.filters import AutocompleteFilter, class SchemeFilter( AutocompleteFilterFactory( 'new Scheme', 'scheme' ) ): def lookups(self, request, model_admin): funder = request.GET.get('funder__pk__exact', '') if funder: schemes= Scheme.objects.filter(funder__exact=funder).distinct() else: schemes = Scheme.objects.none() return schemes def queryset(self, request, queryset): funder = request.GET.get('funder__pk__exact', '') if funder and Scheme.objects.filter(funder__exact=funder).count(): return queryset.filter(scheme__exact=self.value()) return queryset class FunderFilter(AutocompleteFilter): title = 'Funder' field_name = … -
Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432?
I have made a Django project with a postgresql backend and am trying to containerize it. This is my Dockerfile: Dockerfile This is my docker-compose.yml file: docker-compose.yml This is my settings.py within the django project to connect to the db: Settings.py The sudo docker build . command runs without any errors. The error I get when I try to run 'sudo docker compose up' is as follows: Is the server running on host "localhost" (127.0.0.1) and accepting web-1 TCP/IP connections on port 5432? I have confirmed that the postgres server is running: Server active(running) This application also runs without any errors on my local. I had created a network(inventory_network) on which I tried attaching my containers. But one thing I noticed was that whenever I ran the 'compose up' command, it created another network inventory_management_inventory_network automatically to which the containers attached instead of my specified network inventory_network: This is what I got when i ran 'inspect' on both these networks, as I wasn't sure if this was related to the issue: inventory_network inspect inventory_management_inventory_network inspect I have tried everything I know and would really appreciate any inputs.