Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, guidelines for writing a clean method for a ModelChoiceField
I have read the docs and I can only find guidelines on how to write a clean method for a field within a form: https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute However I have created a field which inherits from ModelChoiceField. I wish to add some custom validation and cleaning, attached to the field and not the form, because the field is used in multiple forms, hence keeping it DRY. I can take a stab at creating a clean method, but eactly what args are passed in, and what should be returned seems to be lacking in the documentation, or I can't find it. Here my field that I wish to add custom cleaning and validation to: class FooChoiceField(forms.ModelChoiceField): def __init__(self, required=True): queryset = Foo.objects.filter(enabled=True).order_by('name') super().__init__( widget=forms.RadioSelect, queryset=queryset, to_field_name='id', # The radio button value field required=required, empty_label=None, ) self.error_messages = { 'required': "Please select a Foo.", 'invalid_choice': "Invalid Foo selected, please try again.", } # Pass the whole DB object into the template so one can access all fields def label_from_instance(self, obj): return obj Heres a guess at it? Is it good, bad? How about validation? def clean(self, value): if value != 'correct': raise ValidationError('Value is challenged in it's correctness') return value -
RuntimeWarning: DateTimeField received a naive datetime, with correct timezone and settings
I am receiving this error message: RuntimeWarning: DateTimeField Z.data_zal received a naive datetime (2020-11-05 07:13:24) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" At this step of creating my models instance: views.py from django.utils import timezone t = Z(data_z=timezone.now().strftime('%Y-%m-%d %H:%M:%S'), data_r=data_r, author=request.user) try: t.save() So as far as I know this error occurs when using datetime module instead of timezone. Sometimes the problem lies in wrong settings.py but I am running: TIME_ZONE = 'Europe/Warsaw' USE_TZ = True What seems to be the issue? -
Datatables Pagination Does Not Show
What I'm trying to do is set up a table just like this: https://datatables.net/examples/basic_init/alt_pagination.html Copied the code but then no success. I've tried so many different variables and removing all but the necessary code and I'm at a loss for what the issue may be. I've gone through several other similar SOF questions and some mentioned "sDom" could be the case so I tried a few variations I've found online but no luck yet. table.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} {% block styles %} <script type="text/javascript" href="https://code.jquery.com/jquery-3.5.1.js"></script> <script type="text/javascript" href="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" type="text/css" src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"> {% endblock styles %} <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" href="{% url 'import' %}"><i class="fas fa-plus-circle"></i> Import New Entires</a> </div> <!-- Content Row --> <div class="row"> <div class="col-md-12"> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior … -
View uploaded files for specific object in django
I want to upload files to a client. So when I check the client they all show the same uploaded files. How do I filter through the files to show only for the specific clients who have files added to them? Model: class Document(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='docs') title = models.CharField(max_length=50) docs = models.FileField() Views.py: def fileDetails(request,pk): files = UploadFile.objects.all() client = Client.objects.all() notes = Note.objects.all() docs = Document.objects.all() context = {'files':files,'client':client,'notes':notes,'docs':docs} return render(request, 'clients/file_detail.html',context) Forms.py: class DocumentForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) I tried using a filter but nothing shows on any of my queries. I just would like to see the docs updated on a client and not see the same for all. Might be something I missed or I'm overthinking this query. -
Get_Absolute_URL Reverse Slugs By Many To Many Field From Another Model in Django
I use Slugs to address the URL. It all works but when I want to show product details. I don't know how can I get two slugs from another model and put it beside the details slug. (the category is in the main URL) (show me all products Samsung mobile) Works: site.com/category/mobile/samsung/ (I want when I want to click one of them, show me the details, but it doesn't work) Doesn't Work: site.com/category/mobile/samsung/s10 Model: from Django.db import models from Django.shortcuts import reverse class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) child_category = models.ForeignKey('self', max_length=150, null=True, blank=True, on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def get_absolute_url(self): return reverse('shop:brands', args=[self.slug]) def get_absolute_url_product(self): return reverse('shop:products', args=[self.child_category.slug, self.slug]) class Product(models.Model): category = models.ManyToManyField(to=Category, related_name='products') name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) description = models.TextField() # Here I did what I knew, but It didn't work. =============================================== def get_absolute_url_details(self): return reverse('shop:product_details', self.category.model.slug, self.category.model.child_category.slug, self.slug) When I use this reverse way, it gives me this Error: 'ForwardManyToOneDescriptor' object has no attribute 'slug' URL: from Django.urls import path from Shop import views app_name = 'shop' urlpatterns = [ path('<slug:brands_slug>/', views.brands, name='brands'), path('<slug:brands_slug>/<slug:product_slug>/', views.products, name='products'), path('<slug:brands_slug>/<slug:product_slug>/<slug:product_details>/', views.details_products, name='product_details'), ] View: def products(request, brands_slug, product_slug): product = Product.objects.filter(category__slug=product_slug, category__child_category__slug=brands_slug) context = … -
Django: how to change the width of AdminDateWidget?
In admin page, I am trying to customise the width of DateField by tweaking attrs of AdminDateWidget in formfield_overrides as below formfield_overrides = { models.DateField: { 'widget': admin.widgets.AdminDateWidget(attrs={'size': '8', 'style': 'width:8ch !important;'}), } } Either changing the size nor style works. What should I do to change the width? Thank you! -
calculate numbers of anuual leave for employees every month
I have Django program for calculating salary of every employee and detect leave days that taken in this month from salary ,the problem that some of employee they apply for leave before like one or to month and program start detecting from salary in month that they apply , so can I write code that can detect from salary only if leave date in the current month. -
Is there any method of integrating ReactJS and Django without implementing Django Restful API?
Guys as you may know when using Vanilla JS you can just deliver html files to Django and just code between the lines in Python language in order to create the functionalities that you need in your backend side of your web application. However this is not the case when we use React JS. Is there any similar way(as vanilla JS and html files)for integrating REACT.JS and Django(except for using rest api endpoints)? -
Django python ValueError: not enough values to unpack (expected 2, got 1)
I have this code to in my views.py that will export to excel, i combined two query in 1 loop but i receive this error ValueError: not enough values to unpack (expected 2, got 1) reports = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).order_by('-inputdate') daily = FmCustomerEmployeeSupplier.objects.filter(id__in=reports.values_list('fmCustomerEmployeeSupplierID')) pairs = [reports, daily] for report, day in pairs: writer.writerow( [ smart_str(report.id), smart_str(report.dateSubmitted), smart_str(report.fmCustomerEmployeeSupplierID), # smart_str(report.fmCustomerEmployeeSupplierID.lastname), # smart_str(report.fmCustomerEmployeeSupplierID.middleInitial), smart_str(day.fmCustomerLocationID), smart_str(day.contact_number), smart_str(day.fmCustomerSectionID), smart_str(day.bodyTemperature), smart_str(report.q1Answer), smart_str(report.q2Answer), ] ) return response -
perform_create function in the django view. How it is different from create function?
I am new to django rest api. I need to create a comment api which is posted in database for a particular blogdetail page. But I dont understand this perform_create function? What does this method does and how it is different in create function?? class CommentCreateAPIView(CreateAPIView): permission_classes= [IsAuthenticated] queryset = Comment.objects.all() serializer_class = CommentListSerializer def perform_create(self, serializer): # user = self.request.user blog = get_object_or_404(BlogPost, pk= self.kwargs['pk']) serializer.save(blog=blog) class BlogPostDetailSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api-blog-post_details', read_only=True) comments= CommentListSerializer (many=True) class Meta: model = BlogPost fields = ['id', 'url', 'image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('created_at',) Also, when I used 'user' in that perform_create function inside serializer.save, it generates error. what is the issue? -
How to use Django db.sqlite3 database with React?
I want to use Django as backed with react and I have already integrated Django with react app. And my react app(blog in my case) is up and running with Django. I have made following changes to do so. Dir for templates inside settings.py: Dir for Static Files inside settings.py: In urls.py rendered template without using views.py: But now I want to use the Django's db.sqlite3 as my database for react app. Please tell me how to configure it ? What additional settings I need to configure to fetch data from db.sqlite3 database inside react app ? If more information about the settings are required then tell me I will edit my question accordingly. -
NoReverseMatch at /add_post Reverse for 'article-details' with arguments '('4', '0')' not found. 1 pattern(s) tried: ['blogpost/(?P<pk>[^/]+)$']
Getting this issue in my django blog project. Everything is specified neatly but I don't understand why it is crashing. urls.py : from django.urls import path from .views import Homeview, ArticleDetailView, AddPostView urlpatterns = [ path('', Homeview.as_view() , name="home"), path('blogpost/<str:pk>', ArticleDetailView.as_view(), name='article-details'), path('add_post', AddPostView.as_view( ), name="add_posts") ] models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse ''' class Post(models.Model): blog_title = models.CharField(max_length=200) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField(default="") def __str__(self): return self.blog_title + '|' + str(self.author) def get_absolute_url(self): return reverse('article-details', args = str(self.id)) articledetails.html* {% extends 'home/base.html' %} {% block content %} <h1>{{post.blog_title}}</h1> </br> {{post.body}} {% endblock %} -
Error in Models raise TypeError('on_delete must be callable.')
when i run following command python manage.py makemigrations I have this error enter code here File "C:\Users\pc\Desktop\django\Chocolate\shop\migrations\0002_product.py", line 21, in Migration ('p_cat', models.ForeignKey(blank=True, null=True, on_delete='models.CASECADE', to='shop.category')), File "C:\Users\pc\Envs\test\lib\site-packages\django\db\models\fields\related.py", line 813, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable``` [1]: https://i.stack.imgur.com/ujUkQ.png -
Why is my API data nt showing up on my django html page?
I am fairly new to coding in general so apologies for my dumb question. I created an API in Node. I put some filler data in the DB and tested the API. Works fine. I created a Django app that attempts to access the data in the API. I am using a CORS module so I can access the API on my local machine. When I load the home page, a GET request is sent to the API, and I can see that the API receives the request. I don't know if any data is being sent back. Nothing shows up in the table on the home page. -API routes- (all routes are starting with /questions) router.get('/', queryQuestions); router.post('/', addQuestion); router.delete('/:uid', deleteQuestion); router.get('/:uid', queryQuestion); router.patch('/:uid', updateQuestion); -Django view- from django.shortcuts import render from django.shortcuts import redirect from django.contrib import messages def home(request): import json import requests api_request = requests.get("http://localhost:3000/questions") try: api = json.loads(api_request.content) except Exception as e: api = "Error..." return render(request, 'frontend/home.html', {'api': api}) Django template 'home' (sample) <table class="table table-striped table-bordered table-hover"> <thead class="thead-dark"> <tr> <th scope="col">ID</th> <th scope="col">Question</th> <th scope="col">Category</th> </tr> </thead> <tbody> {% if api %} {% for list_item in api %} <tr> <td>{{ list_item.uid }}</td> … -
Send mail different email id's when user click Button in Django?
I make real-estate system project, i am try to when user see property and they interested so click "interested" Button then send email to seller register email id and message is " someone(interested email id) is interested in your property id. How to do this if you know so plz know me -
I am trying to convert a python project into exe file however I am getting an 'unexpected EOF while parsing' error
I am using Auto-py-to-exe to convert the python project to an executable file. I am trying to export a Django project to production. I need help to convert the project into exe for commercial use. I am currently stuck. I keep getting this error whenever I try to convert the project using Auto-py-to-exe. Here is the full error An error occurred while packaging Traceback (most recent call last): File "d:\anaconda\envs\deepface\lib\site-packages\auto_py_to_exe\packaging.py", line 131, in package run_pyinstaller() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\__main__.py", line 114, in run run_build(pyi_config, spec_file, **vars(args)) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\__main__.py", line 65, in run_build PyInstaller.building.build_main.main(pyi_config, spec_file, **kwargs) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 720, in main build(specfile, kw.get('distpath'), kw.get('workpath'), kw.get('clean_build')) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 667, in build exec(code, spec_namespace) File "C:\Users\ASUSVI~1\AppData\Local\Temp\tmpk_w1xzg6\mask_detection.spec", line 17, in <module> noarchive=False) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 242, in __init__ self.__postinit__() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\datastruct.py", line 160, in __postinit__ self.assemble() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\building\build_main.py", line 419, in assemble self.graph.process_post_graph_hooks() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\depend\analysis.py", line 365, in process_post_graph_hooks module_hook.post_graph() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\depend\imphook.py", line 440, in post_graph self._load_hook_module() File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\depend\imphook.py", line 407, in _load_hook_module self.hook_module_name, self.hook_filename) File "d:\anaconda\envs\deepface\lib\site-packages\PyInstaller\compat.py", line 588, in importlib_load_source return mod_loader.load_module() File "<frozen importlib._bootstrap_external>", line 399, in _check_name_wrapper File "<frozen importlib._bootstrap_external>", line 823, in load_module File "<frozen importlib._bootstrap_external>", line 682, in load_module File "<frozen importlib._bootstrap>", line 265, in _load_module_shim File "<frozen importlib._bootstrap>", … -
how to start celery periodic task at 9:30 to 12:30 every 30 seconds?
I want to run a celery task in Django from 09:30 to 12:30 for every 30 seconds. Is it possible to turn the interval on for 30 seconds and turn on the interval schedule only for a certain period of the day? -
Django Project and .net project with same database (Postgresql)
I have two project which is Django Project and .net Project with the same database (Postgres). what is the recommended way for them not to have a conflict? because there is a problem when I call a certain field of a table using foreignkey just like this in my views.py reports = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).order_by('-inputdate') for report in reports: writer.writerow([ smart_str(report.fmCustomerEmployeeSupplierID.lastname), smart_str(report.fmCustomerEmployeeSupplierID.firstname), smart_str(report.fmCustomerEmployeeSupplierID.middleInitial), ]) return response this is my models.py class TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords(models.Model): fmCustomerEmployeeSupplierID = models.ForeignKey('FmCustomerEmployeeSupplier', related_name='+', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerEmployeeSupplier") class FmCustomerEmployeeSupplier(models.Model): dateSubmitted = models.DateField(auto_now_add=True, null=True, blank=True) lastname = models.CharField(max_length=500, blank=True, null=True) firstname = models.CharField(max_length=500, blank=True, null=True) middleInitial = models.CharField(max_length=500, blank=True, null=True) bodyTemperature = models.FloatField(blank=True, null=True) def __str__(self): suser = '{0.lastname} {0.firstname} {0.middleInitial}' return suser.format(self) @property def is_past_due(self): return date.today() > self.modifyDate class Meta: verbose_name_plural = "50. Customer's List of Employees, Suppliers and visitors" -
Django run a function while exiting a view or navigating to a different URL from the current URL
In my django application, when I visit a particular URL ex:enter_database, a view function is called that adds database entries. Now when I visit a different URL, I want to clear the database entries. My question, is it possible to call a method while leaving a view/URL. Note: I can clear the entries by adding the logic in every other view, which is not the approach I want to do. I am looking for a way to call a method while exiting the current displayed view. -
Django profile image is incorrectly displaying the logged in user's image (on every profile)
Any assistance in this would be much appreciated. Problem: Logged in user image is displaying on every user's profile in Django 3.1 I extended the Django User model with a OneToOne relationship to another model called UserProfile, which contains an ImageField called profile_pic. Settings for root media folder are setup correctly in settings.py and referred to in root urls.py. Something is incorrect with the class-based view, a generic ListView to display a user's product posts, or I'm incorrectly referring to the profile_pic in the template. Any ideas on how to display each user's profile image on their associated userprofile? Currently, when a user is logged in, his/her image is displaying on every profile. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default='default_profile_pic.jpg', upload_to='profile_pics') class Meta: verbose_name_plural = "User Profiles" def __str__(self): return f'{self.user.username} UserProfile' def save(self, *args, **kwargs): super().save(*args, **kwargs) views.py class ProfileListView(ListView): model = Product template_name = 'users/profile.html' context_object_name = 'products' paginate_by = 12 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) # userprofile = UserProfile.objects.filter(user_id=userprofile) return Product.objects.filter(user=user).order_by('-creation_date') profile.html {% if user.userprofile.profile_pic %} <img class="rounded-circle" src="{{ user.userprofile.profile_pic.url }}" alt=""> {% else %} <img class="rounded-circle" src="media/default_profile_pic.jpg" alt=""> {% endif %} -
Limit Foreign Key Options in Django Select
I have a model for Supplier and another model for Product. Each Product must have a Supplier instance associated to it. Later on, in a separate model form for the Proforma model, the user has to select a Supplier and then a Product. What I'd like to see happen is the Product select options filter down to Products where the Supplier = the Supplier the user has selected. I am not finding much on how to handle this use case...could anyone point me in the right direction? Will this require the use of JS or can I do something to set this in the form directly? Or maybe pass a queryset from the view to this field? Anything even some resource on this would be helpful. models.py class Supplier(models.Model): supplierName = models.CharField(max_length=100) class Product(models.Model): code = models.CharField(max_length=100) supplier = models.ForeignKey(Supplier, null=False, blank=False) class Proforma(models.Model): ... supplier = models.ForeignKey(Supplier, null=False, blank=False, on_delete=models.CASCADE) code = models.ForeignKey(Product, null=True, blank=True, on_delete=models.CASCADE) -
Uploading image into ModelForm in Django?
I am having trouble uploading an image into with a form through Django. The file does not appear in my `templates/auctions' directory, nor does it render in my template (probably because it never uploaded). In my views.py: @login_required(login_url="login") def createListing(request): if request.method == "POST": filled_form = CreateListing(request.POST, request.FILES) if filled_form.is_valid(): user = User.objects.get(username=request.user) new_listing = filled_form.save(commit=False) new_listing.listed_by = user new_listing.save() return HttpResponseRedirect(reverse("index")) else: context = { "createlistingform": filled_form } else: context = { "createlistingform": CreateListing() } return render(request, "auctions/createlisting.html", context) I tried to replicate the approach in "Handing uploads with a file" and it's still not working. My AuctionListing model in models.py has this field: image = models.ImageField(blank=True, upload_to="images/") and my project file settings.py has this configuration: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Is my commit=False in the views.py creating an issue? -
Django Chat Application using channels
I am trying to learn to setup a django chat using channels. I tried the Channels tutorial at https://channels.readthedocs.io/en/latest/index.html and got into some issues. My issue is as below. When 1st browser joins a room it works just fine. But the moment a new browser session joins the same room, the first session does not get the messages and 2 messages are sent to the latest browser session. If a third browser session joins the room, 1st and 2nd session don't get the messages and the third session gets all the 3 messages. I followed every step meticulously but not able to fix the issue. Can anyone guide me please. -
How to get a many to many field display in my select field form
FORM class Form_elegir_carrera(forms.Form): carrera_del_tutor= forms.ModelChoiceField(queryset=None,widget=forms.Select(attrs={'class': 'select is-normal'}),label='Tutor carrera',required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(Form_elegir_carrera,self).__init__(*args, **kwargs) if self.user: self.fields["carrera_del_tutor"].queryset = Tutor.objects.filter(user_id=self.user).get().carrera else: self.fields['carrera_del_tutor'].queryset = Tutor.objects.none() def clean(self): carrera_del_tutor = self.cleaned_data.get("carrera_del_tutor") VIEWS @login_required def elegir_carrera(request, tutor_id): context = { 'tutor_id':tutor_id } if request.method == 'POST': form = Form_elegir_carrera(data=request.POST or None) if form.is_valid(): descripcion = form.cleaned_data.get('carrera_del_tutor', None) context = { 'form': form,'tutor_id':tutor_id } return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: context = { 'form': form, 'tutor_id':tutor_id } return render(request, "elegir_carrera.html", context) else: form = Form_elegir_carrera(user = tutor_id) context = { 'form': form,'tutor_id':tutor_id} return render(request, "elegir_carrera.html", context) context = { 'form': form, 'tutor_id':tutor_id } return render(request, "elegir_carrera.html", context) MODEL class Tutor(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) nombre = models.CharField(max_length=50, blank=False, null=True) apellido = models.CharField(max_length=50, blank=False, null=True) carrera = models.ManyToManyField(Carrera, blank=True) class Meta: verbose_name_plural = "Tutores" verbose_name = "Tutor" def __str__(self): return '%s %s' % (self.nombre, self.apellido) #return self.user.email I want to query all carreras that the user has, and display each of them in a dropdown to be selected. Until now it displays the carreras asociated to the user, but when I make a submit, it throws an error saying that is not one of the availables. -
Why is installing python-psycopg2 on my Docker image not preventing the subsequent "No module named 'psycopg2'" error?
I'm using docker-compose v 1.27.4 on Mac. I have this docker-compose.yml file -- two services, a PostGres DB and a Python/Django app ... services: postgres: image: postgres:10.5 ports: - 5105:5432 environment: POSTGRES_DB: directory_data POSTGRES_USER: chicommons POSTGRES_PASSWORD: password web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn directory.wsgi:application --reload -w 2 -b :8000 volumes: - ./web/:/app depends_on: - postgres This is the Dockerfile used to build the Python/Django container ... FROM python:3.8-slim RUN apt-get update && apt-get install RUN apt-get install -y dos2unix RUN apt-get install -y libpq-dev python-dev RUN apt-get install -y python-psycopg2 RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip WORKDIR /my-app/ COPY requirements.txt requirements.txt COPY entrypoint.sh entrypoint.sh RUN python -m pip install -r requirements.txt RUN dos2unix /my-app/entrypoint.sh ENTRYPOINT ["bash", "/my-app/entrypoint.sh"] However, when I start my application using "docker-compose up," I get the below errors web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 25, in <module> web_1 | import psycopg2 as Database web_1 | ModuleNotFoundError: No module named 'psycopg2' web_1 | web_1 …