Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decode resulting json and save into db - Django + Postgres
I have a model like this: class MyClass(models.Model): typea = models.CharField(max_length=128) typeb = models.CharField(max_length=128) If for example, the resulting json from an API is like this: { "count": 75, "results": [ { "typea": "This tipe", "typeb": "A B type", "jetsons": [], "data": [ "https://myurl.com/api/data/2/", ], "created": "2014-12-15T12:31:42.547000Z", "edited": "2017-04-19T10:56:06.685592Z", }, I need to parse this result and save typea and typeb into the database, I'm kind of confused on how to do this. I mean, there is the JSONField on Django, but I don't think that will work for me, since I need to save some specific nested string of the json dict. Any example or idea on how to achieve this? I mean, my confusion is on how to parse this and "extract" the data I need for my specific fields. Thank You -
I Develop a movie review project and the only problem that i cannot solve is how to redirect to the movie that i reviewed after deleting the review
How to redirect to the movie that I reviewed after deleting the review of that movie. I did try overriding get_success_url but the pk it will get is the pk of the review not the pk of the movie. example my url in my movie detail is /movie/1/ and the review id is 10 so if i return reverse('movie-detail', kwargs={'pk': self.object.pk}) after i delete the review it will redirect to the /movie/10 instead i want to redirect to /movie/1/ . I hope you get my point and you can help me. Thanks in advance :) views.py class PostDeleteView(DeleteView): model = Review template_name = 'reviews/post_confirmed_delete.html' def get_success_url(self): return reverse('movie-detail', kwargs={'pk': self.object.pk}) urls.py urlpatterns = [ path('', views.index, name='index'), path('movies/', views.movie_list, name='movie-list'), path('movies/', MovieListView.as_view(), name='movie-list'),#This is movie list path('movie/<int:pk>/', MovieDetailView.as_view(), name='movie-detail'),#every detail of movies path('movie/<int:pk>/review', PostCreateView.as_view(), name='post-create'),#adding review to a specific movie path('review/<int:pk>/', ReviewDetailView.as_view(), name='review-detail'),#every detail of every reviews path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), ] I expect that after I deleted the review, it will redirect to the movie detail that I reviewed. -
How to adjust two divs in views.py
I have made a loop in divs. First div is for first column and another div for second column. I just want it to manage in views.py. I made two functions in views.py for two separate divs. But it is not showing me the result of last function. It is just showing me the first function pics and only the first div is working. index.html {% static 'images/fulls' as baseUrl %} {% static 'images/thumbs' as hiUrl %} <div class="row"> {% for dest in dest1 %} <div class="col-lg-4"> <a href="{{baseUrl}}/{{dest.img}}"> <img src="{{hiUrl}}/{{dest.img}}" alt="" /> <h3>{{destt.desc}}</h3> </a> </div> {%endfor%} </div> {% for destt in dest2 %} <div> <a href="{{baseUrl}}/{{destt.img}}"> <img src="{{hiUrl}}/{{destt.img}}" alt="" /> <h3>{{destt.desc}}</h3> </a> </div> {% endfor %} def index(request): dest1 = Destination() dest1.desc = 'Hello, How arE you?' dest1.img = '01.jpg' return render(request, 'index.html', {'dest1':dest1}) def nextt(request): dest2 = Destination() dest2.desc = 'Hello, How arE you?' dest2.img = '02.jpg' return render(request, 'index.html', {'dest2':dest2}) -
How can I get url of images from browser in django view
What should I do to allow django to read the image url from browser? I'm learning to do a django app for getting dominant colors from images in grasshopper, so that the results could appear in rhino. which need to get images from browser. Images were downloaded in my PC could work , but not images from browser. Then I wonder if there is any python library could help with this problem? jsob = {"clusters": 5,"path": 0} if request.method == "POST": try: data = request.POST["data"] print(data) received = json.loads(str(data)) jsob.update(received) path = jsob.get("path") clusters = int(jsob.get("clusters")) dc = DominantColors(path, clusters) colors = dc.dominantColors().tolist() print(colors) print(type(colors)) results = {"colors":colors} return JsonResponse(results) except Exception as e: PASS -
How to upload image file in django related to a perticular user only
I'm trying to upload a file in django such that uploaded file is linked to a foreign key. i.e. if I upload a file then in database it should reflect that with which database subject it is related to This is my views.py file: def pod_upload (request, pk): lr_object = get_object_or_404(LR, id=pk) if request.method == 'POST': form = UploadPODform(request.POST, request.FILES) form.lr_connected = lr_object form.save() if form.is_valid(): form.lr_connected = lr_object form.save() return redirect('home') else: form = UploadPODform() form.lr_connected = lr_object return render(request, 'classroom/suppliers/model_form_upload.html', {'form': form}) This is my forms.py file: class UploadPODform(forms.ModelForm): class Meta: model = Uploaded_pod fields = ('document',) def __init__ (self, *args, **kwargs): super(UploadPODform, self).__init__(*args, **kwargs) # self.fields['lr_connected'].required = False This is my models.py file: class Uploaded_pod(models.Model): document = models.FileField(upload_to='pods/') lr_connected = models.ForeignKey(LR, on_delete=models.CASCADE, related_name='lr_pod') I expect that if some user upload a file then it must be saved with respect to the LR object. -
"Error occurred while reading WSGI handler" Problem in deploying a Django app on IIS
I am in the process of deploying a Django app in IIS. I have gone through this link https://www.mattwoodward.com/2016/07/23/running-a-django-application-on-windows-server-2012-with-iis/ and followed it step by step. But when I hosted my Django app named 'sample', other apps that were hosted on the IIS started showing the below error while browsing and to mention other apps were developed in different frameworks. Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb)) ValueError: "django.core.wsgi.get_wsgi_application()" could not be imported: Traceback (most recent call last): File "C:\virtualenvs\sample\Lib\site-packages\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File "C:\virtualenvs\sample\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "C:\virtualenvs\sample\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\virtualenvs\sample\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__ self._setup(name) File "C:\virtualenvs\sample\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\virtualenvs\sample\lib\site-packages\django\conf\__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, … -
I literally been stuck in this loop for days. edit/update can't detect the pk of the model?should i submit a ticket?
the error : .Reverse for 'patient_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['patients/update/(?P<pk>[0-9]+)$']? whenever i try calling the url in a template whether in action of a form tag or just a normal anchor. I made a view where users can edit the patients information and as I'm using a custom user model I had to make a custom update/delete view.The views are working when i enter them manually by the url but when i put a link reference to them by an anchor tag i get an error that it can't access the pk,I tried following many answers here and vids on YT but the error is still there Views.py def PatientUpdateView(request,pk=None): patient = get_object_or_404(models.Patient, pk=pk) form = forms.PatientForm(request.POST or None ,instance=patient) if form.is_valid() : patient = form.save(commit=False) patient.save() messages.success(request,"patient updated!") context = { 'patient': patient, 'form': form } return render(request,'patients/patient_edit_form_success.html',context) else: context = { 'patient' : patient, 'form': form, } return render(request, 'patients/patient_edit_form.html', context) and here's how i call it in an anchor tag <a class="btn btn-info btn-sm" href="{% url 'patients:patient_update' patient.pk %}">Open</a> I tried pk = patient.pk pk = pk pk={{ patient.pk}} and many other ways of calling it. urls.py here's the url … -
Drop Down group create and auto user add
The idea of my app is this. At the welcome screen the user has two options either register as a buyer or a seller. If the user decides to go for the simple buyer registration I'm going to use Django's built in sign up form for it but when the user signs up as a seller I want to create a group named "Owner" and their the user is automatically added and has a different dashboard according to their respective group. But this group gets created just once not on every view call. Please give me an idea to how can I achieve this. models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.models import Group from django.db import models from cities_light import models as CityModel from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import User class HallOwnerData(models.Model): owner_name = models.CharField( max_length=256) owner_address = models.CharField("Address",max_length = 256) owner_cnic = models.CharField("CNIC", max_length = 16) contact_number = PhoneNumberField() class HallProperties(models.Model): hall_name = models.CharField(max_length = 128) hall_city = models.ForeignKey(CityModel.City, max_length=512) hall = models.ForeignKey(HallOwnerData,on_delete = models.CASCADE) hall_address = models.CharField("Address", max_length = 128) hall_capacity = models.PositiveSmallIntegerField("Max Capacity") hall_number = PhoneNumberField() views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.http import HttpResponse from … -
Django Channels : Login to the session using consumer not working
I have a SPA built using django channels and Vue for frontend. The very first time user loads the webpage, the index.html is served using url(r'^.*$', TemplateView.as_view(template_name='index.html'), name="app") Then frontend communicates with the server using web socket. One of the messages sent could be to login into the system with appropriate credentials. I have been following instructions at https://channels.readthedocs.io/en/latest/topics/authentication.html to implement login through the consumer. class MyConsumer(AsyncJsonWebsocketConsumer): async def connect(self): self.group_name = str(uuid.uuid1()) print(self.scope['session'].session_key) self.user = self.scope["user"] # Join room group await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() # User data await self.send(simplejson.dumps(dict(data=dict(socketid=self.group_name, user=dict(username=self.user.username or None))))) async def receive_json(self, jsdata): kwargs = jsdata.get('kwargs', {}) # Manage Login if {{ message is intended for login }}: user = authenticate(**kwargs) await login(self.scope, user) print('Saving login session') await database_sync_to_async(self.scope["session"].save)() await self.send(simplejson.dumps(dict(data=dict(user=dict(username=user.username))))) print(self.scope['session'].session_key) return Everything works fine. I could see the seesion key being printed when user logs in. However, when I reload the web page, the session is not retained. It prints None in the connect method. I see the cookies are not getting set after the login is done. I expect the information that is sent from the server to client when the below line runs to set some cookies in the … -
How to use a variable inside a for loop while parsing through the database in Django?
i am trying to replace the {{ filter_term }} variable inside the loop so that if filter_term = " animal_type " then the statement should look like {{ tag.animal_type }} wherever i use it. How to do that? i have already tried the following statements - 1. {{ tag.{{ filter_term }} }} 2. {{ tag.filter_term }} 3. {% with filter_term as term %} {{ tag.term }} {% endwith %} in views,py: def filter(response): ... filter_term = request.GET['filter'] return ( request, 'home.html', { 'filter_term' = filter_term }) ( the above function is working and it returns filter_term as searched ) in home.html - {% for tag in unique %} option name="" value="/display/custom/?search={{ tag. }}">{{ tag. }} {% endfor %} if filter_term is animal _type then {{ tag. }} should look like {{ tag.animal_type }} but it doesn't show anything. -
Can I create a pop up window upon completion of uploading of files in django
I have some files that have large sizes that will be uploaded to http://127.0.0.1:8000/, so it will take some time. I was just wondering: how do I make a pop up window on upon completion in django? Will it be possible? Be it javascript or html? If it is possible, can anyone show and explain the codes to me? Thank you. -
How to adjust rows in columns in django?
I have made a loop in index.html and the pics which I added in views.html, whenever I run the code, all the pics appear in rows. I want it to be appear in columns. How could I do that? views.py def index(request): dest1 = Destination() dest1.desc = 'Hello, How are you?' dest1.img = '01.jpg' dest2 = Destination() dest2.desc = 'Hello, HOw are you?' dest2.img = '02.jpg' dests1 = [dest1, dest2] return render(request, 'index.html',{'dests1':dests1}) index.html {% static 'images/fulls' as baseUrl %} {% static 'images/thumbs' as hiUrl %} {% for dest1 in dests1 %} <div> <a href="{{baseUrl}}/{{dest1.img}}"> <img src="{{hiUrl}}/{{dest1.img}}" alt="" /> <h3>{{dest1.desc}}</h3> </a> </div> {%endfor%} -
How can I import module in external python script django
I have tried to include a python script in the project directory. I want to just run getoffense.py(under project1) and 3 scripts will be run indirectly upon executing getoffense.py. Those three scripts are SampleUtilities.py, RestApiClient.py and config.py.these 3 scripts are under "modules" When i am running this program seperately from django it is working perfectly however when i am using the module path the server gives me error about it. I have explained as better as i can please help as i am new to python and django. this is my project structure C:. ├───.idea └───project1 ├───modules ├───Templates └───__pycache__ I want to run these external python scripts and show the result on an html file. this is my getofense.py import json import os import sys import importlib sys.path.append(os.path.realpath('/modules')) client_module = importlib.import_module('/modules/RestApiClient') SampleUtilities = importlib.import_module('/modules/SampleUtilities') def main(): # First we have to create our client client = client_module.RestApiClient(version='9.0') # ------------------------------------------------------------------------- # Basic 'GET' # In this example we'll be using the GET endpoint of siem/offenses without # any parameters. This will print absolutely everything it can find, every # parameter of every offense. # Send in the request SampleUtilities.pretty_print_request(client, 'siem/offenses', 'GET') response = client.call_api('siem/offenses', 'GET') # Check if the success code … -
Django 2+ : Optional URL using PATH, without making multiple URL
i have this url path('<slug>/thank_you/<user_id>', thank_you, name='thank_you'), i want the <user_id> to be optional, but i dont want to make 2 urls like this path('<slug>/thank_you', thank_you, name='thank_you'), path('<slug>/thank_you/<user_id>', thank_you, name='thank_you2'), i understand that you can make it optional using regex, but thats if you're using django <2 (using url, not path) how do i obtain this ? -
How to copy a model in django with small differences in Meta using a function?
I have a Django project that has lots of models, and lots of relations. I have got a job to create a new model with different name and db_table meta using a function that has a parameter to model that will be copied. I should change ManyToMany and ForeignKey references to newly created/will created new models. I tried DynamicModels in Django with type(name, (models.Model,), attrs), but after some try 'is_relation' attribute error came into action. create_model function will be used to do this action. Class C(models.Model): q = models.CharField(max_length=20) def __str__(self): return self.q Class A(models.Model): x = models.CharField(max_length=20) y = models.DateTimeField(auto_now_add=True) Class B(models.Model): z = models.ForeignKey(A) t = models.ManyToManyField(C) w = models.DateTimeField(auto_now_add=True) def create_model(model): pass I have classes like this which I described in summary. I should create new classes like C1, A1, B1 with different db_table metas. Also, I should change ForeginKey and ManyToMany fields to A1 and C1. -
How can I give specific IP and port that my code requires
In django I am using python osc, using osc server which required IP address and Port no. to run. When I run that specific file on terminal I add the ip and port like: OSC.py --ip --port Now I want to implement this in django but don't know where to add ip and port -
When I deploy a website on a ubuntu server, I can't load image content that was uploaded locally?
1、The project image uses a local upload, so the image link stored in mysql is a link with the local service IP address, which synchronizes the data to the server's mysql data. When opening a website, the image link cannot be loaded because the address in the link cannot be accessed. Do you need to configure which files, can you correct the link correctly? (If the newly uploaded image on the website is loadable, because the service address of the image before the link is the server itself) Local project configuration: project # settings.py Path MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') 2、The images used in the local project are locally uploaded images, and the image links in mysql have local server addresses: Navicat mysql data 3、Use ubuntu_server to deploy the project on the virtual machine, server address: 192.168.164.128, server mysql file,use Navicat for local and server mysql data synchronization: Server mysql file 4、There are also pictures in the project path of the server, and the configuration of nginx: Server image nginx 5、When the project is last run, the image cannot be loaded on the website because the image is still a link with the local service IP address: error message … -
python django - Images are blank when written using decoded base64
My django website aims at allowing users to combine different clothing picture on one single canvas. However, the saved image is blank. I have applied one fiddle, please see here. I've used the methods recommended by some forums. Here is the views.py @csrf_protect @csrf_exempt def savewearingimg(request): imgEncodeString = request.POST.get('imgBase64') if request.method == 'POST' and request.is_ajax(): singleItemNames = request.POST.getlist('singleItemNames[]') saveWearingName = request.POST.get('saveWearingName') #string positionsX = request.POST.getlist('positionsX[]') positionsY = request.POST.getlist('positionsY[]') userWidths = request.POST.getlist('sizes[]') imgEncodeString = request.POST.get('imgBase64').partition(",")[2];//for header removing img64Data = base64.b64decode(imgEncodeString) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) preFileStr = os.path.join(BASE_DIR, "media\\photos\\wearing\\") poFileStr=str(request.user)+'_itemName_'+saveWearingName+'.jpg' filename = preFileStr +poFileStr with open(filename, 'wb') as f: f.write(img64Data) return render(request,'combinewearing.html') And here is part of the javascript combinewearing.js" $(function() { canvas = document.getElementById('save-canvas'); context = canvas.getContext('2d'); }); $('#saveWearingBtn').click(function(){ drawToSave(alreadyPutImg,originalWidths); }); function drawToSave(alreadyPutImg,originalWidths){ loadImagesMike(sources, function(images_) { //the original author is Mike for(var i=0; i<ImgPutArr.length; i++ ){ var img_iter = ImgPutArr[i]; context.drawImage(images_[i],0,0,img_iter.w,img_iter.h); context.drawImage(images_[i],img_iter.x,img_iter.y,img_iter.w,img_iter.h); console.log('images_[i]: '+images_[i] );//[object HTMLImageElement] i++; } }); var myDataURL = canvas.toDataURL(); $.ajax({ type: "POST", url: "/savewearingimg/", data: { 'csrfmiddlewaretoken': "{{ csrf_token }}", 'imgBase64': myDataURL, 'singleItemNames': alreadyPutName,//array storing what users have added to the canvas 'saveWearingName':$('#saveWearingName').val(), //end-users can customized his/her desired wearing title 'positionsX':positionsX, //position array storing every clothing pictures 'positionsY':positionsY, 'sizes':sizes, }, }).done(function(o) { alert('saved'); console.log('saved'); });/*end ajax*/ } function … -
Can Not create a new model and save it into the database. Djanog rest framework view model set
I have a django rest framework project. I am trying to build a view set that overrides the default create method for the ModelViewSet. Right now, I am grabbing all the data that I need to grab from the POSt request and url arguments. I am trying to store them in to a data object and then create a new object in the database based on that same data object. All the data is correct and setup in the object. How can i make the object savable. I am getting an error and I think it is coming from when I try to save. I am not sure though.... Model View Set - create method: @permission_classes((IsAuthenticated)) def create(self, request, *args, **kwargs): namespace = self.kwargs.get('namespace', None) path = self.kwargs.get('path', None) print(request.user) print(request.POST.get('version')) print(request.POST.get('namespace')) print(request.POST.get('path')) print(request.POST.get('value')) print(request.user.id) if namespace is None and path is None: return super().create(request) if namespace and path is None: data = { "person":request.user, 'version':request.Post.get('version'), 'value':request.Post.get('value'), 'user_id':request.user.id, } 'namespace':namespace, 'path':request.Post.get('path'), return super().create(data) if namespace and path: data = { "person":self.request.user, 'version':self.request.Post.get('version'), 'namespace':namespace, 'path':path, 'value':self.request.Post.get('value'), 'user_id':self.request.user.id, } return super().create(data) Model: from django.db import models from django.contrib.auth.models import User from owf_framework.people.models import Person class Preference(models.Model): id = models.BigAutoField(primary_key=True, null=False) version = … -
Problema na utilização do pyzbar em sistema com hospedagem compartilhada
Estou desenvolvendo um sistema web com Django 2.0.6 que em um dado momento, precisa fazer a leitura de uma imagem de um qrcode. Então, na minha máquina local utilizei o pyzbar na minha virtualenv para realizar tal necessidade e funcionou perfeitamente. Fiz a realização de diversos testes, e até então estava funcionando perfeitamente. Assim, tive a necessidade de hospedar o sistema em um servidor compartilhado(já tinha realizado tal procedimento para outro sistema web feito com Django 2.0.6), sendo que desta vez deu erro na hospedagem devido a biblioteca pyzbar, alegando que a biblioteca não estava devidamente instalada. Requisitei o suporte da empresa de hospedagem(hostgator) para verificar o problema e me foi dito o seguinte: "Verifiquei que o erro ao executar o indexWebScg.fcgi estava ocorrendo devido a falta de módulos instalados em seu vritualEnv, fiz a instalação dos módulos necessários, entretanto pude notar que um dos módulos de sua aplicação se trata do "zbar" esse módulo não é compatível com nossos planos compartilhados pois o mesmo exige uma biblioteca a nível de servidor chamada libzbar o qual não é padrão de nossos servidores compartilhados." A minha pergunta é, se tudo que eu preciso usar no sistema está instalado dentro da virtualenv … -
Creating new objects under specific parameters
I am new to django and trying to under the capabilities of django models. I stumbled across Model managers and understand that they can be used to perform customized queries and I understand how they serve that function. But what if I wanted to create a new object but under a specific set of guidelines. For example let's say I had a model as such: #models.py class TestModel(model.Model): num = models.IntegerField(default=5) Now if I create a new object without specifying the value of num it will set its default equal to 5. But is it possible to have a creation function within the model that would give it another value. For example what if I wanted the value to be a random number between 1 and 100. I know that I could always run that function and then set the num field equal to its output and then create the model, but I want to have that function run within the model and execute just by calling TestModel(). Is this possible? -
How to replace QueryDict to python dictionary with same key
I have a QueryDict from HttpRequest (request.POST) and I Have a new dictionary with same key. How can I insert or replace my new dictionary to QueryDict. any help will be appreciated. print(request.POST) <QueryDict: {'csrfmiddlewaretoken': ['FEWFDFdcgfgrthBFFBDFBDF'], 'form-TOTAL_FORMS': ['13'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-publish': ['05/28/2019'], 'form-0-cell': ['81'], 'form-0-cell_name': ['13a'], 'form-0-jam': ['07.00-08.00'], 'form-0-target': ['60'], 'form-0-model_name': [''], 'form-0-article_no': [''], 'form-0-input_qty': [''], 'form-0-cementing_qty': [''], 'form-0-perbaikan_qty': [''], 'form-0-b_grade_qty': [''], 'form-0-diff_manual_output': [''], 'form-0-scan_bungkus': [''], 'form-0-total_scan_bungkus': [''], 'form-0-manual_output_qty': [''], 'form-0-total_manual_output': [''], 'form-0-scan_pack_qty': ['10'], 'form-0-component_upper_qty': [''], 'form-0-total_scan_pack': [''], 'form-0-grand_total_qty': [''], 'form-0-diff_output_component_upper': [''], 'form-0-problem': [''], 'form-0-tot_prod_hours': [''], 'form-0-tot_prod_ot': [''], 'form-0-time_normal': [''], 'form-0-time_ot1': [''], 'form-0-time_ot2': [''], 'form-0-time_ot3': [''], 'form-1-publish': ['05/28/2019'], 'form-1-cell': ['81'], 'form-1-cell_name': ['13a'], 'form-1-jam': ['07.00-08.00'], 'form-1-target': ['60'], 'form-1-model_name': [''], 'form-1-article_no': [''], 'form-1-input_qty': [''], 'form-1-cementing_qty': [''], 'form-1-perbaikan_qty': [''], 'form-1-b_grade_qty': [''], 'form-1-diff_manual_output': [''], 'form-1-scan_bungkus': [''], 'form-1-total_scan_bungkus': [''], 'form-1-manual_output_qty': [''], 'form-1-total_manual_output': [''], 'form-1-scan_pack_qty': ['20'], 'form-1-component_upper_qty': [''], 'form-1-total_scan_pack': [''], 'form-1-grand_total_qty': [''], 'form-1-diff_output_component_upper': [''], 'form-1-problem': [''], 'form-1-tot_prod_hours': [''], 'form-1-tot_prod_ot': [''], 'form-1-time_normal': [''], 'form-1-time_ot1': [''], 'form-1-time_ot2': [''], 'form-1-time_ot3': [''], 'form-2-publish': ['05/28/2019'], 'form-2-cell': ['81'], 'form-2-cell_name': ['13a'], 'form-2-jam': ['07.00-08.00'], 'form-2-target': ['60'], 'form-2-model_name': [''], 'form-2-article_no': [''], 'form-2-input_qty': [''], 'form-2-cementing_qty': [''], 'form-2-perbaikan_qty': [''], 'form-2-b_grade_qty': [''], 'form-2-diff_manual_output': [''], 'form-2-scan_bungkus': [''], 'form-2-total_scan_bungkus': [''], 'form-2-manual_output_qty': [''], 'form-2-total_manual_output': [''], 'form-2-scan_pack_qty': ['10'], 'form-2-component_upper_qty': [''], 'form-2-total_scan_pack': [''], 'form-2-grand_total_qty': [''], 'form-2-diff_output_component_upper': [''], 'form-2-problem': [''], … -
PySpark as a runtime for Django instead of a regular python env?
Is it possible to use PySpark as a runtime for Django instead of a regular python environment? Since Django is just running Python tasks, could these tasks not be parallelized in Spark? Here in python3 manage.py shell_plus --notebook, I have imported pyspark and ran a query using the ORM. It runs clean. import findspark findspark.init() import pyspark import pyspark.sql sc = pyspark.SparkContext(appName="Django") patients = Patient.nodes.all() print(patients) sc.stop() [1]: #returned the data from my model I suppose this would work for Flask and Pyramid too? -
How to re-render a view in Django with an updated context from listener or callback function?
I've been trying hard to find a solution to this problem. My Django project uses Firebase Admin SDK. Everything works fine but I have a page view which has this piece of code in it def my_view(request): def on_snapshot(doc_snapshot, changes, read_time): print('Data changed!') return render(request, 'xxxxx.html', context) # 'db' is the Firestore object initialized using firebase admin SDK doc_ref = db.document(....) res = doc_ref.get().to_dict() doc_ref.on_snapshot(on_snapshot) context = { 'result': res, ......... ......... } return render(request, 'xxxxx.html', context) The problem is it works fine when the view is first loaded but when the data in the location of doc_ref is changed from the web browser in the Firebase console, the listener function on_snapshot gets called and the message Data changed! gets printed in the console but the return render(.....) never gets triggered. I don't know why this is not working, I've searched online for solutions, many of them are suggesting to use ajax. If the event is triggered by the user in the front-end then ajax is helpful, but in my case, the event is triggered by the listener function. Please help me to get through this. What I want to have realtime updates on my front-end. But this is not … -
django FloatField - how do I retrieve the value
I have a model made like this class SnpsPfm(models.Model): snpid = models.ForeignKey(Snps, models.DO_NOTHING, db_column='SNPID', primary_key=True) # Field name made lowercase. pfmid = models.ForeignKey(Pfm, models.DO_NOTHING, db_column='PFMID') # Field name made lowercase. start = models.PositiveIntegerField() strand = models.PositiveIntegerField() type = models.CharField(max_length=8) scoreref = models.FloatField(db_column='scoreRef', blank=True, null=True) # Field name made lowercase. scorealt = models.FloatField(db_column='scoreALT', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'SNPs_PFM' unique_together = (('snpid', 'pfmid', 'start', 'strand'),) def __str__(self): return str(self.snpid + self.pfmid + self.start + self.strand) And i need to do this operation a = SnpsPfm.objects.filter(snpid=qset[0]) score = a[k].scorealt - a[k].scoreref Problem is that it won't let me do that giving me could not convert string to float: 'ARNTL.SwissRegulon I tried to cast them as float but it's obviously not the solution. I even tried to add def __float__(self): return float(self.scoreref) to SnpsPfm but still won't work