Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create a django model form that will dyanamically render fileds by counting specific models atrribute
I am new to Django, I want to create a model and a model forms where it has three field tow of them are specified and one of them will create dynamically. This dynamic filed can be multiple inputs filed(integer).Further understand you can see this video. My Code For This models.py class SubjectCombination(models.Model): get_class_name = models.CharField(max_length=20) get_subject_name = models.CharField(max_length=20) class Result(models.Model): class_name = models.CharField(max_length=20) student_name = models.CharField(max_length=20) marks = # here i want to get dyanamic filed for all subjects in SubjectCombination model. forms.py class SubjectCombinationForm(forms.ModelForm): class Meta: model = SubjectCombination fields = '__all__' class ResultForm(forms.ModelForm): class_name = forms.CharField(required=True) student_name = forms.CharField(required=True) marks = # What Shoud i write here ? views.py def add_result(request): sbjcmb = SubjectCombination.objects.order_by('id') students = Student.objects.order_by('id') if request.method == 'POST': resultForm = ResultForm(request.POST) for data in resultForm: print(data) else: resultForm = ResultForm context = {'subcom':sbjcmb, 'students':students, 'form':resultForm} return render(request, 'add-result.html', context) HTML Template <form class="form-horizontal" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-group"> <label for="{{ form.class_name.id_for_label }}" class="col-sm-2 control-label">Class</label> <div class="col-sm-10"> <select name="{{ form.class_name.name }}" class="form-control clid" id="{{ form.class_name.id_for_input }}" onChange="getStudent(this.value);" required="required" > <option value="">Select Class</option> {% for class in subcom %} <option value="{{ class.get_class_name }}">{{ class.get_class_name }}</option> {% endfor %} </select> </div> </div> <div … -
Celery/Django is running task trying to run when timezone has been set
I am running into the issue that, when using a timezone inside my celery.py tasks run every chance it gets, thus running not according to schedule. This is the output: scheduler_1 | [2018-11-29 11:00:09,186: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,199: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,204: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,210: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,220: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,228: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,231: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,236: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,239: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,247: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,250: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) My celery.py: import os from celery import Celery from celery.schedules import crontab from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") # app = Celery('biko') task_apps = [ 'biko.supplier.tasks', 'biko.common.tasks', 'biko.commerce.tasks', 'biko.shop.tasks' ] app = Celery('biko', include=task_apps) app.config_from_object('django.conf:settings') app.conf.timezone = 'Europe/Amsterdam' app.autodiscover_tasks() app.conf.ONCE = { 'backend': 'celery_once.backends.Redis', 'settings': { 'url': 'redis://' + … -
Configure IIS to Serve Django Applications
I'm trying to publish a Django web application (created with Python 2.7.15) via IIS. First of all I installed the application: :: setup folders mkdir C:\Software\MyApp\ cd C:\Software\MyApp\ :: clone the git Repository git clone https://gitlab.com/blablabla.git C:\Software\MyApp\MyAppServer :: create the virtualenv python -m pip install --upgrade pip pip install virtualenv virtualenv py2_env call py2_env\Scripts\activate.bat :: install the python-requirements in the virtualenv pip install -r C:\Software\MyApp\MyAppServer\requirements.txt :: copy all static files in C:\var\www python C:\Software\MyApp\MyAppServer\manage.py collectstatic :: just to check if the app works (and it works!) python C:\Software\MyApp\MyAppServer\manage.py runserver At this point, my folders organization is: C:\ └── Software\ └── MyApp\ ├── py2_env\ │ ├── Include\ │ ├── Lib\ │ ├── Scripts\ │ └── tcl\ └── MyAppServer\ ├── manage.py ├── ... └── myapp_django_server\ ├── urls.py ├── wsgi.py └── ... And the packages installed in my py2_env virtual env are: (py2_env) C:\Software\MyApp\py2_env\Scripts>pip freeze --local Django==1.11.2 djangorestframework==3.6.3 numpy==1.12.1 pytz==2018.7 wfastcgi==3.0.0 At this point I configure IIS following this guide (I jumped to the Configure IIS to Serve Django Applications chapter) but, at the end, if I browse to http://localhost:81 I get this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Software\MyApp\py2_env\Lib\site-packages\wfastcgi.py", line 791, in main env, handler … -
How to check input username and password match with postgres database in login page?
I have a user login page with code below: {% extends "base_generic.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %} I have a table named user in postgres database with username and password field.Here is my model: class User(models.Model): name = models.CharField(db_column='Name', max_length=100) password = models.CharField(db_column='Passwd', max_length=30, ) class Meta: db_table = 'User' How can i check the input username and password whether is match with the table 'user'? -
Looking for Django equivalent of Flask's request.get_data() (for Slack request verification with raw request body)
I need equivalent of Flask's request.get_data() for Django / DRF. Got it almost working with str.encode(json.dumps(request.data)), but the output contains spaces between pairs key: value and existing link's signs are not escaped. Flask output (that works for me): b'{"token":"xxxx","team_id":"TDB6U9XM1","api_app_id":"yyyyyy","event":{"type":"link_shared","user":"UDC5TRW0M","channel":"CE9GC5C4R","message_ts":"1543451681.002600","links":[{"url":"http:\\/\\/testing.serv-dev.pl\\/viewer\\/3\\/24","domain":"serv-dev.pl"}]},"type":"event_callback","event_id":"EvEE40NTSM","event_time":1543451682,"authed_users":["UDC5TRW0M"]}' Current Django output: b{"token": "xxxx", "team_id": "TDB6U9XM1", "api_app_id": "yyyyyy", "event": {"type": "link_shared", "user": "UDC5TRW0M", "channel": "CE9GC5C4R", "message_ts": "1543452606.003600", "links": [{"url": "http://testing.serv-dev.pl/viewer/3/24", "domain": "serv-dev.pl"}]}, "type": "event_callback", "event_id": "EvEENV65TU", "event_time": 1543452607, "authed_users": ["UDC5TRW0M"]}'. This is specifically for slack request signature verification that specifically requires raw request body to be passed. Accessing request.body throws an error django.http.request.RawPostDataException: You cannot access body after reading from request's data stream probably due to POST method. -
Why it's not working? What should be done to make the user login work?
Tried many ways but still not working. How to make this work? class LoginView(View): templates = "#/signin.html" context = ModelUser.objects.all() def get(self, *agrs, **kwargs): return render(self.request, self.templates, {'context' : self.context}) def post(self, *args, **kwargs): login = ModelUser() if self.request.method == 'POST': if self.request.POST.get('username') and self.request.POST.get('password'): login.username = self.request.POST.get('username') login.password = self.request.POST.get('password') for verify in self.context: if self.context.filter(username=self.request.POST.get('username')).exist() and self.context.filter(password=self.request.POST.get('password')).exist(): return HttpResponse('You are logged in') else: return HttpResponse('Error password or username') -
How to search django queryset without connect db
How to search django queryset without connect db. I am sorry, my English is not good. Example: items_list = Items.object.all() Items.object.filter(pk=1).delete() items_list.filter(pk=1) # result is None for item in items_list: # I do not want to get a new queryset like this if item.id == 1: new_items_list= item -
Make a prediction on the selected rows in the HTML table using the Django techniques
From an HTML Data table as the one below, I would like for each row selected via a checkbox make a prediction using SVM classifier. Before, I used the same classifier to predict all the dataset containing in CSV file. Now, I want to make the same prediction on only selected rows in the HTML table. Below is my SVM code to make the prediction. import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.svm import SVC from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn import metrics #Loading dataset train=pd.read_csv('Data.csv') features_col=['Changed_file','Num_commits_before_Closed','Num_lines_added','Num_lines_deleted'] X=train[features_col].dropna() y=train.classes test_size=0.4 #could also specify train_size=0.7 instead random_state=0 #train_test_split convenience function X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=random_state,test_size=test_size) clf = SVC(probability=True, random_state=5) clf=clf.fit(X_train,y_train) y_pred=clf.predict(X_test) #Confusion matrix print(confusion_matrix(y_test,y_pred)) #Print the classification report from sklearn.metrics import classification_report print (classification_report(y_test,y_pred)) -
Django creating model instances(?), newbie
I'm learning some django basics and I have question about models. class album(models.Model): name = models.CharField(max_length=30) datecreated = models.DateTimeField(auto_now_add=True, blank=True) email = models.EmailField() class photo(models.Model): pic_url = models.TextField(default="http://some.url/pic.png") name = models.DateTimeField(auto_now_add=True, blank=True) When creating new album I would like it to have 1000 photos with default picture. Is that possible? How? Thanks! -
Raise validation error in inline field Django
I have a model that contains a TabularInline, and I want to raise a validation error when a condition is not valid. My parent model: @admin.register(Even) class EventAdmin(admin.ModelAdmin): list_display = ['id', 'title'] list_display_links = ['id', 'title] inlines = [EventSpecialPriceInline] And my TabularInline: class EventSpecialPriceInline(admin.TabularInline): model = EventSpecialPrice extra = 0 can_delete = True The error I want to raise is when a price of a row is negative EventSpecialPrice.price < 0 -
curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused
I try to run this command on pycharm terminal: curl -X POST -d "username=admin&password=123" http://127.0.0.1:8000/ap i-token-auth/ But I get this error: curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused I searched internet but there is no good solution for it -
Django, How do have Post details and a comment form with comments on the same page?
I am trying to have a Post description and an ability to add comments below on the same page. What i have written feels like it should work, i just dont know what im missing. Currently everything works except for the add comment form, it wont display on screen and says Method Post Failed. My issue is somewhere in my 2 views that appear on my detail.html page. The details of the post, and then the partial New Comment form below it. Views.py from django.shortcuts ... ... import NewPostForm class IndexView(ListView): ... class Detail(DetailView): model = Post template_name = 'posts/detail.html' class CommentView(TemplateView): model = Post template_name = 'posts/detail.html' def post(self, request): commentform = AddCommentForm(request.POST) if request.user.is_authenticated: if commentform.is_valid(): comment = commentform.save(commit=False) comment.comment_user = request.user comment.save() comment.comment_date = timezone.now() comment.comment_title = commentform.cleaned_data['comment_text'] commentform = AddCommentForm() args = {'commentform': commentform,} return render(request, self.template_name, args) class NewPostView(TemplateView): ... And My Model that it uses Model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User import datetime # Create your models here. TYPE_CHOICES = ( ) class Post(models.Model): post_title = models.CharField(max_length=100, default="") post_text = models.CharField(max_length=2500, default="") post_user = models.ForeignKey(User,on_delete=models.CASCADE) pub_date = models.DateTimeField('Date Posted') post_type = models.CharField(max_length=1, choices = TYPE_CHOICES, default="M") def … -
AttributeError: 'ModelFormOptions' object has no attribute 'private_fields'
I get this error when trying to create a custom Form on the Admin view, I don't see any solution on stackoverflow (yes similar problems) so I think it's a good idea to post it: My Models.py: class Webhook(models.Model): url = models.CharField('URL', max_length = 60, unique = True) description = models.CharField('Descripcion', max_length = 255) enabled = models.BooleanField('Enabled', default=True) event = models.CharField('Evento', max_length=1, choices=Events.EVENTS_CHOICES) My Forms: class WebhookForm(forms.ModelForm): class Meta: model = Webhook fields = '__all__' def save(self, commit=True): print('saveeeeeee') webhook = super().save(commit=False) webhook.code = webhook.id # Get token response_token = TOKEN.get() if response_token['success']: # Create Webhook url = 'https://sandbox.bind.com.ar/v1/webhooks' headers = { 'Content-type': 'application/json', 'Authorization': 'JWT ' + response_token['token'] } data = { 'url': webhook.url, # Debera responder status_code == 200 'description': webhook.description, 'code': webhook.id, 'enabled': webhook.enabled, 'events': webhook.event } data_json = json.dumps(data) response = requests.put(url, data= data_json, headers = headers) response_json = response.json() # Result result = {} if response.status_code == 409: result['success'] = False result['details'] = response_json else: result['success'] = True result['data'] = response_json # If ok, Save if commit & result['success']: webhook.save() return result['success'] My Admin.py class WebhookAdmin(forms.ModelForm): # Only to override a form in admin class Meta: model = WebhookForm fields = '__all__' # Style to … -
How to create a repeating generic field on a Django model that does not render entries from other objects in the admin?
I'm fairly new to Django, but wondering how to get one seemingly obvious thing to work in my model definitions. For a model "Product" I want to be able to add any number of links, so I made a more or less generic "Link" model with a display name field and a URL field. In Product I add this as ManyToManyField with the respective Link model. This works like intended in the admin view in that I can add any number of links and do so inline. However, I only want the admin view to list existing links of this product, let the user delete them, and let the user add new ones. What I do not want is for the inline link field to display all other product’s links. Am I confused with the Field Type or overall approach, or how can I get this to work? I was wondering if the through options is the way to do this, or if this is merely something you should do in the admin forms and not on model level? -
how to call two functions at a time in django ,
how to call two functions at a time in Django ,in which one function takes many minutes to executes and one functions takes fraction of seconds to executes but 2nd function which takes less minutes needs to be updated in the html page dynamically until the first function completes -
give template tags inside jquery prepend function
my jquery: else if(json.event == "Follow Notify"){ console.log(json.sender) $("#not").prepend('<li class="media">'+ '<a href="javascript:;">'+ '<div class="media-left">'+ '<i class="fa fa-bug media-object bg- silver-darker"></i>'+ '</div>'+ '<div class="media-body">'+ '<h6 class="media- heading">'+json.notification'+ '<i class="fa fa-exclamation-circle text- danger"></i></h6>'+ '<p>'+json.notification+'</p>'+ '<a href="{% url "student:accept_follow" pk=request.user.id notify='+json.sender+' %}">Accept</a>'+ '<a href="{% url "student:reject_follow" pk=request.user.id notify='+json.sender+' %}">Reject</a>'+ '</div></a></li>') } I want to prepend html code with django url tags ..Im receiving a json and parsing it with json.sender..but it seems its taking it as a string .HOw do i propelry allow django template tags inside this jquery function? -
Python Django 2 template blocks overriding is not working
I'm working on a Python(3.6) and django(2.0) project in which I need to implement multiple templates with inheritance. Here are my templates: The first template is: dashboard-base.html: {% block header %} // Header content like loading css and js files along with title {% endblock%} {% block body %} {% block dashboard_header %} Load dashboard specific header here - some html {% endblock %} {% block navbar %} Load dashboard specific navbar {% endblock %} {% block content %} Will load dynamic content here {% endblock %} {% block footer %} Footer content will go here {% endblock %} {% endblock %} Now I need to load the dynamic content in multiple templates like profile.html and dashboard-personal-info.html. Here's how I have inherited this templates: from profile.html: {% extends 'Utechdata/dashboard-base.html' %} {% block content %} <div class="mdl-grid demo-content"> <h1> This is the another content</h1> </div> {% endblock %} from dashboard-personal-info.html: {% extends 'Utechdata/dashboard-base.html' %} {% block content %} <div class="mdl-grid demo-content"> <h1> This is the another 2nd content</h1> </div> {% endblock %} But in these templates, the content inside the content block is not displaying. what can wrong here? Thank You, -
how to implement Response from flask in Django
I am trying to implement this project using django. What I want to do is once the server is started, I should be able to start the camera from any system that is connected to network and display the feed in that system. I am using Django because I have written other modules of my project with django This is my code so far views.py def index(request): return render(request, 'index.html') # the gen() is part of the server.py code. This has to be added to the start_server() function. # the start_server() function should be rectified def gen(): streamer = Streamer('localhost', 8000) streamer.start() while True: if streamer.client_connected(): yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + streamer.get_jpeg() + b'\r\n\r\n') def start_server(request): return render_to_response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') def start_client(request): cap = cv2.VideoCapture(0) clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) clientsocket.connect(('localhost',8000)) while(cap.isOpened()): ret,frame=cap.read() memfile = StringIO() np.save(memfile, frame) memfile.seek(0) data = json.dumps(memfile.read().decode('latin-1')) clientsocket.sendall(struct.pack("L", len(data))+data) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.imshow('frame', frame) cap.release() The client.py file from the repo is placed under start_client() function in views.py I have made a small change to the client.py file from the repo. I added cv2.imshow('frame', frame) to display the feed in the client's system index.html <html> <head> </head> <body> <div class='container'> <a href='/start_server'><button>Start Server</button></a> <a href='/start_client'><button>Start Client</button></a> … -
Django ORM bulk_create 1:1 related models
I've seen similar questions asked, but vague answers were provided so I would appreciate any feedback. I want to do a bulk create on some related 1:1 objects. I was hoping I could do something like this: class A(models.Model): class B(models.Model): A = models.ForeignKey(A) all_a = [] all_b = [] for i in range(10000): new_a = A() new_b = B(A=new_a) all_a.append(new_a) all_b.append(new_b) with transaction.atomic(): A.objects.bulk_create(all_a) B.objects.bulk_create(all_b) But I'm guessing the A models need to be written to the DB and the actual PK returned and associated with B models before I can write them. Has anyone got a good suggestion on how to do this efficiently? Thanks in advance -
button click event inside bootstrap not work
I use nested modal. when I open main modal for first time it works well but for next time it's button doe'st work. there are multiple button in main modal that lunch other modals. here is main modal <form method="post" action="{% url 'wo_update' form.instance.id %}" class="js-wo-update-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" id="closeCompanyModal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">ویرایش</h4> </div> <div class="modal-body"> {% include 'cmms/maintenance/partialWoForm.html' %} </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">بستن</button> <button type="submit" class="btn btn-primary">ویرایش</button> </div> </form> and here is one the nested modal inside main modal. for first time buttom work well after reopen the main modal below buttom not work. <!--pip install django-widget-tweaks--> <div class="row"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>فعالیت ها </h5> </div> <div class="ibox-content"> <div class="table-responsive"> <table class="table table-striped" id="task-table"> <thead> <tr> <th></th> <th></th> <th>شرح</th> <th>کاربر مشخص شده</th> <th>زمان تخمینی</th> <th>زمان واقعی صرف شده</th> <th></th> </tr> </thead> <tbody id='tbody_task'> {% include 'cmms/tasks/partialTasklist.html' %} </tbody> </table> <!-- BUTTON TO TRIGGER THE ACTION --> <p> <button type="button" class="btn btn-primary js-create-task" data-url="{% url 'task_create' %}" > <span class="glyphicon glyphicon-plus" ></span> جدید </button> </p> </div> </div> </div> </div> <div class="modal fade" id="modal-task"> <div class="modal-dialog "> <div class="modal-content "> </div> </div> </div> </div> … -
ValueError: underlying buffer has been detached when i run python manager.py makemigrations
error 1 when i run python manager.py makemigrations , the problem as the picture. i check the django source code, find the problem code at here picture 2, it can work when i note this line:self._out.write(style_func(msg)). I don't know how make this problem. django source code -
How to use dot as thousand separator in Django
In my settings.py I have following code: LANGUAGE_CODE = 'en' USE_I18N = True USE_L10N = True USE_DECIMAL_SEPARATOR = True DECIMAL_SEPARATOR = "," USE_THOUSAND_SEPARATOR = True THOUSAND_SEPARATOR = "." And in my template I use the number as follows: {% load humanize %} {% load i18n %} {% load l10n %} <div>{% trans "Price" %}: € <b>{{ payment|floatformat:2|intcomma }}</b></div> But still the number is 18,300.00 and I want that it is 18.300,00. Any idea? -
Can't get user info getting error like "unauthorized_client
Error: Description KeycloakAuthenticationError at 401: b'{"error":"unauthorized_client","error_description":"Client certificate missing, or its thumbprint and one in the refresh token did NOT match"}' Please refer my code get solution # Configure client keycloak_openid = KeycloakOpenID(server_url="http://localhost:8080/auth/", client_id="testclient1", realm_name="Realm", client_secret_key="******") token = keycloak_openid.token("kishore", "Kichakcb001@") print(token) userinfo = keycloak_openid.userinfo(token['access_token']) print(userinfo) Thanks, Kishore -
django performance is slow
enter image description here I has a performance question.look this image,total time is 231MS,but response time is 1255,every requests has more than about 800ms duration between response and cpu total time.where's consume these times? -
Django Channels Unit Test
I'm working on a project which makes use of Javascript and Python so I'm using sockets for communication. I'm having issues writing tests for the django channels part. I have this python celery task @task(name="export_to_caffe", bind=True) def export_caffe_prototxt(self, net, net_name, reply_channel): net = yaml.safe_load(net) if net_name == '': net_name = 'Net' try: prototxt, input_dim = json_to_prototxt(net, net_name) randomId = datetime.now().strftime('%Y%m%d%H%M%S')+randomword(5) with open(BASE_DIR + '/media/' + randomId + '.prototxt', 'w+') as f: f.write(prototxt) Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'success', 'action': 'ExportNet', 'name': randomId + '.prototxt', 'url': '/media/' + randomId + '.prototxt' }) }) except: Channel(reply_channel).send({ 'text': json.dumps({ 'result': 'error', 'action': 'ExportNet', 'error': str(sys.exc_info()[1]) }) }) The javascript which sends net to the socket. exportNet(framework) { this.exportPrep(function(netData) { Object.keys(netData).forEach(layerId => { delete netData[layerId].state; if (netData[layerId]['comments']) { // not adding comments as part of export parameters of net delete netData[layerId].comments; } }); console.log("Net: "+JSON.stringify(netData)); this.sendSocketMessage({ framework: framework, net: JSON.stringify(netData), action: 'ExportNet', net_name: this.state.net_name, randomId: this.state.randomId }); }.bind(this)); } Now I'm trying to write tests for these. import unittest from celery import Celery from ide.tasks import export_caffe_prototxt from channels import Channel class TestExportCaffePrototxt(unittest.TestCase): def test_task(self): net = '{"l36":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l35"],"output":["l37"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l36"}},"l37":{"info":{"phase":null,"type":"Dropout","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l36"],"output":["l38"]},"params":{"caffe":true,"rate":0.5,"trainable":false,"seed":42,"inplace":true},"props":{"name":"l37"}},"l34":{"info":{"phase":null,"type":"Dropout","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l33"],"output":["l35"]},"params":{"caffe":true,"rate":0.5,"trainable":false,"seed":42,"inplace":true},"props":{"name":"l34"}},"l35":{"info":{"phase":null,"type":"InnerProduct","parameters":16781312},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l34"],"output":["l36"]},"params":{"bias_filler":"constant","bias_regularizer":"None","kernel_constraint":"None","bias_constraint":"None","activity_regularizer":"None","num_output":4096,"weight_filler":"constant","kernel_regularizer":"None","caffe":true,"use_bias":true},"props":{"name":"l35"}},"l32":{"info":{"phase":null,"type":"InnerProduct","parameters":102764544},"shape":{"input":[512,7,7],"output":[4096]},"connection":{"input":["l31"],"output":["l33"]},"params":{"bias_filler":"constant","bias_regularizer":"None","kernel_constraint":"None","bias_constraint":"None","activity_regularizer":"None","num_output":4096,"weight_filler":"constant","kernel_regularizer":"None","caffe":true,"use_bias":true},"props":{"name":"l32"}},"l33":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[4096],"output":[4096]},"connection":{"input":["l32"],"output":["l34"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l33"}},"l30":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l29"],"output":["l31"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l30"}},"l31":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[512,14,14],"output":[512,7,7]},"connection":{"input":["l30"],"output":["l32"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l31"}},"l38":{"info":{"phase":null,"type":"InnerProduct","parameters":4097000},"shape":{"input":[4096],"output":[1000]},"connection":{"input":["l37"],"output":["l39"]},"params":{"bias_filler":"constant","bias_regularizer":"None","kernel_constraint":"None","bias_constraint":"None","activity_regularizer":"None","num_output":1000,"weight_filler":"constant","kernel_regularizer":"None","caffe":true,"use_bias":true},"props":{"name":"l38"}},"l39":{"info":{"phase":null,"type":"Softmax","parameters":0},"shape":{"input":[1000],"output":[1000]},"connection":{"input":["l38"],"output":[]},"params":{"caffe":true},"props":{"name":"l39"}},"l18":{"info":{"phase":null,"type":"Convolution","parameters":1180160},"shape":{"input":[256,28,28],"output":[512,28,28]},"connection":{"input":["l17"],"output":["l19"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l18"}},"l19":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l18"],"output":["l20"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l19"}},"l14":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l13"],"output":["l15"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l14"}},"l15":{"info":{"phase":null,"type":"Convolution","parameters":590080},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l14"],"output":["l16"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":256,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l15"}},"l16":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l15"],"output":["l17"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l16"}},"l17":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[256,56,56],"output":[256,28,28]},"connection":{"input":["l16"],"output":["l18"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l17"}},"l10":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[128,112,112],"output":[128,56,56]},"connection":{"input":["l9"],"output":["l11"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l10"}},"l11":{"info":{"phase":null,"type":"Convolution","parameters":295168},"shape":{"input":[128,56,56],"output":[256,56,56]},"connection":{"input":["l10"],"output":["l12"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":256,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l11"}},"l12":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l11"],"output":["l13"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l12"}},"l13":{"info":{"phase":null,"type":"Convolution","parameters":590080},"shape":{"input":[256,56,56],"output":[256,56,56]},"connection":{"input":["l12"],"output":["l14"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":256,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l13"}},"l21":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l20"],"output":["l22"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l21"}},"l20":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l19"],"output":["l21"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l20"}},"l23":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l22"],"output":["l24"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l23"}},"l22":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,28,28],"output":[512,28,28]},"connection":{"input":["l21"],"output":["l23"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l22"}},"l25":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l24"],"output":["l26"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l25"}},"l24":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[512,28,28],"output":[512,14,14]},"connection":{"input":["l23"],"output":["l25"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l24"}},"l27":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l26"],"output":["l28"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l27"}},"l26":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l25"],"output":["l27"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l26"}},"l29":{"info":{"phase":null,"type":"Convolution","parameters":2359808},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l28"],"output":["l30"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":512,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l29"}},"l28":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[512,14,14],"output":[512,14,14]},"connection":{"input":["l27"],"output":["l29"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l28"}},"l6":{"info":{"phase":null,"type":"Convolution","parameters":73856},"shape":{"input":[64,112,112],"output":[128,112,112]},"connection":{"input":["l5"],"output":["l7"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":128,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l6"}},"l7":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[128,112,112],"output":[128,112,112]},"connection":{"input":["l6"],"output":["l8"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l7"}},"l4":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[64,224,224],"output":[64,224,224]},"connection":{"input":["l3"],"output":["l5"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l4"}},"l5":{"info":{"phase":null,"type":"Pooling","parameters":0},"shape":{"input":[64,224,224],"output":[64,112,112]},"connection":{"input":["l4"],"output":["l6"]},"params":{"layer_type":"2D","kernel_w":2,"stride_d":1,"pad_h":0,"stride_h":2,"pad_d":0,"padding":"SAME","stride_w":2,"kernel_d":"","caffe":true,"kernel_h":2,"pad_w":0,"pool":"MAX"},"props":{"name":"l5"}},"l2":{"info":{"phase":null,"type":"ReLU","parameters":0,"class":""},"shape":{"input":[64,224,224],"output":[64,224,224]},"connection":{"input":["l1"],"output":["l3"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l2"}},"l3":{"info":{"phase":null,"type":"Convolution","parameters":36928},"shape":{"input":[64,224,224],"output":[64,224,224]},"connection":{"input":["l2"],"output":["l4"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":64,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l3"}},"l0":{"info":{"phase":null,"type":"Input","parameters":0,"class":"hover"},"shape":{"input":[],"output":[3,224,224]},"connection":{"input":[],"output":["l1"]},"params":{"dim":"10, 3, 224, 224","caffe":true},"props":{"name":"l0"}},"l1":{"info":{"phase":null,"type":"Convolution","parameters":1792,"class":""},"shape":{"input":[3,224,224],"output":[64,224,224]},"connection":{"input":["l0"],"output":["l2"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":64,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l1"}},"l8":{"info":{"phase":null,"type":"Convolution","parameters":147584},"shape":{"input":[128,112,112],"output":[128,112,112]},"connection":{"input":["l7"],"output":["l9"]},"params":{"layer_type":"2D","stride_d":1,"pad_h":1,"kernel_constraint":"None","activity_regularizer":"None","stride_h":1,"pad_d":0,"weight_filler":"constant","stride_w":1,"dilation_d":1,"use_bias":true,"pad_w":1,"kernel_w":3,"bias_filler":"constant","bias_regularizer":"None","bias_constraint":"None","dilation_w":1,"num_output":128,"kernel_d":"","caffe":true,"dilation_h":1,"kernel_regularizer":"None","kernel_h":3},"props":{"name":"l8"}},"l9":{"info":{"phase":null,"type":"ReLU","parameters":0},"shape":{"input":[128,112,112],"output":[128,112,112]},"connection":{"input":["l8"],"output":["l10"]},"params":{"negative_slope":0,"caffe":true,"inplace":true},"props":{"name":"l9"}}}' net_name = "Sample Net" reply_channel = "TestChannel" task = export_caffe_prototxt.delay(net, net_name, reply_channel) response = …