Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Checking if the .csv file is formatted correctly before importing to avoid embedding wrong data into database
I am working on a django project that requires updating database with bulk data provided in an excelsheet format. So basically, a user can upload a .csv file if it is in a correct format. I know how to import a file using django-import-export, but the problem is , i don't know how to perform checks like checking if the .csv file has correct column names and information before updating database. I am new to django, please help. -
Django model formset is not saving data to backend db
I am trying to save data using modelformset_factory but i am unavle to do so, i am wondering why? Here is my views.py views.py if request.POST: try: user_info = Education.objects.filter(applicantt= applicant_info).first() formset = educationformset(request.POST, instance=user_info) if formset.is_valid(): print(formset.cleaned_data) for form in formset: obj = form.save(commit=False) obj.id = user_info obj.applicantt = applicant_info obj.save() return redirect('test') else: context['education_form'] = formset except: formset = educationformset(request.POST) if formset.is_valid(): for form in formset: obj = form.save(commit=False) obj.applicantt = applicant_info obj.save() return redirect('test') else: context['education_form'] = formset This the template i am using.... template <form method="POST" class="">{% csrf_token %} {{ education_form.management_form}} {% for form in education_form %} <table class="table table-bordered" cellspacing="0" > <thead id="head"> <tr> {% for field in form.visible_fields %} <th >{{field.label}}</th> {% endfor %} </tr> </thead> <tbody id="head"> <tr > {% for field in form.visible_fields %} <th>{{field}}</th> {% if error in field.errors %} <small id="" class="text-danger"> {{error}} </small> {% endif %} {% endfor %} </tr> </tbody> </table> {% endfor %} <div class="card-block"> <button type="submit" class="btn btn-success center-block pull-right" href="{% url 'test' %}">Finish</button> </div> </form> and finally this is my model.py which i am using for the project.... models.py class Education(models.Model): LEVEL = [ ('Matric','Matric'), ('Intermediate','Intermediate'), ('Graduation','Graduation'), ('Master','Master'), ('Doctrate','Doctrate'), ] applicantt = models.ForeignKey(Personal, on_delete=models.CASCADE, unique=False) … -
How to add data to different table using signals?
In my invoicing app, when client make payment, i create new clientpayment with date and client name and amount paid, and in clientpaymentitem i choose one or many invoices that client paid and put the amount_paid on each line and where the money is stored, in bank or cashier. i can receive cash and check for example and then i select treasury.cashier for invoice paid on cash and the other paid with check same way treasury.bank. now i want when i save the clientpayment that this transaction will be saved on treasury on same time, no need to repeate the whole things. I tried to use signals but didn't work correctly for me in case i modify the amount for ex. class ClientPayment(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) total_paid = models.DecimalField(default=0, max_digits=20, blank=True, null=True, decimal_places=2) class ClientPaymentItem(models.Model): clientpayment = models.ForeignKey('ClientPayment', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.PROTECT) amount_paid = models.DecimalField(max_digits=20, decimal_places=2) treasury = models.ForeignKey('Treasury', on_delete=models.PROTECT) class Treasury(models.Model): name = models.CharField(max_length=256) class TreasuryItem(models.Model): treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) name = models.CharField(max_length=256) debit = models.DecimalField(max_digits=20, decimal_places=2, default=0) credit = models.DecimalField(max_digits=20, decimal_places=2, default=0) -
Django: TypeError: post() missing 1 required positional argument: 'request'
I am getting below error when I pass the invalid credentials. TypeError: post() missing 1 required positional argument: 'request' I don't understand it. Here is the view. View: class LogInView(TemplateView): template_name = "login.html" @staticmethod def post(self, request, *args, **kwargs): username_or_email = request.POST['username'] password = request.POST['password'] if '@' in username_or_email: username = User.objects.get(email=username_or_email).username else: username = username_or_email if username and password: user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/admin') else: messages.warning(request, 'Sorry, wrong username or password.') return render(request, self.template_name) else: messages.warning(request, 'Username and Password cannot be blank.') return render(request, self.template_name) Here is the url. Url: from django.urls import path, include from sa.views import ( LandingPageView, LogInView, LogOutView, ) urlpatterns = [ path('', LandingPageView.as_view(), name='LandingPageView'), path('login', LogInView.as_view(), name='LogInView'), path('logout', LogOutView.as_view(), name='LogOutView'), ] Please help. -
'tensorflow' has no attribute 'get_default_session'
I am currently working on a project using DJANGO KERAS and TENSORFLOW But I am really facing some issues while executing the project I even reinstalled DJANGO KERAS and TENSORFLOW but I still face these issues I have also added the screenshots of the error message Please help me to solve the issueenter image description here [Command Prompt][Webpage] default_session = tf.get_default_session() AttributeError: module 'tensorflow' has no attribute 'get_default_session' -
How to show breaklines in textarea and data fetch from JavaScript to My inner Text of textarea
I want to get data from user in <textarea> and show it on the DOM page with edit button and with breaklines if user click on edit user old data send to new <textarea> with breaklines Adding an item. <form name="add" method="POST" action="{% url 'notepad:addnote' %}">{% csrf_token %} <div class="modal-body"> Title : <input name="title" class="w-50" type="text" required><br> Note :<br> <textarea name="text" id="" cols="60" rows="10" required></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> Showing an items. <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li> </ul> {% endfor %} </div> But if i show an items it removes break lines. So I'll try pre tag to show that content with breaklines. <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <pre><li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li></pre> </ul> {% endfor %} </div> It shows break lines, but i again want to edit and send this content to my input and textarea to edit that's content , So i … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead
When i try to post a order i get error saying 'Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead.' Any help would be great. here is my models.py class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) food_item = models.ForeignKey(FoodItem,on_delete=models.CASCADE) quantity = models.IntegerField(default=0,null=True,blank=True) size = models.CharField(max_length=10,choices=SIZE_CHOICES,null=True,blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} of {self.food_item}' class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) order = models.ManyToManyField(OrderItem,null=True) order_created = models.DateTimeField(auto_now_add=True) paid = models.BooleanField(default=False,null=True,blank=True) transction_id = models.CharField(max_length=30,unique=True,null=True,blank=True) def __str__(self): return self.user.username Here is my serializer.py class OrderItemListSerializer(serializers.ModelSerializer): #user = UserSerializer(many=True,read_only=False) class Meta: model = OrderItem fields = ['id','user','food_item','quantity','size'] def create(self,validated_data): return OrderItem.objects.create(**validated_data) class OrdersSerializer(serializers.ModelSerializer): order = OrderItemListSerializer(many=True,) class Meta: model = Order fields = '__all__' depth = 0 # def create(self, validated_data): def create(self,validated_data): return Order.objects.create(**validated_data) here is my views.py class OrderPost(APIView): # add permission to check if user is authenticated permission_classes = [permissions.AllowAny] # 2. Create def post(self, request, *args, **kwargs): serializer = OrdersSerializer(data=request.data) serializer.set(order) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) error Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead. -
Payments on website: From customers to the website and vice versa
I am creating a website that needs to do this points: Receive payments to the Web site. I know that there are several payments gateways to do this. Can anyone recommend any? Make payments from the Web site to the people who are registered on the site. This people can live in any country and so they can have accounts in any bank of the world. It's possible to make bank transfers to any bank? There's another way to do it, for example with PayPal? If anyone has another idea how to do this I would be very grateful if you tell me. Without having this resolved I cannot move forward on my website. My Web site uses: HTML, CSS, Bootstrap, Jquery, Django y Python, with a SQLLite database. Thanks. -
How can i run a Django app and a Vue on the same port?
I'm building a SPA using Django for my backend and Vue to handle the entire frontend. In order to avoid some security issue and keep using the standard Django's session authentication, i'm going to run these two apps in production on the same sever and on the same port, and i will setup Nginx to route traffic, so that /account/login will be handled by Django, while /app/someURL is redirected to the Vue application. My question is: how can i do the same locally, during development? If i run manage.py runserver and npm run serve -- ---port 8000 the two apps will clash because there is no way to know where should each request be redirected. -
Django multithread database update
how do you guys handle database update when running a multithread? When I call download_image function and perform operation, it hangs after the last line to update Django ImageField for newly created thumbnail, any clue? def main(): with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: for indi_image in all_images_without_thumbnail: executor.submit(download_image, indi_image) def download_image(indi_image): image = Image.objects.get(pk = indi_image_id) image_request_result = requests.get(image.url) img_temp = PilImage.open(BytesIO(image_request_result.content)) width, height = img_temp.size max_size = [200, 200] if width > 200 or height > 200: img_temp.thumbnail(max_size) image_io = BytesIO() img_temp.save(image_io, format='JPEG') filename = image.key.split('/')[-1] file_location = os.path.join(str(image.data_set_id), filename) image.thumbnail.save(file_location, ContentFile(image_io.getvalue()), save=True) print ("here it never reach this line, only hang and no Error or Exception raised") -
Resct- Danjo REST framework: Unable to post data to a model with foreign key
I am new to Django and doing my first project. What I am unable to do is send some data to model which has a foreign key field. Here is models.py: class BasketProductMapping(models.Model): product_reference = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True, related_name='%(class)s_product_name') mapped_basket_name = models.CharField(max_length=5,null=False, blank=False) mapped_product_name = models.CharField(max_length=30, null=False, blank=False) basket_product_mapping_date = models.DateField(auto_now_add=True) basket_product_mapping_modified_date = models.DateField(auto_now=True) def __str__(self): return self.mapped_basket_name Here is my serializers.py file: class BasketProductMappingSerializer(serializers.ModelSerializer): product_reference = ProductSerializer(read_only=False) class Meta: model = BasketProductMapping fields = ('id', 'mapped_basket_name', 'mapped_product_name', 'product_reference') Here is my views.py: class BasketProductViewSet(APIView): def get(self, request): if request.GET.get('id'): #print('Basket Product Mapping Details') basketProductMappingData = BasketProductMapping.get(id = request.GET.get('id')) serializer = BasketProductMappingSerializer(basketProductMappingData) else: print('Basket Product Mapping Details') basketProductMappingData = BasketProductMapping.objects.all() serializer = BasketProductMappingSerializer(basketProductMappingData, many=True) response = {'status':1, 'message':"Basket Product Mapping List", 'data':serializer.data} return JsonResponse(response, safe=False) def post(self, request): data = request.data print(data) serializerData = '' saveBasketProductMapping = BasketProductMappingSerializer(data = data) if saveBasketProductMapping.is_valid(): print('Valid data') saveBasketProductMapping.save() serializerData = saveBasketProductMapping.data satusResponse = status.HTTP_201_CREATED else: print('Invalid Data') serializerData = saveBasketProductMapping.errors statusResponse = status.HTTP_400_BAD_REQUEST response = {'status': 1, 'message': 'Basket Product Mapping created successfully', 'statusResponse':statusResponse, 'serializerData':serializerData} return JsonResponse(response, safe=False) I am receiving the data from a POST request in this format: <QueryDict: {'mapped_basket_name': ['B3'], 'mapped_product_name': ['XYZ'], 'product_reference': ['XYZ']}> However, the data is not … -
OSError: dlopen(/opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/Darwin/libepanet22_win32.dylib, 6): image not found
I updated billiard,celery,kombu,amqp : nothing worked, Please help me resolve this. I am trying to use https://wntr.readthedocs.io/ OSError Traceback (most recent call last) <ipython-input-9-6ccee6a8a438> in <module> 1 # Simulate hydraulics 2 sim = wntr.sim.EpanetSimulator(wn) ----> 3 results = sim.run_sim() /opt/anaconda3/lib/python3.8/site-packages/wntr/sim/epanet.py in run_sim(self, file_prefix, save_hyd, use_hyd, hydfile, version) 94 inpfile = file_prefix + '.inp' 95 self._wn.write_inpfile(inpfile, units=self._wn.options.hydraulic.inpfile_units, version=version) ---> 96 enData = wntr.epanet.toolkit.ENepanet(version=version) 97 rptfile = file_prefix + '.rpt' 98 outfile = file_prefix + '.bin' /opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/toolkit.py in __init__(self, inpfile, rptfile, binfile, version) 155 except Exception as E1: 156 if lib == libnames[-1]: --> 157 raise E1 158 pass 159 return /opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/toolkit.py in __init__(self, inpfile, rptfile, binfile, version) 148 elif sys.platform in ['darwin']: 149 libepanet = resource_filename(epanet_toolkit,'Darwin/lib%s.dylib' % lib) --> 150 self.ENlib = ctypes.cdll.LoadLibrary(libepanet) 151 else: 152 libepanet = resource_filename(epanet_toolkit,'Linux/lib%s.so' % lib) /opt/anaconda3/lib/python3.8/ctypes/__init__.py in LoadLibrary(self, name) 457 458 def LoadLibrary(self, name): --> 459 return self._dlltype(name) 460 461 cdll = LibraryLoader(CDLL) /opt/anaconda3/lib/python3.8/ctypes/__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error, winmode) 379 380 if handle is None: --> 381 self._handle = _dlopen(self._name, mode) 382 else: 383 self._handle = handle OSError: dlopen(/opt/anaconda3/lib/python3.8/site-packages/wntr/epanet/Darwin/libepanet22_win32.dylib, 6): image not found Everything worked earlier. I am using MacOS Sierra 10.13.6 -
ValueError: operands could not be broadcast together with shapes (32,31) (32,29)
import numpy as np TODO: divide error by respective number of instances for normalization def costfunction(params,Y, R, num_students, num_courses, num_features, reg_param, reg_param2, OrigTheta): # X is courses*features # Theta is students*parameters X = np.reshape(params[:num_courses * num_features], (num_courses, num_features), order='F') Theta = np.reshape(params[num_courses * num_features:], (num_students, num_features), order='F') # Take dot product of theta and x transpose to compute predicted rating # Compute squared error squared_error = np.power(np.dot(Theta, X.T) - Y, 2) # Contribution to squared error will come only from those ratings which # are not missing and which have not been relocated to test data J = (1 / 2.) * np.sum(squared_error * R) #Add contribution of theta and x to objective funciton incorporating the regularization parameter J = J + (reg_param / 2.) * (np.sum(np.power(Theta, 2)) + np.sum(np.power(X, 2))) # Limit the value of new theta close to original theta J = J + (reg_param2 / 2.) * (np.sum(np.power(Theta - OrigTheta,2))) X_grad = np.dot(Theta.T, (np.dot(Theta, X.T) - Y) * R).T Theta_grad = np.dot(((np.dot(Theta, X.T) - Y) * R), X) X_grad = X_grad + reg_param * X Theta_grad = Theta_grad + reg_param * Theta + reg_param2 * (Theta - OrigTheta) grad = np.concatenate((X_grad.reshape(X_grad.size, order='F'), Theta_grad.reshape(Theta_grad.size, order='F'))) return J , … -
Why is django-cleanup deleting used media files?
I have django-cleanup installed on my project, and I've ran into a bug where anytime I upload an image with the same name as another image already in the media folder, the old image is deleted and the new image is saved, but with new string on the end of it. This means I am losing used images when an image of the same name is uploaded. For example if I have image.jpg and I upload another image called image.jpg, the original image.jpg is deleted and the new one is saved as something like image_tccwtVY.jpg. I've implemented this in previous projects the exact same way (and version) and never had an issue. Can anyone think as to why it is doing this? -
What happens if I put same SECRET_KEY for my django 3 (app.com, portal.app.com , code.app.com) different projects
I was working on a project that have 2 sub-domains. Lets Understand with example I have 3 domains http://127.0.0.1:8000/ # This project is for api.my-domain.com http://127.0.0.1:8002/ # This project is for my-domain.com http://127.0.0.1:8003/ # This project is for account.my-domain.com at the initial stage I was stuck at accessing Logged In/out user from portal project in other project. like payoneer do: => we login at http://login.payoneer.com, But the same (Logged in) account we can access in http://myaccount.payoneer.com/ I was stuck at session authentication to get logged user. Then i try on myself to change secret key. I put the same secret key for all my domains . e.g. Let's Assume this is my secret key in django SECRET_KEY = "ehs-345asf4512*$^&__SH-35asdf43" i set this secret key in settings.py for http://127.0.0.1:8000/ I also set this secret_key in settings.py for http://127.0.0.1:8002/ I also set this same secret_key in settings.py for http://127.0.0.1:8003/ Then i was able to access Logged in/Out user from my http://127.0.0.1:8000/ project to another projects MY Question is that what happens if i put same SECRET_KEY for all my sub-domains on this domain? Is there any other way to get logged in/out user from my project. i am gonna work on android … -
How can I connect my pre-existing python script to Django
I am currently working on an Automated Machine Learning App, and my pipelines are implemented in python. Now that I need to move to the platform in Django, I'm finding difficulties to use my preexisting functions for the requests. (I am still very new to Django and was only able to configure the template which is the main page) I read about its MTV architecture and do understand the logic. My ML pipelines are currently called through my 'main.py' file and I need to shift this to the web app. -
How to turn off logging for SqlAlchemy db pool only, when debugging is enabled in Python Django?
Context / environment I have a Python Django project connecting to a PostgreSQL database with a SqlAlchemy django-postgrespool2 db pool. What I'm trying to achieve In settings.py I have set DEBUG = True which will make the program log. However, I want to disable the logging coming from the SqlAlchemy db pool only, while having DEBUG set to True. In other words, when debugging, I want to see all logs except for the ones coming from the SqlAlchemy db pool. What I've tested The code below shows too different attempts I've made to disable the db pool logging: def turnOffLog(self): # --- Attempt 1, db pool logs still show --- logging.basicConfig() logging.getLogger('sqlalchemy').setLevel(logging.ERROR) # --- Attempt 2, db pool logs still show --- sqla_logger = logging.getLogger('sqlalchemy.engine.base.Engine') for hdlr in sqla_logger.handlers: sqla_logger.removeHandler(hdlr) I also pass echo=False to the QueuePool instance when I create it, which still doesn't remove the logs: dbPool = pool.QueuePool(dbConnection, max_overflow=dbConfig.poolMaxOverflow, pool_size=dbConfig.poolSize, recycle=dbConfig.poolRecycleTime, pre_ping=dbConfig.prePing, dialect=postgresql.dialect(), echo=False) My settings.py file (DEBUG is set to True from an env-config file): """ Mbrain """ import os import logging import socket import sys from decouple import Config, RepositoryEnv import time # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
DRF post method working without csrf token. Is it safe?
Before working with drf, i knew that, we need to add csrf token to submit the form data. But in django-rest-framework POST method working without csrf token. Is it safe? createGroup=()=>{ let store = JSON.parse(localStorage.getItem('login')) var url = 'http://127.0.0.1:8000/myapi/creategroup/' fetch(url,{ method:'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Token '+store.token, }, body:JSON.stringify({ 'name':this.state.groupName, }) }) .then((response)=>{ response.json() document.getElementById('i').value='' this.setState({groupName:''}) }) } -
How to reject login when user already has a session in django
In my django application I want to reject a user login if he has already an active session. How can I do that? I tried some attempts using user_logged_in signals. Should I do this check login form with confirm_login_allowed() before new session creation? My current setup is like that: accounts/signals.py @receiver(user_logged_in) def check_existing_session(sender, user, request, **kwargs): session_key = request.session.session_key user.set_session_key(session_key) accounts/models.py def set_session_key(self, key): self.last_session_key = key self.save() -
Enable Partial/Free/Full text search on a unique column PostgreSQL
I have a unique column inside the table of type citext (at Django model level CICharField). colName = CICharField(max_length=255, unique=True) This column has a unique constraint(index) enabled. UNIQUE CONSTRAINT, btree (colName). I have a case where I want to perform a partial/full/free text search on this column using %LIKE%. Now since this already has a unique constraint index enabled on this column, is there a way to create another index that can be used by %LIKE% query to improve the performance? I understand that only 1 index can be used at once but I was just wondering if there is any workaround to improve this a little more. I'm using Django ORM, which provides __contains attribute, that can be used to perform %LIKE% queries. Since it's a citext type column, I can't use the search attribute provided by Django. https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/search/ I guess adding db_index=True wouldn't help either. -
psycopg2 installed on M1 running MacOS Big Sur, but unable to run local server
I have the new (2021) Macbook Air running the Apple M1 chip. I have set up my django application, which uses postgresql, and I have created a virtualenv running Python 3.9.2. Have installed Python directly from the macOS 64-bit universal2 installer on python.org. After much difficulty, I was finally able to install psycopg2 using: env LDFLAGS="-L/opt/homebrew/opt/openssl@1.1/lib -L/opt/homebrew/opt/readline/lib" pip3 --no-cache install psycopg2-binary==2.8.6 I am able to SSH into my PostgreSQL DB, but when I run python manage.py runserver, I get the following error (abridged due to length). File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/contrib /auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/contrib /auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/mode ls/base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/mode ls/base.py", line 325, in add_to_class value.contribute_to_class(cls, name) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/mode ls/options.py", line 208, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/__in it__.py", line 28, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/util s.py", line 207, in __getitem__ backend = load_backend(db['ENGINE']) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/util s.py", line 111, in load_backend return import_module('%s.base' % backend_name) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__ init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/Users/seb/.virtualenvs/onefabric/lib/python3.9/site-packages/django/db/back ends/postgresql/base.py", line 29, in <module> raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/ … -
Is this a Django bug with annotation?
Redefining models.query.QuerySet. class TransactionQuerySet(models.query.QuerySet): def delete(self, *args, **kwargs): wallets = [] wallet_transactions = self.values('wallet').annotate(amount = Sum('amount')) ... ... I got: wallet_transactions = <TransactionQuerySet [{'wallet': 1, 'amount': 666}, {'wallet': 1, 'amount': 1000}, {'wallet': 1, 'amount': 500}, {'wallet': 1, 'amount': 1000}]> Why aggregation in annotation doesn't work??? If you write right there: Transaction.objects.all().values('wallet').annotate(amount = Sum('amount')) then everything is ok and I get: <TransactionQuerySet [{'wallet': 1, 'amount': 3166}]> self и Transaction.objects.all() - одно и тоже <TransactionQuerySet [<Transaction: Transaction: B3>, <Transaction: Transaction: B3>, <Transaction: Transaction: B2>, <Transaction: Transaction: B1>]> Is it a Django bug? -
Django translate data from the DB {{ profession }}
Is it possible to translate DB entries? I have a dependent dropdown story that i need to translate. But i cant translate the dropdown fields, the fields come from other models and har hard coded. I can use HTML with JQ to achive this but i want to skip the manual labor to translate everytime new profession or professioncategories are added. class Profession(models.Model): name = models.CharField(max_length=30), def __str__(self): return self.name class Professioncategory(models.Model): profession = models.ForeignKey(Profession, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Skills(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(_('Active'), default=True) profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True) professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True) posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('last updated'), auto_now=True) years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) -
Using Google OAuth with React-Django Application
I am working on a web application with ReactJs frontend and Django backend. In this app, I will need to send calender notifications to the users and overall need a user authentication feature for which I planned to use google oauth. From react, I am able to log in the user and get the access tokens but since they expire in an hour, I planned to get the authorization code and use it to get the refresh/access tokens from the backend whenever a user logs in/needs to send API request. The issue is that I am not able to find any good resource on how to get refresh tokens from the backend given I have the authorization code. Most of the HTTP based methods I have found are very outdated and I have searched some of the google documentation but have not found anything worthwhile. Since I could not find any package that would handle this, I have been trying to send POST request to the URL mentioned here (https://developers.google.com/identity/protocols/oauth2/web-server#python_1) but only get a 400 response. Below are 2 methods I have tried. to_send={'code':user_data['code'], 'client_id': cl_id , 'client_secret': cl_secret, 'redirect_uri':'http://localhost:3000/', 'grant_type':'authorization_code'} test=requests.post('https://oauth2.googleapis.com/token', data=to_send) print(test) credentials = service_account.Credentials.from_service_account_file('path/key.json') scoped_credentials = credentials.with_scopes(['https://www.googleapis.com/auth/drive.metadata.readonly']) … -
Script function not found : doGet
These are the codes i m working with script_url is the google script web app deployed sample.py import requests import datetime url = "script_url?client_name={}&client_address={}&company_name={}&company_address={}&vessel_name={}&po={}&id={}&date={}&item1={}&item2={}&item3={}&cost1={}&cost2={}&cost3={}&total={}" name_client = ["inder", "sawpnesh", "kajal"] address_client = ["addInder", "addswapnesh", "addkajal"] name_company = ["ospl", "ospl", "ospl"] address_company = ["addospl", "addospl", "addospl"] vessel_name = ["redlips", "elizabth", "jack"] po = ["EWDCC", "wefwec", "asxwq"] invoice_ids = ["1", "2", "3"] item1 = ["keyboard", "mouse", "screen"] item2 = ["mouse", "screen", "keyboard"] item3 = ["screen", "keyboard", "mouse"] cost1 = ["1000", "500", "2000"] cost2 = ["500", "2000", "1000"] cost3 = ["2000", "1000", "500"] i = 0 for invoice_id in invoice_ids: total = cost3[i] + cost2[i] + cost1[i] print("processing ", invoice_id) response = requests.get( url.format(name_client[i], address_client[i], name_company[i], address_company[i], vessel_name[i], po[i], invoice_id, datetime.date.today(), item1[i], item2[i], item3[i], cost1[i], cost2[i], cost3[i], total )) # response = requests.get( # url.format(invoice_id, cust_names[i], add_streets[i], add_citys[i], issue_dates[i], last_dates[i])) print("file generated") response = requests.get(response.content) print("file downloaded") i += 1 with open("invoice{}.pdf".format(invoice_id), "wb") as f: f.write(response.content) # i += 1 google script app code.cs function createDocument(id,client_name,client_address,company_name,company_address,vessel_name,po,date,item1,item2,item3,cost1,cost2,cost3,total) { var TEMPLATE_ID = 'template_id'; var documentId = DriveApp.getFileById(TEMPLATE_ID).makeCopy().getId(); drivedoc = DriveApp.getFileById(documentId); drivedoc.setName("Invoice " + id+"/2021"); doc = DocumentApp.openById(documentId); var body = doc.getBody(); body.replaceText('{id}', id); body.replaceText('{client_name}',client_name); body.replaceText('{client_address}',client_address); body.replaceText('{company_name}',company_name); body.replaceText('{company_address}',company_address); body.replaceText('{vessel_name}',vessel_name); body.replaceText('{po}',po); body.replaceText('{date}',date); body.replaceText('{item1}',item1); body.replaceText('{item2}',item2); body.replaceText('{item3}',item3); body.replaceText('{cost1}',cost1); body.replaceText('{cost2}',cost2); body.replaceText('{cost3}',cost3); …