Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get_object error not handled correclty
I have the following setup: class DashboardViewSet(...): def get_object(self): print('GET_OBJECT') queryset = self.filter_queryset(self.get_queryset()) ... try: obj = queryset.get(pk=pk) except queryset.model.DoesNotExist: print('ERROR_GET_OBJECT') raise Http404('error') class CampaignObjectViewSet(DashboardViewSet): permission_classes = (IsAuthenticated,) def get_queryset(self): print('START_GET_QUERYSET') try: # some logic print('END_GET_QUERYSET') except (Campaign.DoesNotExist, TenantUser.DoesNotExist, django.http.Http404): print('ERROR_HANDLER') raise Http404 class CampaignTargetViewSet(CampaignObjectViewSet): def get_queryset(self): print('SUB_QUERYSET') base = self.filter_queryset(super().get_queryset()) ... The output I'm getting is: GET_OBJECT ERROR_GET_OBJECT SUB_QUERYSET START_GET_QUERYSET END_GET_QUERYSET Which means I'll get results from the backend although there was actually an error in the get_object method. What am I missing here or not handling properly? -
Django queryset: cannot filter by current week when USE_TZ is enabled
I am using Django 2.1 with USE_TZ = True and TIME_ZONE = 'UTC'. This is my model DateTimeField: create_date = models.DateTimeField(_('date created'), null=True, auto_now_add=True) I am trying to get the current week results based on the week number. I tried the following: today = timezone.now() current_week_num = today.isocalendar()[1] week_results = MyModel.filter(create_date__week=current_week_num).count() This always return 0 while there are records in the database. It works fine if I set USE_TZ = False. Any idea? -
handling url parameters in Django unit tests
I am testing a link which has parameters, how can I pass them in the unit test? urls.py re_path(r'^link/(?P<id>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z_\-]/$', views.link, name="link"), views.py def link(request, id, token): ... In tests.py @classmethod def setUpTestData(cls): ... cls.data = { 'id': '01', 'token': 'token1234' } .... response = self.client.post(reverse('link'), kwargs=self.data) -
KMeans in python (framework = django)
I wanto to use KMeans in django... my code is: from django.db import models from django.utils import timezone import sys from sklearn.cluster import KMeans from sklearn.metrics import pairwise_distances_argmin_min # Create your models here. class tabla (models.Model): nombre = models.CharField(max_length=35) comida = models.PositiveSmallIntegerField() cantidad = models.PositiveSmallIntegerField() edad = models.PositiveSmallIntegerField() fecha_publicacion = models.DateTimeField(auto_now_add = True) def datos(self): cadena="hola, {0}, {1}, {2}, {3}, {4}" cadena2="{0} {1} {2}" cadena2.format(self.cantidad,self.comida,self.edad) #return cadena.format(self.nombre, self.comida,self.cantidad,self.edad,self.fecha_publicacion) kmeans = KMeans(n_clusters=3).fit(cadena2) centroids = kmeans.cluster_centers_ return centroids def __str__(self): return self.datos() and .. my result is : oh my problem is ... wat is the wrong?? C:\TrabajoIA>python manage.py runserver C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\externals\joblib\externals\cloudpickle\cloudpickle.py:47: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\externals\joblib\externals\cloudpickle\cloudpickle.py:47: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp Performing system checks... System check identified no issues (0 silenced). December 17, 2018 - 04:46:40 Django version 2.1.3, using settings 'TrabajoIA.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. C:\Users\kleys\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\externals\joblib\externals\cloudpickle\cloudpickle.py:47: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import imp Performing system checks... System check identified no issues (0 silenced). December … -
how to implement drag and drop to upload files in django, while i have already implemented simple file upload
I have below code for upload file but i need to implement drag and drop functionality on top of that in django please help with my code. upload.html {% block content %} <div method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"><br><br> <input type="submit" value="upload"> {% endblock %} Views.py def simple_upload(request): # return HttpResponse("<H2>Upload</H2>") if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage(location="ciscotest/uploadedmedia") filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'upload.html', {'uploaded_file_url': uploaded_file_url,"fileupload":"File uploaded successfully"}) return render(request, 'upload.html') -
One way syncing of data between two Django programs, over Postgresql
I have a Django system that is working for more than two years, sitting there, collecting data (specifically User information related to my question). Now the customer needs another application that would use existing system's user database, but needs to have a completely different environment, besides the shared User base, and probably different server, network etc. My basic requirements are: Write access to user tables are only from the old system Read access to same tables are from both systems. While instant sync is not required, a batch (that copies data from one server to other (let's say on the hour every hour) is our of question, they need to have data to be available around 10-15 minutes, and running a batch sync that frequently would kill both servers. Now, I have tried to connect multiple databases to a single (new) program. However, as Django does not support inter database relations, this does not work for me. I am planning and trying to use Postgresql foreign table mechanism and it seems to be promising. What I wonder is; Can anybody provide me with either: Some best practices for such a connection, or Another, well established method for connecting Django programs … -
python, Django added new celery task
i'm new to python celery, and thus my question, i added recently 3 new tasks that looks like this : @shared_task(name="3rd-task",acks_late=True, autoretry_for=(Exception,), retry_backoff=True) when i run it from console, everything is fin, but when i try to run via periodic_task in Django i get this error AttributeError at /admin/django_celery_beat/periodictask/ 'NoneType' object has no attribute 'delay' Request Method: POST Request URL: http://localhostadmin/django_celery_beat/periodictask/ Django Version: 2.0.4 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'delay' Exception Location: /usr/local/lib/python3.5/dist-packages/django_celery_beat/admin.py in <listcomp>, line 184 i think, problem is that i didn't register it somewhere -
Web page timeout and refresh is not working
I have a web page template on django. In this template i have two controls. I am waiting the page to be forwarded to another page after a certain time passed. One is meta : <meta http-equiv="refresh" content="900;{% url 'list-attendance' %}"/> and second one is script : <script> window.setTimeout(function(){ window.location.href = "{% url 'list-attendance' %}"; },610000); </script> If i open one page on browser it works. And redirects to list-attendance url. But if i open same page in two tabs on same browser, one of the pages redirect other one stucks and does not redirect. -
How to update tensorflow on Windows 10
I recently tried to update Tensorflow on my Windows 10. Using pip3 install --upgrade tensorflow I've already updated to latest pip version and installed the following: pip3 install six numpy wheel pip3 install keras_applications==1.0.6 --no-deps pip3 install keras_preprocessing==1.0.5 --no-deps However, I am getting the following error when I import Tensorflow. Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\Users\User\Anaconda3\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "C:\Users\User\Anaconda3\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: A dynamic link library (DLL) initialization routine failed. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow__init__.py", line 24, in from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python__init__.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in from tensorflow.python.pywrap_tensorflow_internal import * File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in _pywrap_tensorflow_internal = swig_import_helper() File "C:\Users\User\Anaconda3\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\Users\User\Anaconda3\lib\imp.py", line 243, … -
Django Regex Field Lookup - Sort by Number of Matches for Each Item in QuerySet
I am experimenting with a basic regex expression as a way of performing a Django filter operation. I would like to remove any insignificant words from a supplied query string, look for any objects with titles containing any of the remaining words, and then sort starting with those containing the most words. Using a quick and simplified example: ignored_words = {'for', 'a', 'of', 'the', 'and', 'to', 'in'} keywords = [] for word in query.split(): if word not in ignored_words: keywords.append(word) if len(keywords) > 0: regex_str = r'(' + '|'.join(keywords) + ')' results = MyModel.objects.filter(title__iregex=regex_str) # Now sort them... If my query string was 'Delicious Apples and Bananas' and I had three objects with the following titles: 'Apples' 'Bananas' 'Apples and Bananas' is there an efficient way I can order my results by the number of keyword occurrences? More specifically, I'm not sure if I should be doing some sort of Count() operation whilst querying, or looping through the results afterwards and doing some sort of additional regex processing then. Thanks. -
How to separate users dashboard and model in django
I want to create a system that has two type of user. Normal users and coaches. How can I separate users when they login in system. I want to separate their dashboard after they logged in. Should I create two model? one model for users and one model for coaches? -
Django autoincrement field
I was trying to make an auto-increment for a certain field and don't know the proper way to do it. I am using postgres for administrating my database and usually This is my code: models.py class Workorder(models.Model): WO_ID = models.BigIntegerField(blank=True, primary_key=True) WO_DateDefWO = models.DateField(default=datetime.now) WO_DateSched = models.DateField(blank=True, null=True) WO_DateFinished = models.DateField(blank=True, null=True) WO_ST_ID_Sign = models.BigIntegerField(blank=True, null=True) WO_Status_ID = models.BigIntegerField(blank=True, null=True, default=1, choices=STATUS_CHOICES) WO_Type_ID = models.BigIntegerField(blank=True, null=True, default=1, choices=TYPE_CHOICES) WO_Comments = models.CharField(max_length=254, blank=True, null=True) WO_Nav_ID = models.BigIntegerField(blank=True, null=True) WO_Nav_Kons_ID = models.CharField(max_length=12, blank=True, null=True) WO_Nav_Name = models.CharField(max_length=254, blank=True, null=True) WO_Nav_CustAdr = models.CharField(max_length=254, blank=True, null=True) WO_Nav_Debt = models.FloatField(blank=True, null=True) WO_Nav_PropCode = models.CharField(max_length=254, blank=True, null=True) WO_Nav_DepCode = models.CharField(max_length=254, blank=True, null=True) WO_Nav_PhoneNo = models.CharField(max_length=254, blank=True, null=True) WO_Nav_ReasonCompl = models.CharField(max_length=254, blank=True, null=True) WO_NightShift = models.BooleanField(default=False) WO_Priority = models.BigIntegerField(blank=True, null=True) WO_RE_ID = models.BigIntegerField(blank=True, null=True) WO_MapUrl = models.CharField(max_length=254, blank=True, null=True) def __unicode__(self): return self.WO_ID postgresql autoincrement code: CREATE SEQUENCE public.MMS_workorder_id_seq INCREMENT 1 START 1 alter table MMS_workorder ALTER COLUMN "WO_ID" SET DEFAULT nextval('MMS_workorder_id_seq'); -
django filter with and conditions doesn't work
I want to filter a model with with 2 conditions with "and" logic. I have tried using chain filters and Q method too but not getting the desired result. Its works as "or" logic. Please help. -
History in Proxy Django model
I am trying share a model between 2 apps and I achieved it using Proxy model mechanism. Now when I change any field in Proxy model interface it is not reflecting in history page. I'm seeing no changes made via admin interface message. Do I need to add anything in proxy model to get the history. Please help me out Note: I defined proxy model like below class ModelA(models.Model): fields goes here class Meta: db_table = 'Table' class ProxyModel(ModelA): class Meta: proxy=True -
displaying one field from InlineModel horizontally in django-admin
i have field('image_tag') from Inlinemodel that i want to display in one row of Orderdetail model. class SampleImagesInline(admin.StackedInline): fields = ['image_tag'] readonly_fields = ['image_tag'] model = SampleImages extra = 0 @admin.register(OrderDetail) class OrderDetailAdmin(admin.ModelAdmin): inlines = [SampleImagesInline] by default these are showing vertically. how to display in one row?. -
Django Forms; Is it possible to hide some of the choices?
What I want to do is to hide or show some of the choices depending on the page. For example, A = 'a' B = 'b' C = 'c' D = 'd' E = 'e' TOPICS = ( (A, 'A'), (B, 'B'), (C, 'c'), (D, 'd'), (E, 'e'), ) topic = models.CharField( max_length=1, choices=TOPICS, default=A, ) For a page, I want to force users not to choose A, so I want to hide A in form and also change the default value. How can I do this? -
Django - select all model objects that are in list
I have a model: class SupplierOffer(models.Model): name = models.CharField(max_length=255, blank=True) code = models.CharField(max_length=255, blank=True) brand = models.CharField(max_length=255, blank=True) And from the outer API I got a list of codebrands: api_list = [CodeBrand(code=u'N00105004004', brand=u'NOVONOL'), CodeBrand(code=u'N00105004004', brand=u'Preston')] I want to filter all my supplier offers that match API list items, like this: result = [] for item in api_list: result.extend(list(SupplierOffer.objects.filter(code=item.code, brand=item.brand))) It is not the best solution, because it makes 1 db query per item in api_list. How can I filter offers in 1 db query? -
custom roles and permission
I am newbie in django and drf, so this is the place where I think I could be helped. I am building a office attendance system. Now here the users are 1. Operational Manager(OM) 2. Admin 3. staff 4. CEO. OM can creates a new user and assigns whether it is admin or staff or ceo. Admin, Staff and CEO have their own permissions. My questions is how to assign these roles and permission to the types of user in django rest framework. I had seen the drf documentation on custom permission which says to extend BasePermission class and implement 2 methods. My requirement is new user doesn't make registration by themself but OM creates a new user for them. -
Python unhashable type list inside JSON when refactored into a JSON array
I'm generally aware of how python deals with JSON (I think), but I've come across something I can't explain. I was initially using this code in an api endpoint to provide options for dropdown menus in a react app: data = { "urgency_choices": URGENCY_CLASSES, "severity_choices": SEVERITY_CLASSES, "issue_classes": ISSUE_CLASSES, "flats": [(x.id, x.flat.name) for x in OperationsFlat.objects.all()] } I then decided that this could be refactored to instead provide a JSON array of 'fields', each with its own choices key, and whether or not it is a required field: data = { [ {"name": "Urgency", "choices": URGENCY_CLASSES, "required": True}, {"name": "Severity", "choices": SEVERITY_CLASSES, "required": True}, {"name": "Issue Class", "choices": ISSUE_CLASSES, "required": True}, {"name": "Flat", "choices": [(x.id, x.flat.name) for x in OperationsFlat.objects.all()], "required": True} ] } The error is: "name": "Flat", "choices": [(x.id, x.flat.name) for x in OperationsFlat.objects.all()], "required": True} TypeError: unhashable type: 'list' To my mind, although the level of nesting of the list has changed, python still needs to hash the list in the same way, so why does it work in the first form, but not in the second? More information: This is within a django rest framework APIView, the APIView's return returns a Response object with this object in … -
Sending webRTC video stream to server with django channels
I am trying to create a face detection web application written in django. The app works this way. The user navigates to the url The camera starts on the client machine Each frame is then sent to the server for face detection Processed frame is then displayed on the web page I understood I could not use opencv VideoCapture because, it only works on the server side. When I read online people asked me to use javascript and specifically webRTC to start live stream on the client side. So I found this tutorial which explains how to start webcam on the client machine with javascript. Now my question is how to send each frame from javascript on the client machine to opencv python on the server side? All this should happen in real time. So I cannot save the live video and then run the python code on the saved video. Some sites asked me to use AJAX to send data to the server side but I am not sure how to target each frame that is to be sent in the javascript code. This is my code so far CLIENT SIDE CAMERA ACCESS WITH webRTC <!DOCTYPE html> <html> <head> … -
mongoengine: invalid dictionary key name - keys may not contain . or $
I am trying to store a report using a Django model connected with MongoDB. models.py class Report(me.EmbeddedDocument): report = me.DictField() class ReportDocument(me.Document): report = me.EmbeddedDocumentField('Report') storing json def store_report(report): # report is json given in link above. rd = ReportDocument(report={"report": report}) rd.save() I am getting following error on rd.save() mongoengine.errors.ValidationError: ValidationError (ReportDocument:None) (report.Invalid dictionary key name - keys may not contain "." or "$" characters: ['report']) -
How to user VueJS variable in Django if else tag
I want to use VueJS variable in Django {% if %} tag. My vue have delimiters: ['${', '}']. Exactly what I want to do is: {% if django.variable == vue.variable %} ... {% endif %} How to do this? Thanks. -
how use annotation Instead loop on filter
i use a table Bid in this table have multi fields and a field named user other hand have a Dealer table that save users in Dealer_serializer i have a bids_count serializer Method Field that return each user count in Bid table i want use annotate instead of loop over filter! to get each user how many in Bid Table. if my idea not true explain me what exactly doing annotation? -
How to Pass Custom Values like Username or E-mail into SurveyMonkey
Working on Integrating a SurveyMonkey Survey into a website. How do I pass Username or Email of a Logged in User to the Survey? I am using an Embedded Survey. Any Documentation Links would be welcome. Also, Can I get real-time Response from SurveyMonkey to get the results after a user has finished the taking survey? I have a Paid Plan. Using Django to build the website. -
Programmaitically finding the data in django python django rest framework
I have 3 tables PC(ID, PcNAME, Brand), CellPhoness(ID, CellPhoneName, Brand), Printers(ID, PrinterName, Brand). there is no relationship between the 3 tables. I would like to run query where in the user can input the search string and the program would search the 3 models for where the data exists and return the same with the Id, name and brand in the form of a Json response.