Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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); … -
Filtering, ordering and pagination in clean architecture django rest
I recently used clean architecture for my project. The project is divided into several sections according to clean architecture, each of which performs its tasks. But what confused me is that, I do not know how can I use filter and pagination class in this architecture. -
"NodeAlreadySaved " error when using djangocms publishing page changes
Encounter an error when using djangocms publishing page changes. when I ran tail -f /var/log/apache2/error.log, it returned: treebeard.exceptions.NodeAlreadySaved: Attempted to add a tree node that is already in the database, referer: http://47.95.254.172/?edit And when I allowed the settings.py DEBUG= True and click the 'Publish page changes' button: NodeAlreadySaved at /admin/cms/page/1/en/publish/ Attempted to add a tree node that is already in the database Request Method: POST Request URL: http://47.95.254.172/admin/cms/page/1/en/publish/ Django Version: 3.1.7 Exception Type: NodeAlreadySaved Exception Value: Attempted to add a tree node that is already in the database Exception Location: /root/env1/lib/python3.8/site-packages/treebeard/mp_tree.py, line 326, in process Python Executable: /root/env1//bin/python Python Version: 3.8.5 I have run python manage.py cms fix-tree but it did not work. While python manage.py cms check returned 10 checks successful!. I deployed the djangocms project with: apache2.4.41 mod-wsgi 4.8.0 django 3.1.7 django-cms 3.8.0 The python version in venv is 3.8.5, and mod-wsgi was compiled by python3.8.5 in the venv. Thank you for the help! -
How can store Multiple checkbox value to single user
I am trying save multiple id of products from checkbox to a specific user, but i select multiple values and submit them it show the error. ' Field 'id' expected a number but got ['13', '14', '22']. ' when i select any category from drop down menu it just only show last added category, not show that category which i select view.py class Vendor_Category(TemplateView): template_name = 'purchase/vendorCategory.html' def get(self, request, *args, **kwargs): categories = CategoryModel.objects.all() categoryId = self.request.GET.get('SelectCategory') products = ProductModel.objects.filter(category_id=categoryId) args = {'categories': categories, 'products': products, 'selectedCategory': categoryId} return render(request, self.template_name, args) def post(self, request, vendor_id): categoryobj = self.request.GET.get('SelectCategory') productobj = self.request.POST.getlist("ProductSelect") try: vendor = VendorCategory( vendor_id=VendorModel.objects.get(id=vendor_id), category_id=categoryobj, product_id=productobj, ) vendorCate.save() return redirect('menu') except Exception as e: return HttpResponse('failed{}'.format(e)) Template {% block content %} <form method="get"> {% csrf_token %} <label> <select name="SelectCategory" > <option disabled="disabled" value="True" selected="{{ selectedCategory|yesno:"yes, no"|safe }}"> Select Category</option> {% for category in categories %} <option value="{{ category.id }}" selected="{% if category.id == selectedCategory %} {% endif %}"> {{ category.name }} </option> {% endfor %} </select> </label> <input type="submit" value="Select"> </form> <form method="post"> <input type="hidden" value={{ selectedCateogry }} name="ProductSelect"> {% csrf_token %} <label> {% for product in products%} <input type="checkbox" name="ProductSelect" value="{{ product.id }}" >{{ product.name … -
How could i get an object correctly from database in a different server in python?
I am trying to work with a machine learning and a web server with django, and both my web and machine learning server use the same dockerized postgres database. Machine learning server creates machine learning models and writes them to the database by using pickle. I have a Regressor class in machine learning server like this: class Regressor: def __init__(self): self.predictions = [] self.yTrue = [] self.predDiffs = [] self.model = object self.name = "" #some methods below and i have a class that creates an appropriate database table for orm technique class RegressorTable(DeclarativeBase): __tablename__ = "ml_models" id = Column(Integer, primary_key=True) regressorName = Column(String) regressorModel = Column(LargeBinary) and both in machine learning and django web server, i have 2 functions in order to convert models to binary and binaries to model def modelToBinary(model): return pickle.dumps(model) def binaryToModel(data): return pickle.loads(data) Here is my method in the machine learning server to save the Regressor models for the database: def saveModelsToDb(predictorArray): for predictor in predictorArray: predictorForTable = RegressorTable() predictorForTable.regressorName = predictor.name predictorForTable.regressorModel = modelToBinary(predictor) DBSession.add(predictorForTable) DBSession.commit() The predictorArray in the above code contains Regressor objects. When i try to save and load models in machine learning server, i can successfully save, load and … -
Realtime sharing of Website content to other user
I have a django web application with a map view using openlayers. I have to develop a map sharing screen in real time to other user in the application for the real time view/suggestion for the edit. How to develop the real time web content sharing system. -
Django. Model function for avatar
I wrote a function for the profile model so that if the profile does not have an avatar, there will be a default picture. But this function works only when the profile has a picture, and when it does not exist, there is the absence of any image tag . How can I write the function correctly so that it displays a picture from the media folder of the project directory? @property def avatarURL(self): try: url = self.avatar.url except: url = 'media/avatar.svg' return url ── ./media │ ├── ./media/avatars │ ├── ./media/avatar.svg │ └── ./media/images HTML <img src="profile.avatarURL" alt="Profile picture class="round"/> -
How to show Many-to-Many Field on Django Admin Panel?
I have 2 models, Product and Tag. The relation between product and tag is Many-to-Many Relationship. How to show "tags" field on django admin panel? Currently the value is None when I am using the code below models.py class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) name = models.CharField(max_length=200, null=True) price = models.FloatField(null=True) category = models.CharField(max_length=200, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) tags = models.ManyToManyField(Tag) admin.py @admin.register(Product) class ProductAdmin(admin.ModelAdmin): list_display = ['id','name','price','category','tags'] list_display_links = ['name'] def tags(self): return self.tags.name -
REST Framework — Serializing many-to-many. Create and Save
I am using django-restframework for my API. My problems: I can't validate data. Need to create "regions" and nested with courier. Regions send as a list in json. But when validating the data, I get the following errors: error_valid {'regions': [{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')]}, {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got int.', code='invalid')] How I can created models with this json POST request? The POST json: { "data": [ { "courier_id": 10, "courier_type": "foot", "regions": [1, 12, 22] }, { "courier_id": 11, "courier_type": "bike", "regions": [22] },.. ] } My models.py: class Regions(models.Model): region_id = models.PositiveIntegerField(unique=True) def __str__(self): return self.region_id class Courier(models.Model): courier_id = models.PositiveIntegerField(unique=True, ) courier_type = models.CharField(max_length=4, choices=TypeCourier.choices, blank=False, ) regions = models.ManyToManyField("Regions", through=RegionsCouriers, through_fields=("courier", "region" ), ) Regions will need to be created together with the post request my serializers.py class RegionsSerializer(serializers.ModelSerializer): class Meta: fields = "__all__" model = Regions class CourierSerializerPost(serializers.ModelSerializer): regions = RegionsSerrializer(many=True) class Meta: model = Courier fields = "__all__" my View.py class CourierView(APIView): def post(self, request): data = request.data["data"] couriers_add = [] couriers_fail = [] for record in data: serializer = CourierSerializerPost(data=record) if serializer.is_valid(): courier_id = … -
Unable to update many to many fields in Django Rest Framework
I have a Product model which has many fields, some of them have many to many relationships with other models, for eg the Category model. I am able to update other fields but I am stuck at updating the m2m fields from the JSON payload sent from the frontend. I have the logic, but can't write the code. I have to first remove the existing categories which are associated with that product and add the new categories that are on the payload from the ids. My models: class Category(models.Model): name = models.CharField(max_length=100, unique=True) image = models.ImageField(null=True, blank=True) class Meta: verbose_name_plural = "Categories" def __str__(self): return self.name class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? best_seller = models.BooleanField(default=False) top_rated = models.BooleanField(default=False) My views: class ProductUpdateView(UpdateAPIView): permission_classes = [AllowAny] queryset = Product.objects.all() serializer_class = ProductUpdateSerializer My serializers: class ProductUpdateSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id','featured', 'top_rated','brand','collection', 'name','description', 'main_product_image','best_seller', 'rating','availability','warranty','services',] def update(self, instance, validated_data): instance.featured = validated_data.get('featured',instance.featured) instance.top_rated = validated_data.get('top_rated', instance.top_rated) instance.brand = validated_data.get('brand', instance.brand) instance.collection = validated_data.get('collection',instance.collection) instance.name = validated_data.get('name', instance.name) instance.description = validated_data.get('description', instance.description) #category_logic category_data = validated_data.get('category') #new_category = validated_data.pop('category') product = …