Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery task has disabled backend until another task (from a different app) is imported
I'm having a problem with celery, redis backend in a django environment. When I import a celery task from one file the backend is DisabledBackend, and any calls to delay() hang/block. However when I import a celery task from another file, the backend is RedisBackend and any calls to delay() work fine. The weird part is that after importing the second task, the backend of the first task changes to RedisBackend and then works fine. See example below: >>> from file1 import task1 >>> task1.backend <celery.backends.base.DisabledBackend object at 0x7f2bf3582470> >>> from file2 import task2 >>> task2.backend <celery.backends.redis.RedisBackend object at 0x7f2bf2bc7668> # And now the very weird bit, the backend of task1 now is correct >>> task1.backend <celery.backends.redis.RedisBackend object at 0x7f2bf2bc7668> Both tasks are defined using the following construct from celery import shared_task @shared_task def task1(): # Logic here from celery import shared_task @shared_task def task2(): # Logic here I can't seem to find any reason why this might happen. When I inspect the celery log I see both tasks registered. - ** ---------- [config] - ** ---------- .> app: *redacted* - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 2 … -
Annotate: Pass parameter to Subquery
I have a queryset as follow: result = model_a.union(model_b) The result have these fields: (`user`, `date`) Is it possible pass date field to a Subquery as follow? result.annotate(amount = Subquery( Model_C.objects.filter( Q(model_c__date__lt=('_date') # <--- Pass date here ) .aggregate(Sum('amount'), 0))['amount'] ) output_field=IntegerField() )) According to the above implementation, the following error occurs: ... raise FieldError('Related Field got invalid lookup: {}'.format(lookup_name)) django.core.exceptions.FieldError: Related Field got invalid lookup: date_lt Is it possible to pass the fields from the result to Subquery in order to filtering? Is there another way? -
Django-rules makemigrations "No changes detected"
I'm using django-rules for object level security. I recently added a new field "managers" to my Location model, but python manage.py makemigrations doesn't detect it: No changes detected Given the following model: from django.db import models from django.conf import settings from django.contrib.auth.models import Group from rules.contrib.models import RulesModel # Create your models here. STATUS = [ ("red", "red"), ("amber", "amber"), ("green", "green"), ] class Location(RulesModel): name = models.CharField(max_length=200) description = models.TextField(blank=True) status = models.CharField(max_length=5, choices=STATUS, default="green") owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) managers = models.ForeignKey(Group, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I red on https://izziswift.com/django-1-7-makemigrations-not-detecting-changes/ that makemigrations might not detect it because the Class doesn't inherit django.db.models.Model. Is there a way to get python manage.py makemigrations working as expected? -
Django form errors appearing without error
I made a research here in Stack and my problem is the opposite of the majority, I saw some ways to make it appear, but my problem is that it's appearing when the user hits the "Register" button / Refresh the register page. So it's an annoying thing that appears wherever the user enter/refresh the page because the form is empty. View.py @unauthenticated_user def register(request): form_u = CreateUser(request.POST) form_c = CreateClient(request.POST) if request.method == 'POST': form_u = CreateUser(request.POST) form_c = CreateClient(request.POST) if form_u.is_valid() and form_c.is_valid(): user = form_u.save() group = Group.objects.get(name='func') user.groups.add(group) client = form_c.save(commit=False) client.user = user client.save() return redirect('login') else: form_u = CreateUser() form_c = CreateClient() context = {'form_u': form_u, 'form_c': form_c} return render(request, 'register.html', context) HTML <form method="POST" action="" id="ativa"> {% csrf_token %} ... </form> {{form_u.errors}} {{form_c.errors}} <div class="mt-4"> <div class="d-flex justify-content-center links"> Have an account ? <a href="{% url 'login' %}" class="ml-2">Login</a> </div> </div> Print P.S: The site is in portuguese, but I can share the form link in heroku -
onw of my two app is not working in django
Below is my code. In my hello_world project there is two app pages. one is home page and another is profile page. home page is working fine, but profile page is showing error. hello_world urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('home_page.urls',)), path('profile_page',include('profile_page.urls',)) ] home page urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.home,name='home page'), ] home page views.py from django.http import HttpResponse def home(request): return HttpResponse('home page') profile page urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('profile_page',views.profile,name='profile page'), ] profile page views.py from django.http import HttpResponse def profile(request): return HttpResponse('profile page') -
Sorting using using href - Django
I am trying to sort the data by the column's header of a table. I am using the GET.get method but it seems that it doesn't work. The link is created but after i press it, the url changes but it the table is not sorted accordingly. def offer_sorting(request): sort_column = request.GET.get('sort_by', 'date') slist = Offer.objects.order_by(sort_column) context = {"offers": slist} return render(request, 'main/offer.html', context) the template: <!DOCTYPE html> <html> {% extends "main/header.html" %} {% block content %} <div class="row"> <div class="col-md"> <div> <h1> Offers </h1> <br> </div> <p align = "right"> <br> <a class="waves-effect waves-light btn-large" href = "submitoffer/">New Offer</a> </p> <div class="card card-body"> <table class="table"> <thead> <tr> <th><a href="{% url 'main:Offers' %}?sort_by=location_name">Location</a></th> <th>Date</th> <th>Minerals</th> <th>Chemical Analysis</th> <th>User</th> </tr> </thead> <tbody> {% for offer in offers %} <tr> <td>{{offer.location_name}}</td> <td>{{offer.date}}</td> <td>{{offer.minerals}}</td> <td>{{offer.chem_anal}}</td> <td>{{offer.user_data}}</td> <td> <a class="waves-effect waves-light btn" href = "{% url 'main:details' pk_test=offer.id %}" >Details</a> </td> <td> <a class="waves-effect waves-light btn" href = "{% url 'main:bid' pk_test=offer.id %}" >Bid</a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> {% endblock content %} </html> the model Offer includes the following fields which are going to be used for the sorting: minerals date location_name -
django filter one model with another model
I have two models and both have foreign keys with the User model. class UserCostCenter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) cost_center = models.PositiveIntegerField() created_date = models.DateTimeField(auto_now_add=True) start_date = models.DateField(null=False, blank=False) end_date = models.DateField(null=True, blank=True) class UserBooking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) date = models.DateField() hours = models.DecimalField() task = models.ForeignKey(UserProject, on_delete=models.DO_NOTHING, null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(null=True, blank=True) history = HistoricalRecords(table_name='booking_history_userbooking') Now I want to exclude the userbookings which does not have a cost center Currently I am doing like this: queryset = UserBooking.objects.all() for booking in queryset: cost_center = UserCostCenter.objects.filter( Q(user=booking.user, start_date__lte=booking.date, end_date__gte=booking.date) | Q(user=booking.user, start_date__lte=booking.date, end_date=None)).first() if not cost_center: booking_ids_without_cost_center.append(booking.id) queryset = queryset.exclude(id__in=booking_ids_without_cost_center) I do not want to exclude userbooking objects using for loop, please help! -
How to pass onclick variable from javascript to django form
I am a beginner and I really need your help for a function. You have a table and when you click on a cell, it opens a form in a pop-up modal to enter some text called "trigramme". Then you select the "time" (corresponding to the row) and the "position" (corresponding to the column) on the pop-up form, submit it and it will put the text into the correct cell on the table. This works correctly. Now, I would like to take the "time/position" variables directly from the cell clicked and pass these variables to the django form, so that you only have to enter the text in the form and submit it. I have a function to pick up the time and position after clicking a cell that works to display the cell clicked position (column header related to this cell) and time (row header related to this cell) : $('table').on('click', 'td:not(:first-child)', function(e) { var time = e.delegateTarget.tHead.rows[1].cells[this.cellIndex], position = this.parentNode.cells[0]; alert([$(position).text(), $(time).text()]); }) I also have this function to display the modal that works correctly : $(function () { var cells = document.querySelectorAll('td:not(:first-child)'); cells.forEach((e)=>{ e.addEventListener("click", ()=>{ $.ajax({ beforeSend: function () { $("#modal-activity").modal("show"); }, success: function (data) { $("#modal-activity.modal-content").html(data.html_form); … -
Django, multiprocessing and python logging
I have a django view with a method that calls multiprocessing.Process() and I'd like to configure logging to write logs to separate file for each subprocess. I've read some examples in the Python logging cookbook which focus on multiprocessing and writing logs to a single file, but I want to write to separate files. So I'm trying to create a new logging instance within the child process. I've set logging to None in django settings (because I think this is only called once in setup()) and then applied a logging config under the multiprocessed method, like so - def run_upgrade(self, input_data, status): logger = logging.getLogger("parent") logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # set the console handler ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) # set the filehandler fh = logging.FileHandler(f'/var/log/example/{status.device}.log') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) Within the modules that are imported, I've then called getLogger(parent.child) to get them to propagate back to the root logger. Is this the right approach? -
Extendend Django App System to a "module" system?
honestly, I am not totally sure if thats a suitable SO question but I thought I can most likely get insights or answers here from the community. We currently devlop a web application or rather an extensible framework on top of django (Version 3.1.5). We therefore also use reusable apps but we lack several features of "plain" django apps: Some require changes to the settings.py We want to share a certain level of configuration (we use django-constance for that) Each app may (or may not) bring other depdencies either as pip dependencies or other django apps that would need to be installed I know that django has a pretty opiniated approach and tries to strictly isolate what an app does and what is "site specific" and belongs to the settings.py. In our scenario, however, both models don't perfectly fit as we want to have several deployments of a subset of our apps which we want to manage automatically and so, we dont want to manually maintan a large set of settings.py files that also are very similar and share lots of code (which is against Django very natural DRY). Finally, we came up with the idea of "modules" which are … -
Django: Adding more code or a new database table
I don't know if anyone has been in this situation before. I'm have a table named doctors, every doctor will have an attribute called universities where I will store the universities where the doctor studied. Anyway, should I add new table where I put the universities and link it to the doctors or should I store the universities in a text attributes in the doctors table and add some python code to analyse it when needed. Thanks in advance. -
How to check each key separately from a list in a loop without creating multiple loops. Which may have a KeyError etc
I wrote a code that takes 5 keys from API. The authors, isbn_one, isbn_two, thumbinail, page_count fields may not always be retrievable, and if any of them are missing, I would like it to be None. Unfortunately, if, or even nested, doesn't work. Because that leads to a lot of loops. I also tried try and except KeyError etc. because each key has a different error and it is not known which to assign none to. Here is an example of logic when a photo is missing: th = result['volumeInfo'].get('imageLinks') if th is not None: book_exists_thumbinail = { 'thumbinail': result['volumeInfo']['imageLinks']['thumbnail'] } dnew = {**book_data, **book_exists_thumbinail} book_import.append(dnew) else: book_exists_thumbinail_n = { 'thumbinail': None } dnew_none = {**book_data, **book_exists_thumbinail_n} book_import.append(dnew_none) When I use logic, you know when one condition is met, e.g. for thumbinail, the rest is not even checked. When I use try and except, it's similar. There's also an ISBN in the keys, but there's a list in the dictionary over there, and I need to use something like this: isbn_zer = result['volumeInfo']['industryIdentifiers'] dic = collections.defaultdict(list) for d in isbn_zer: for k, v in d.items(): dic[k].append(v) Output data: [{'type': 'ISBN_10', 'identifier': '8320717507'}, {'type': 'ISBN_13', 'identifier': '9788320717501'}] I don't know what … -
How to specify the SearchVector content manually in Django for Postgres?
Django supports the Postgres full-text-search using a SearchVectorField. The data has to be prepared using to_tsvector on the Postgres side which is done by the SearchVector function in Django: class SomeSearchableModel(PostgresModel): searchable = SearchVectorField() I need to populate this column with data not stored in other columns of the table. The default way to go would be: class SomeSearchableModel(PostgresModel): text = TextField() searchable = SearchVectorField() On every save: obj.searchable=SearchVector('text') # Column name to be read This application doesn't hold the searchable data in a usable format within the database. The content is prepared within some backend script. How do I provide the SearchVectorField content manually? Like: obj.searchable=SearchVector(some_processed_text) The PostgreSQL query part would be: INSERT INTO ... SET searchable=to_tsvector(...). Calculating the content in Postgres is no option. -
how to pass a data in a django view to other views without globall
so I am using a payment that has a view called verify , and It is going to check if the result was Ok , do something . But I need to pass order_id in the previous view that is token from the url to this view . some suggestion was using the global . but I am afraid of a error in the real server . If you need . Its the code : Previous view that sends a request to the payment center : def send_request(request , order_id): i = order_id amount = get_object_or_404(Order , id = i , user_id = request.user.id) result = client.service.PaymentRequest(MERCHANT , amount.total , description , email , mobile , CallbackURL) if result.Status == 100 : return redirect('https://www.zarinpal.com/pg/StarPay' + str(result.Authority)) else : return HttpResponse('error code : ' , str(result.Status)) And I need the order_id in the next view SO what can i do??Help please! -
my model field is not accepting "+" symbol into data. Using CharField field for model
models.py class Profile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,null=True) mobile = models.CharField(max_length=14,null=True) add = models.CharField(max_length=10,null=True) image = models.FileField(null=True) def __str__(self): return self.user.username when i give mobile = +12345 its showing in admin as mobile = 12345 after i edit and save its showing +12345 why? and which field to use for including + symbol -
Querying users based on time
I want to add a class-based view to return users created from one date to another date. I have tried the following are there other ways to filter the user-created between two dates? views.py class RegisteredUserFilter(APIView): serializer = RegisteredUserFilterSerializer def get(self, from_date, to_date): userondate = User.objects.filter(created_at__range=[from_date, to_date]) return Response({"User": userondate}) serializers.py class RegisteredUserFilterSerializer(serializers.Serializer): from_date = serializers.DateField() to_date = serializers.DateField() model = User full code at: https://github.com/abinashkarki/rest_framework_authentication/tree/master/authapp -
Django Docker Celery - Cannot assign requested address Is the server running on host
I am trying to run celery within a docker with django and postgres. My .env.dev is as follows DB_HOST=localhost DB_NAME=app DB_USER=postgres DB_PASS=supersecretpassword DB_ENGINE=django.db.backends.postgresql DB_PORT=6543 POSTGRES_DB=app POSTGRES_USER=postgres POSTGRES_PASSWORD=supersecretpassword POSTGRES_PORT=6543 My settings.py is as follows DATABASES = { 'default': { 'ENGINE': os.environ.get('DB_ENGINE'), 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), 'PORT': os.environ.get('DB_PORT'), } } My docker-compose is as follows version: "3.9" services: web: container_name: website build: ./backend command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/app/ ports: - "8000:8000" env_file: - ./.env.dev depends_on: - db - redis db: container_name: database image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.dev environment: - POSTGRES_HOST_AUTH_METHOD=trust ports: - "6543:5432" redis: image: redis:6-alpine celery: build: context: ./backend command: celery worker server --loglevel=info --logfile=logs/celery.log volumes: - ./backend/:/usr/src/app/ env_file: - ./.env.dev depends_on: - db - redis - web volumes: postgres_data: The error message I get is /usr/local/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py:105: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 6543? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 6543? -
"Module not found" while trying to debug with VSC a remote deployed containerized Django app
I have a django app inside a container that is deployed in a remote server. I have successfully set up VSC in order to debug my app. I have started debugging my django app but I get the error ModuleNotFound while debugging. Obviously, since the django app is deployed and working perfectly, all requirements modules do exists. Despite that, I get this error. Any ideas? -
getting input value on button click in django
i'm trying to get the input value on button click if request.method == 'POST': if request.POST['fah']: this is getting me False when page is loaded and if i click on button, it's not changing how can i write something like js addEventListener in django? my button <button type="button" class="bbtn" name="fah" id="fah" value="fah">Convert</button> -
Postman Django CSRF error when requesting obtain_auth_token route
Basically the same as this post which didn't get an answer, when I try to access the token route of the rest_framework using Postman, I get a 403 that says "CSRF cookie not set." I don't understand why I would need a token to request the route which is supposed to give me an authentication token, but most of all, I don't know how to get around this issue ! -
Django rest framework Login Authentication Problem
I'm using django rest framework for login. I tried this on postman app but it keep showing me something went wrong. help me out with this. Thanks in advance. Here is the code for views_api.py: from rest_framework.views import APIView from rest_framework.response import Response from django.contrib.auth.models import User from django.contrib.auth import authenticate , login class LoginView(APIView): def post(self , request): response = {} response['status'] = 500 response['message'] = 'Something went wrong' try: data = request.data if data.get('username') is None: response['message'] = 'key username not found' raise Exception('key username not found') if data.get('password') is None: response['message'] = 'key password not found' raise Exception('key password not found') check_user = User.objects.get.filter(username = data.get('username')).first() if check_user is None: response['message'] = 'invaild username, user not found' raise Exception('invaild username not found') user_obj = authenticate(username = data.get('username'), password = data.get('password')) if user_obj: response['status'] = 200 response['message'] = 'Welcome' else: response['message'] = 'invaild password' raise Exception('invaild password') except Exception as e: print(e) return Response(response) LoginView = LoginView.as_view() -
How to make ModelForm avoid form validation for instances coming in for update?
models.py class Receivables(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) pattern = RegexValidator(r'(RT|rt|rT|Rt)\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') rt_number=models.CharField(max_length=15, validators=[pattern]) discount=models.DecimalField(max_digits=9, decimal_places=2, default=0) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=0) approval_date=models.DateField(default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) expected_value=models.DecimalField(max_digits=10, decimal_places=2, blank=True) forms.py class ReceivablesForm(ModelForm): class Meta: model=Receivables fields='__all__' widgets={ "base_value":forms.NumberInput(attrs={"disabled":"on"}), "expected_value":forms.NumberInput(attrs={"disabled":"on"}), 'approval_date': DateInput(attrs={'type': 'date'}), } def clean(self): cleaned_data=super().clean() pt=self.cleaned_data['patient'] print('clean - receivables - instance: ', self.instance) if self.instance == None: if Discharge.objects.filter(patient=pt): dis1=Discharge.objects.filter(patient=pt) print('receivable form - dis1 value: ', dis1) try: pkg1=Package.objects.filter(patient=pt) dis2=dis1.order_by('-id').first() pkg2=pkg1.filter(date_of_admission__gt=dis2.date_of_discharge) if not pkg2: raise ValidationError('There is no Package value for this entry - 1!') except Package.DoesNotExist: raise ValidationError('No history of Package instance!') else: try: Package.objects.get(patient=pt) print(Package.objects.get(patient=pt)) except Package.DoesNotExist: raise ValidationError('There is no Package value for this entry - 2!') What this does is that it checks whether the data in the model prior to this model is already saved or not. If not saved already, it throws a validation error asking the user to fill in the previous form first. views.py def receivables_view(request): if request.method=='POST': fm_receivables=ReceivablesForm(request.POST) if fm_receivables.is_valid(): receivables=fm_receivables.save() ipd=IpdReport.objects.create(patient=receivables.patient, package=Package.objects.filter(patient=receivables.patient).order_by('-id').first(), receivables=receivables) print('Receivables ke views ka ipd value: ', ipd) OngoingReport.objects.create(ipdreport=ipd) fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) else: fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) Receivables update view def update_receivables_view(request, id): if request.method=='POST': print(request.POST) rec=Receivables.objects.get(pk=id) print(rec) form=ReceivablesForm(request.POST, instance=rec) print(form) if form.is_valid(): … -
How to register user using your own Model Django
I am having trouble registering a user as a PetOwner. I'm not sure what I am suppose to code in my signup view. I can signup a user and that user does not have admin or staff status which is great because they should not have these privileges. Problem is that I do not just want them to be a user but I want them to be a PetOwner. Currently, they are only a User not a PetOwner. What am I doing wrong here or what do I have to add. in models.py from django.db import models from django.urls import reverse from django.contrib.auth.models import User class PetOwner(models.Model): """Model representing a pet owner.""" user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=50, help_text="Enter owner's first name") last_name = models.CharField(max_length=50, help_text="Enter owner's last name") email = models.EmailField( max_length=50, blank=True, unique=True, help_text="Enter owner's email" ) phone_number = models.CharField( max_length=15, blank=True, unique=True, help_text="Enter owner's phone number" ) address = models.ForeignKey( "Address", on_delete=models.SET_NULL, null=True, blank=True ) class Meta: """Controls default ordering of records when querying the Model type.""" ordering = ["first_name", "last_name"] def __str__(self): """String for representing the Model object.""" return self.first_name def get_absolute_url(self): """Returns the url to access a detail record of this pet owner.""" return … -
How to add data to the model whose column are referenced(Foreign Field) from other model in Django
I am trying to add data to my Cart Model but getting the error as In the field in which I am trying to enter the data is the ForeignField whose reference is Items. Cannot assign "9": "Cart.pid" must be a "items" instance. Here is my code:- Views.py def add_cart(request): pid = request.POST.get('cart_id') quantity = request.POST.get('quantity') details = items.objects.filter(pk = request.POST.get('cart_id')) name = None price = None for i in details: name = i.name price = i.price pid = i.id user_id = request.user.id total = int(quantity)*price instance = Cart(pid = pid,quantity = quantity,pro_name = name,pro_price = price,user_id = user_id,total = total) return redirect('home') Models.py class items(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100,default='Item') desc = models.TextField(max_length=500, default='Best') price = models.IntegerField() category = models.CharField(max_length=50,default='Product') image = models.ImageField(upload_to="media",default='Item Image') class Cart(models.Model): pid = models.ForeignKey('items',on_delete=CASCADE,related_name="proid") name = models.ForeignKey('items',on_delete=CASCADE,related_name="proname") price = models.ForeignKey('items',on_delete=CASCADE,related_name="proprice") quantity = models.IntegerField(default=1) user_id = models.ForeignKey(User,on_delete=CASCADE) total = models.IntegerField(default=0) Please help!!! -
Django: ModuleNotFoundError: No module named 'psycopg2' on Mac
I have installed psycopg2-binary 2.9.1(pip install psycopg2-binary) in virtualenv, but when I execute python manage.py migrate, that appears "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'", and python console also can't import psycopg2. how to fix the problem?