Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Historical model does not allow deletion in reverting django data migration
I'v two models class A(models.Model): index = models.SmallIntegerField(primary_key=True) audio = models.FileField(null=True, blank=True) x = models.SmallIntegerField() y = models.SmallIntegerField(null=True, blank=True) and class B(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) index = models.SmallIntegerField() audio = models.FileField(null=True, blank=True) image = models.FileField(null=True, blank=True) I made a data migration that initializes model A objects (every object also creates B objects with it and every created B also creates C objects with it.) Here is the migration: from django.db import migrations def create_as(apps, schema_editor): A = apps.get_model('super_app', 'A') B = apps.get_model('super_app', 'B') C = apps.get_model('super_app', 'C') # C has FK referencing B # Some logic here that creates instances of A (also creates B and C) def delete_as(apps, schema_editor): A = apps.get_model('super_app', 'A') A.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('super_app', '00xx_the_very_previous_migration'), ] operations = [ migrations.RunPython(create_as, delete_as) ] The migrations is applied forward successfully.. but when I try to revert back the migration (Which should call delete_as) I'm always having this error: ValueError: Cannot query "B object (757)": Must be "B" instance. I've been trying and digging but no clue why this happens! Note: The type of models in migrations are historical models (__fake__.{MODEL}) I tried to use the latest state of the model by doing: def delete_as(apps, … -
Unable to activate virtual environment
Virtualenv is installed and created using virtualenv venv command. However I am in same directory and can't activate it. Tried below commands venv/Scripts/activate . venv/Scripts/activate .venv\Scripts\activate Please refer attached screenshot -
The localhost address in front of the django image url
When i get an image, some models put "http://localhost:8000" at the beginning and some models don't. I want to unify it in one way, but how can I express it without attaching "http://localhost:8000"? -
Django: How to filter model property in views
Please how can I filter a queryset in views using model @property method. class TransactionData(models.Model): Nozzle_address = models.CharField(max_length=255) Device = models.ForeignKey(Devices, on_delete=models.CASCADE) Site = models.ForeignKey(Sites, on_delete=models.CASCADE, enter code hererelated_name='transaction_data') Pump_mac_address = models.CharField(max_length=255) @property def product_name(self): try: return f'{(Nozzle.objects.filter(Pump__Device__Device_unique_address=self.Pump_mac_address,Nozzle_address=self.Nozzle_address)).Product.Name}' except : pass Basically I want to be able to write a query in views like this: filtered_product = models.TransactionData.objects.filter(Site=Site_id, product_name='kero') But django does not support this. I think I will need to write a custom manager where I can then query like this filtered_product = models.TransactionData.objects.filter(Site=Site_id).product_name('Key') The problem is that in the property method product_name am making use of Another model like Nozzle Please how can i get this done... I know I would need to use either custom manager or queryset to get this work but can't just figure it out.. I really appreciate your help. Thanks -
File not found while trying to deploy Django on heroku
I am trying to deploy Django on a heroku server. I am using this particular blog as a step by step guide: https://www.analyticsvidhya.com/blog/2020/10/step-by-step-guide-for-deploying-a-django-application-using-heroku-for-free/ On step 20, I ran the command and faced the issue that secret_key file is not found. There is no error while running it locally. Structure of the project: --BankingSystem--bankingsystem(Base project)--settings.py --user(App) --base(App) --manage.py --secret_key.txt --ProcFile ERROR with open("./secret_key.txt") as f: remote: FileNotFoundError: [Errno 2] No such file or directory: './secret_key.txt' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 -
Arranging JSON Data in excel file in Django
I am exporting data from database using this function: def export_packing_xls(request): response = HttpResponse(content_type='application/ms-excel') file_name = "packing_list_"+str(datetime.now().date())+".xls" response['Content-Disposition'] = 'attachment; filename="'+ file_name +'"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Packing List') date1 = request.GET.get('exportStartDate') date2 = request.GET.get('exportEndDate') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Ref Number', 'Description of Goods','QTY','Gross WT',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = Booking.objects.filter(created_at__range =[date1, date2]).values_list('booking_reference', 'product_list', 'gross_weight',) for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) print(row[col_num][1][:4]) wb.save(response) return response I am getting this kind of : Ref Number Description of Goods QTY Gross WT AWBO114 [{"id":1,"Name":"T shirt","Quantity":"10","Weight":"2","WeightTypes":"KG","TotalWeight":"20","CustomsCharge":"20.0","Discount":"12","Subtotal":"188"}] 12 22 AWBO117 [{"id":1,"Name":"T shirt","Quantity":"15","Weight":"45","WeightTypes":"KG","TotalWeight":"675","CustomsCharge":"20.0","Discount":"45","Subtotal":"255"}] 45 455 AWBO118 [{"id":1,"Name":"Fan","Quantity":"12","Weight":"12","WeightTypes":"KG","TotalWeight":"144","CustomsCharge":"100.0","Discount":"12"},{"id":2,"Name":"T shirt","Quantity":"22","Weight":"5","WeightTypes":"KG","TotalWeight":"110","CustomsCharge":"20.0","Discount":""}] 15 15 AWBO121 [{"id":1,"Name":"T shirt","Quantity":"12","Weight":"12","WeightTypes":"KG","TotalWeight":"144","CustomsCharge":"20.0","Discount":"12","Subtotal":"228"}] 0 20 AWBO122 [{"id":1,"Name":"T shirt","Quantity":"12","Weight":"12","WeightTypes":"KG","TotalWeight":"144","CustomsCharge":"20.0","Discount":"12","Subtotal":"228"}] 12 12 But i want to make a list for "Description of Goods" As like this : How can i list out my JSON data in the Excel file? If you have anything to know, please let me know in the comment section. Thank you. -
Assigning user to multiple groups in JIRA
I have a question regarding adding user to groups in Jira using rest api. So, I wrote this code in python and it works just fine. However, if I would like to add this one user to multiple groups, what is the right syntax. I tried a lot of syntax and none of them worked and I also searched online and found none. Would appreciate it if someone helped me. Thank you headers = {'Content-Type': 'application/json',} query = {'groupname': 'groupname'} data = '{"name": "name"}' response = requests.post('url', headers=headers, params=query, data=data, verify=False, auth=(username, password)) -
Why is the result of the multiplication not seen from the template with javascript but when inspecting the element in chrome dev tools it is?
i'm combining with my django project some javascript to do the calculations of a system. However, it seems strange to me that something as simple as the result of a multiplication is not reflected in the template of my web page but in the chrome dev tools I attach some images, in the first the total of the multiplication is not reflected, in the second the result of the multiplication is seen but with the chrome dev tools here you do not see the result of the multiplication here you see the result of the multiplication Parte/models.py class Parte(models.Model): codigo=models.IntegerField() quantity=models.IntegerField() unit_price=models.IntegerField() total_price=models.IntegerField() tax_free=models.BooleanField() descripcion=models.TextField(max_length=255,blank=True, null=True) descuento=models.IntegerField(default=0) total=models.IntegerField(default=0) # estatus = models.BooleanField() # def __str__(self): # return f'{self.codigo}: {self.estatus} {self.descripcion}' def __str__(self): return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_price} {self.tax_free}{self.descuento}{self.total}' Parte/forms.py class ParteForm(forms.ModelForm): class Meta: model=Parte fields=['codigo','descripcion','quantity','unit_price','total_price','tax_free'] Presupuestos/models.py class Presupuestos(models.Model): parte=models.ForeignKey(Parte, on_delete=models.SET_NULL, null=True) def __str__(self): return f'{self.parte}' calculos.js function multiplicar(){ var x=parseInt(document.getElementById('id_quantity').value); var y=parseInt(document.getElementById('id_unit_price').value); document.getElementById('id_total_price').innerHTML=x*y; } <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_price}} </td> <td> <div class="form-check"> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="addrow" onclick="childrenRow()" value="+" /> </td> <td> <button type="button" onclick="multiplicar();">Button</button> </td> -
save model with foreign key in django
I have models for eg like this. class Mp3(models.Model): title=models.CharField(max_length=30) artist=models.ForeignKey('Artist') and Here is how the Artist models looks like: -
Django Dynamic Fields Within A Form
A requirement for my app is to give user's capability to create a survey. For each survey, the user should have the capability to add any number of questions. I am trying to achieve this by first defining my models and a form. # models.py. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) def __str__(self): return self.question_text class Survey(models.Model): survey_name = models.CharField(max_length=200) questions = models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return self.survey_name #forms.py from django import forms class Survey(forms.Form): survey_name = forms.CharField(required=200) #TODO: define questions I am stuck. In my form module, how do I define the one to many relationship between the survey and questions in order for the user to add and define questions for each survey they create. -
Current I am learning django but every time try to creat simple web page on local sever I get error ! What should I do?
enter image description here enter image description here enter image description here enter image description here enter image description here -
Trying to edit a ms word document using django
I want to read data from a ms excel file and edit an existing words document using the data from excel to fill in bookmarks. So far I have been able to read to data successfully but I'm struggling with the editing part. I'm using python-docx for this. It would be great if someone can help. my code: from django.shortcuts import render from django.http import HttpResponse import openpyxl import docx from docx import Document def index(request): if "GET" == request.method: return render(request, 'letters/index.html', {}) else: excel_file = request.FILES["excel_file"] # you may put validations here to check extension or file size wb = openpyxl.load_workbook(excel_file) # getting a particular sheet by name out of many sheets worksheet = wb.sheetnames if 'sheet name' in wb.sheetnames: sheet = wb['sheet name'] print(worksheet) excel_data = list() # iterating over the rows and # getting value from each cell in row for name in wb.sheetnames: sheet = wb[name] first = False for row in sheet.iter_rows(): row_data = list() for cell in row: row_data.append(str(cell.value)) print (row_data) if first == False: pass else: document = Document("media/template.docx") doc = docx.Document() for x in range (5): def addParagraphAfterParagraph(self, document, paragraph, bookmark ): for para in document.paragraphs: if para.text == bookmark: p … -
Is there a way to make a form dynamic in django
I'm trying to make a dynamic dropdown list in the Admin Panel. It should show all the fields from a certain model. Here is the snippet of my code: JS_FUNCTION = """ obj = document.getElementById('id_field_name'); for (let i = 0, len = test.length; i < len; i++) { var opt = document.createElement('option'); opt.value = test[i]; opt.innerHTML = test[i]; obj.appendChild(opt); } """ def set_queryset(value): # model = SyncModel.objects.get(id=value) # return model.get_fields() return ["a", "b", "c", "d"] class WhitelistForm(forms.ModelForm): sync_model = forms.ModelChoiceField( queryset=SyncModel.objects.all(), widget=forms.Select( attrs={ "onchange": f'console.log(value); var test = {set_queryset("value")}; {JS_FUNCTION}', "required": True, } ), ) field_name = forms.ChoiceField( choices=(), ) class Meta: model = WhitelistModel fields = "__all__" The problem is, I need to return the fields from the model. However, when I pass the 'value' as a parameter for the python function, it doesn't send the id the is printed on the console.log. Console Log output: I'd like to know if there is a way to make the model dynamic only on the form file. -
(DJANGO) How to get user input and redirect the user to another page
This is part of the CS50W courseware project 1. A search input will be provided by the user, user input will be passed through the search function and redirected to respective views. However, the view.search function is not being called after input is provided. layout.html <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form class='search' action="{% url 'search' %}" method="get"> <input type="search" name="search_query" placeholder="Search Encyclopedia"> </form> <div> <a href="{% url 'index' %}">Home</a> </div> <div> Create New Page </div> <div> Random Page </div> {% block nav %} {% endblock %} </div> <div class="main col-lg-10 col-md-9"> {% block body %} {% endblock %} </div> </div> </body> </html> views.py def search(request): search_query = request.GET.get['search_query'] if search_query in util.list_entries(): return redirect('view.entry_page') else: return redirect('view.index) urls.py urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entry_page, name="entry_page"), path("error_404", views.error_404_view, name="error_404"), path("search", views.search, name="search") ] -
How can you use Create() and Update() in the same Django HTML page?
I am trying to create a page where I can create a new entry/note to a list and also update an existing list on one HTML page. The problem is create() does not require a primary key. However, update() requires existing primary key. How can do I do this in django? Do I create a new function in views.py? Example: def new_note(request, note_id=None): if note_id == None: notes(request) #function that just uses create() else: note_sad(request, note_id) #sad=save and delete using update() and delete() views.py sample function for entering notes: def notes(request): if request.method == 'GET': notes = Note.objects.all().order_by('note_id') form = NoteForm() return render(request=request, template_name='notes.html', context={ 'notes': notes, 'form': form }) # when user submits form if request.method == 'POST': form = NoteForm(request.POST) if form.is_valid(): note = form.cleaned_data['note'] Note.objects.create(note=note) # "redirect" to the todo homepage return HttpResponseRedirect(reverse('new_note')) views.py function for creating a new entry/note: def note_sad(request, note_id): if request.method == 'GET': note = Note.objects.get(pk=note_id) form = NoteForm(initial={'note_text': note.note_text}) return render(request=request, template_name='notes.html', context={ 'form': form, 'note_id': note_id }) if request.method == 'POST': if 'save' in request.POST: form = NoteForm(request.POST) if form.is_valid(): note = form.cleaned_data['note'] Note.objects.filter(pk=note_id).update(note_text=note) elif 'delete' in request.POST: Note.objects.filter(pk=note_id).delete() return HttpResponseRedirect(reverse('new_note')) -
Django query aggregation into list of dicts
I'm using Django and Postgres and I have the current setup (mockup): Class A: name=models.CharField() b=models.ForeignKey(to=B) Class B: c=ForeignKey(to=C) amount=models.IntegerField() I need to create a query that, starting from A returns all the values in B as a list of dictionaries. I tried JSONBAgg and ArrayAgg but had no luck while trying to save multiple fields. Example query: from django.contrib.postgres.aggregates.general import JSONBAgg A.objects.annotate(test=JSONBAgg('amount')).values('name', 'test') WORKS! A.objects.annotate(test=JSONBAgg('amount', 'c__id')).values('name', 'test') DOES NOT WORK! How do I get a list of dicts with multiple values instead of a list of strings? -
how to query foreignkey in django with if conditions and do something if a condition is met
i'm working a website where i want to display product that are of two categories which are premium and free package and i want to filter all the premium package and label it with a star or a premium text to indicate it a premium package and for the free i'll do nothing but i don't really know if i should user foreign key for this or tuple, i'm a django beginner and would really appreciate any help from you all. Thanks in advance models.py STATUS_CHOICE = ( ('draft', 'Draft'), ('in_review', 'In Review'), ('published', 'Published') ) class Package_Category(models.Model): title = models.CharField(max_length=10000, verbose_name="Title") slug = models.SlugField(max_length=1000, unique=True) def get_absolute_url(self): return reverse("package-categories", args=[self.slug]) def __str__(self): return self.title class Meta: verbose_name = "Package Category" verbose_name_plural = "Package Categories" class Vectors(models.Model): title = models.CharField(max_length=10000, null=True, blank=True, verbose_name="Title") slug = models.SlugField(unique=True) image = models.ImageField(upload_to="vectors-images/%Y/%m/%d/", default="default.jpg", verbose_name="Image Cover") vec_file = models.FileField(upload_to='vector-uploads/%Y/%m/%d/', null=True, blank=True, verbose_name="Upload File") category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category") package_category = models.ForeignKey(Package_Category, on_delete=models.CASCADE, verbose_name="Package Category") tags = models.ForeignKey(Tag, on_delete=models.CASCADE, verbose_name="Tag") status = models.CharField(choices=STATUS_CHOICE, default="published", max_length=150, verbose_name='Status') creator = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Creator") creator_image = models.ImageField(upload_to="creators-images/%Y/%m/%d/", default="default.jpg", verbose_name="Creator Image") created = models.DateTimeField(verbose_name="Created") class Meta: verbose_name = "Vector" verbose_name_plural = "Vectors" def get_absolute_url(self): return reverse("vector-details", args=[self.slug]) def __str__(self): … -
How to test Django model fields
I want to do unit tests for Django model fields: class Animal(models.Model): name = models.CharField(unique=True, max_length=30, blank=False, null=False) class Meta: managed = True db_table = 'animal' ordering = ['name'] My Test setUp looks like this: class TestAnimalModel(TestCase): def setUp(self): self.animal = Animal.objects.create(name = 'TestAnimal') self.animal2 = Animal.objects.create(name = 123) self.animal3 = Animal.objects.create(name = 'TestAnimalWithTooManyCharacters') animal2 and animal3 are created even though they shouldn't because animal2.name is int and animal3.name has more than 30 characters. How then do I test if name field has proper values? Is it normal that the object is created even though it has values that doesn't match Model? -
HTML Checkboxes uncheck after submit button
I wrote a password manager with length and checkboxes for symbols like chars/digits and special characters like !$& Everytime I hit the submit button to generate the password the unchecked boxes are checked again (because my default is that they should be checked), but how can I make that the box is like it was before submitting the form. I tried it with an if statment in the template because I'm using django but that doesnt help. If someone has an idea how I can achieve my solution please let me know. Thanks for your help Heres my code: def view_passwordgenerator(request): alphabets_b = bool(request.GET.get('alphabets')) digits_b = bool(request.GET.get('digits')) special_characters_b = bool(request.GET.get('special_characters')) alphabets = string.ascii_letters*alphabets_b digits = string.digits*digits_b special_characters = "!@#$%^&*()"*special_characters_b characters = alphabets + digits + special_characters if 'length' in request.GET: length = int(request.GET.get('length')) password = '' for i in range(length): password+=random.choice(characters) pyperclip.copy(password) pyperclip.paste() messages.info(request, 'The password was copied to your clipboard') username = request.user.username context = {'password': password, 'length': length, 'username': username} return render(request, 'home/passwordgenerator.html', context) username = request.user.username hs = {'username': username} return render(request, 'home/passwordgenerator.html', hs) and my template: <form method="get" action="{% url 'home:passwordgenerator' %}"> <div class="fake_input"> <p class="fake_input_text">{{ password }}</p> </div> <span class="fake_input_l">Length:</span> <select class="fake_input_drop" name="length"> <option value="8" … -
Django django-fontawesome-5
I've download django-fontawesome-5 in my django project, and followed the direction of the document https://pypi.org/project/django-fontawesome-5/. header <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %} CMFitness {% endblock title %}</title> {% load static %} {% load bootstrap4 %} {% load fontawesome_5 %} {% bootstrap_css %} {% fontawesome_5_static %} </head> navbar.html {% load static %} {% load fontawesome_5 %} <nav class=" d-flex flex-row p-3 align-items-center border-bottom"> <button style="width: 3%; border: solid 1px black;" class="btn" onclick='openNav()'> {% fa5_icon 'bars' %} </button> <!-- <span class="fas fa-bars" onclick="openNav()"></span> --> <div class=" px-2 mx-auto"> </div> </nav> Why wont my font awesome show up? -
Django signals (Clarification of doubts)
I'm new to Django and watching a series of tutorial videos where we did a project ... In the series they talk about 'signals'. What is proposed to do is connect some signals at the time of making a user registration on the page views.py from django.shortcuts import render, redirect from .models import * from .forms import OrderForm, CustomerForm, CreateUserForm from django.contrib import messages from django.contrib.auth.models import Group from django.contrib.auth.decorators import login_required from .decorators import unauthenticated_user, allowed_users, admin_only @unauthenticated_user def registerPage(request): form_value = CreateUserForm if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): user = form_value.save() username = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(username)) return redirect('login') else: messages.warning(request, 'Data is invalid, please try again') context = {'form_key':form_value} return render(request, 'accounts/register.html', context) signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User, Group from .models import Customer def customer_profile(sender, instance, created, **kwagrs): if created: group = Group.objects.get(name='customer') instance.groups.add(group) Customer.objects.create( user = instance, name = instance.username ) print('Profile created.!') post_save.connect(customer_profile, sender= User) apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'accounts' def ready(self): import accounts.signals settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'django_filters', ] This are my questions: 1) What is the job of … -
Django Admin format_html_join cannot seperate with new line <br>
format_html_join( '<br>', '<br><a href="{}">{}</a>', ( (reverse("admin:research_webproductpage_change", args=[wpp.id]), wpp.title[:30]) for wpp in webproductpages ) ) Above I am trying to add many to many links to my django admin list display which I did succesfully. But <br> or "\n" not working as seperators, although <br> is working in the second parameter. If I put <br> in the first parameter it appears in double quote not as an html. Or If I put "\n" it does not appear at all. I want to put links row by row because o it looks better then. What is wrong with my code? -
how to for loop from a number to number in django
i try to do this {% for post in posts %} {% if forloop.counter 15>=30 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% endfor %} and its give me a err the photo here **What I'm trying to do is make the repetition start at 15 and end or = at 30 ** I searched a lot and couldn't find what I wanted So please help me lan = python django -
How to write a text or binary file to a Django response?
I am trying to hook up Django and React. See here or here. This is serving up some Django URLs, but then passing the rest on to React. I want to serve up not only React's index.html, but also any of its files from the "public" directory. There is HTML, JSON, could be images or icon files, etc. A mix of text files and binary files. Here is some code to serve up a binary file (like an image) with FileResponse: from django.http import FileResponse def view_func(request): # .. find a static file to serve content = open(some_file_path, 'rb') return FileResponse(content) Note that it opens content as a binary file (rb). But if I am serving index.html, presumably that is not binary. For example, it might be UTF-8. (I think that's the default if I open with r, no binary.) Is there an easy way to serve up a file in Django whether it is text or binary? P.S. I feel like there should be a way to hook up Django's static file serving, but after a few hours of fiddling, it is harder than it looks. This is not going to get super-high traffic, so I'm fine with this. -
hi can help me in this issu wth database whith django
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' how can resolv this issue .im alrady install psycopg2 in my vertualenv