Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Zero Downtime Code Update for Django App
Things being used: Supervisor to run uwsgi uwsgi to bring up my Django non-rel 1.6 based ML app (Django Upgrade in process) I am using Uwsgi to start my Django ML based app. But somehow as it has to load a lot of binaries for initialization, it takes about 20-30 seconds for supervisor to restart and load new code. How can I reduce this time? or is there any other way to run the Django app so as to reload quickly when code changes? With ZERO downtime? as Nginx will start throwing 5xx if it can't connect to Django. -
query an object using uuid in django
I am using uuid for creating an id field which is primary key as below import uuid class User_Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) So whenever we save an object into the database it was saving as an UUID instance instead of string as below user_profiles = User_Profile.objects.values_list('id', flat=True) print user_profiles [UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')] now how to query it by using django ORM ? since it was not saving as a string i can't able to fetch it as below and getting an error user_profile = User_Profile.objects.get(id='193b6acc-2b78-4ddc-9ef8-632cde33ef74') error: ValueError: invalid literal for int() with base 10: '193b6acc-2b78-4ddc-9ef8-632cde33ef74' when i recieved this uuid as string from query params in Django, i also tried by converting it in to uuid from string as below and i got the error import uuid id = uuid.UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74') user_profile = User_Profile.objects.get(id=id) error: ProgrammingError: operator does not exist: uuid = numeric LINE 1: ...ifications" FROM "tc_user_profile" WHERE "tc_user_profile"."id" = 33539211... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. So finally how to query a uuid id field from django database ? -
query an object using uuid in django
I am using uuid for creating an id field which is primary key as below import uuid class User_Profile(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) So whenever we save an object into the database it was saving as an UUID instance instead of string as below user_profiles = User_Profile.objects.values_list('id', flat=True) print user_profiles [UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74')] now how to query it by using django ORM ? since it was not saving as a string i can't able to fetch it as below and getting an error user_profile = User_Profile.objects.get(id='193b6acc-2b78-4ddc-9ef8-632cde33ef74') error: ValueError: invalid literal for int() with base 10: '193b6acc-2b78-4ddc-9ef8-632cde33ef74' when i recieved this uuid as string from query params in Django, i also tried by converting it in to uuid from string as below and i got the error import uuid id = uuid.UUID('193b6acc-2b78-4ddc-9ef8-632cde33ef74') user_profile = User_Profile.objects.get(id=id) error: ProgrammingError: operator does not exist: uuid = numeric LINE 1: ...ifications" FROM "tc_user_profile" WHERE "tc_user_profile"."id" = 33539211... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. So finally how to query a uuid id field from django database ? -
Identation Error while doing django
I have a problem with the code in the line 62 and i dont know how to fix this, its the first time i recive this error. Seems that is not well identated but i think it was. Is in the line with 'mes = lista_meses[tempNumMes-1]' views.py def crear_pdf(request): fecha = datetime.date.today() tempNumMes = fecha.month year = fecha.year lista_meses = ["Enero" , "Febrero" , "Marzo" , "Abril" , "Mayo" , "Junio" , "Julio" , "Agosto" , "Septiembre" , "Octubre" , "Noviembre" , "Diciembre"] mes = lista_meses[tempNumMes -1] return render(request,'pdf_creado.html') -
Identation Error while doing django
I have a problem with the code in the line 62 and i dont know how to fix this, its the first time i recive this error. Seems that is not well identated but i think it was. Is in the line with 'mes = lista_meses[tempNumMes-1]' views.py def crear_pdf(request): fecha = datetime.date.today() tempNumMes = fecha.month year = fecha.year lista_meses = ["Enero" , "Febrero" , "Marzo" , "Abril" , "Mayo" , "Junio" , "Julio" , "Agosto" , "Septiembre" , "Octubre" , "Noviembre" , "Diciembre"] mes = lista_meses[tempNumMes -1] return render(request,'pdf_creado.html') -
OperationalError at /admin/ no such table: xadmin_usersettings
File "/project_path/project_env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute 323. return Database.Cursor.execute(self, query, params) Exception Type: OperationalError at /admin/ Exception Value: no such table: xadmin_usersettings -
OperationalError at /admin/ no such table: xadmin_usersettings
I am getting the following error when open the admin panel of the project Note : Integrating django-xadmin. File "/project_path/project_env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py" in execute 323. return Database.Cursor.execute(self, query, params) Exception Type: OperationalError at /admin/ Exception Value: no such table: xadmin_usersettings -
Whoosh search results not Json serializable
How do I make the results from Whoosh search results JSON serializable so I can return that data back to the client? Whoosh search output (list of python objects): [<Hit {'content': 'This is the second example.', 'path': '/b', 'icon': '/icons/sheep.png', 'title': 'Second try'}>, <Hit {'content': 'Examples are many second.', 'path': '/c', 'icon': '/icons/book.png', 'title': "Third time's the charm"}>] Error when doing this: return JsonReponse({"data": whoosh_results}) TypeError: <Hit {'content': 'This is the second example.', 'path': '/b', 'icon': '/icons/sheep.png', 'title': 'Second try'}> is not JSON serializable I have tried making a separate class class DataSerializer(serializers.Serializer): icon=serializers.CharField() content=serializers.CharField() path=serializers.CharField() title=serializers.CharField() but the error becomes that the Hit object has no attribute 'icon' -
Whoosh search results not Json serializable
How do I make the results from Whoosh search results JSON serializable so I can return that data back to the client? Whoosh search output (list of python objects): [<Hit {'content': 'This is the second example.', 'path': '/b', 'icon': '/icons/sheep.png', 'title': 'Second try'}>, <Hit {'content': 'Examples are many second.', 'path': '/c', 'icon': '/icons/book.png', 'title': "Third time's the charm"}>] Error when doing this: return JsonReponse({"data": whoosh_results}) TypeError: <Hit {'content': 'This is the second example.', 'path': '/b', 'icon': '/icons/sheep.png', 'title': 'Second try'}> is not JSON serializable I have tried making a separate class class DataSerializer(serializers.Serializer): icon=serializers.CharField() content=serializers.CharField() path=serializers.CharField() title=serializers.CharField() but the error becomes that the Hit object has no attribute 'icon' -
"hostname doesn't match" errors when using request on PythonAnywhere hosted server
I'm using the XMLHttpRequest AJAX API to send data from different websites to our server in PythonAnywhere. Something odd happens: depending on the website, either we send successfully or we get this error POST https://canecto.pythonanywhere.com/api/ 500 (Internal Server Error) even though the same code is loaded. I tried to manually open the request and send data via JavaScript console in Chrome but nothing changes. Here is how the snippet looks like: var url = "https://canecto.pythonanywhere.com/api/"; var xmlHttpPost = new XMLHttpRequest(); xmlHttpPost.open("POST", url, true); xmlHttpPost.setRequestHeader("Content-type", "application/json"); var postData = { page_url: window.location.href, time_on_page: activeTime, cookie: cookie, /* some variables */ }; xmlHttpPost.onreadystatechange = function() { if (xmlHttpPost.readyState == 4 && XMLHttpRequest.DONE) { console.log(''); } }; /* send data */ xmlHttpPost.send(JSON.stringify(postData)); I read here that the problem should not be the client-side JavaScript. If I inspect on the server side, for the line requests.get(page_url, headers=HEADER, timeout=10)(where I try to access the page) I get this log: I read on the Python request library that it may be something related to the SSL verification, but I have very little clue about it. I tried to check other similar questions but I have not found the answer. Has anybody experienced anything similar and successfully … -
multiprocessing in django with db queires in each process
I have around 30k items in db where each one must be processed and dumped out into a file. def reset_database_connection(): from django import db db.close_old_connections() all_quiz_ids = [q_id for q_id in MyModel.objects.values_list('id', flat=True)] # chunk the huge list into 5 parts chunked_quiz_ids = [all_quiz_ids[i::5] for i in xrange(5)] for ids in chunked_quiz_ids: p = Process(target=my_script, args=(ids, ids[0])) # close parent process db connection, so each new process creates its own one reset_database_connection() p.start() p.join() in my_script I will query the db, get some infos and write into a file. inside my_script, I will reset db connections again where queries happen for longer time When I run the code, I am getting from the Process-2 the OperationalError: (2006, 'MySQL server has gone away') what am I doing wrong here? how can I create 5 processes where each process can handle 6k items on its own without losing db connection? I am using python2 and django 1.8 -
multiprocessing in django with db queires in each process
I have around 30k items in db where each one must be processed and dumped out into a file. def reset_database_connection(): from django import db db.close_old_connections() all_ids = [q_id for q_id in MyModel.objects.values_list('id', flat=True)] # chunk the huge list into 5 parts chunked_all_ids = [all_ids[i::5] for i in xrange(5)] for ids in chunked_all_ids: p = Process(target=my_script, args=(ids, ids[0])) # close parent process db connection, so each new process creates its own one reset_database_connection() p.start() p.join() in my_script I will query the db, get some infos and write into a file. inside my_script, I will reset db connections again where queries happen for longer time When I run the code, I am getting starting from the Process-2 the error OperationalError: (2006, 'MySQL server has gone away') what am I doing wrong here? how can I create 5 processes where each process can handle 6k items on its own without losing db connection? I am using python2 and django 1.8 -
How to incorporate elasticsearch in an existing osqa(django) project? [on hold]
I have an osqa website which uses mysqlfulltext for search. I want to use elasticsearch instead. Where and what code changes will I have to make? -
How to incorporate elasticsearch in an existing osqa(django) project?
I have an osqa website which uses mysqlfulltext for search. I want to use elasticsearch instead. Where and what code changes will I have to make? -
Django auth with redis
I try to plug in my django aplication into microservice architecture. Authentication is made by component written in spring boot. It stores session in redis in following format: "spring:session:sessions:71f06a1d-b169-4bb9-a4c8-013bb82742ee" Is it possible to configure some existing django lib (configure namespace) to use build in auth system. I would like to avoid write down whole from scratch. Any help will be welcome. -
Django auth with redis
I try to plug in my django aplication into microservice architecture. Authentication is made by component written in spring boot. It stores session in redis in following format: "spring:session:sessions:71f06a1d-b169-4bb9-a4c8-013bb82742ee" Is it possible to configure some existing django lib (configure namespace) to use build in auth system. I would like to avoid write down whole from scratch. Any help will be welcome. -
Connect Django 1.11 to Mariadb Galera cluster
I am using Django 1.11 with MariaDB 10.1 Galera cluster I didn`t find in the documentation how to connect to a cluster. I tried using gcomm://NODE1,NODE2 url with no success... any idea? -
Connect Django 1.11 to Mariadb Galera cluster
I am using Django 1.11 with MariaDB 10.1 Galera cluster I didn`t find in the documentation how to connect to a cluster. I tried using gcomm://NODE1,NODE2 url with no success... any idea? -
How to remove an element by tag matching
I want to remove the part surrounded by a specific element / class from the variable storing html, but I do not know how. For example, the following html document is stored in the variable "content" <div class="content"> <h1>content</h1> <p>content<p> <p>content</p> <div> <!-- want to delete from here --> <div class="Footer"> <div class=Footer-item> ... ... </div> </div> I tried implementing as below from urllib.parse import urlparse newcontent = content.find("div", {"class":"Footer"}).extract() However, the following error occurred TypeError: slice indices must be integers or None or have an __index__ method If you have a good solution please tell me. -
How to remove an element by tag matching
I want to remove the part surrounded by a specific element / class from the variable storing html, but I do not know how. For example, the following html document is stored in the variable "content" <div class="content"> <h1>content</h1> <p>content<p> <p>content</p> <div> <!-- want to delete from here --> <div class="Footer"> <div class=Footer-item> ... ... </div> </div> I tried implementing as below from urllib.parse import urlparse newcontent = content.find("div", {"class":"Footer"}).extract() However, the following error occurred TypeError: slice indices must be integers or None or have an __index__ method If you have a good solution please tell me. -
django admin doesn't display value
How to display the Author name correctly? It only display a 'dash' there. The following is my code. admin.py @admin.register(Solution) class SolutionAdmin(admin.ModelAdmin): def get_original_question(self, obj): se = obj.question_code return format_html(se.question) def get_name(self, obj): se = obj.user_id.name return se fieldsets = [ ('question', {'fields': ['get_original_question']}), ('author', {'fields': ['get_name']}), ('solution', {'fields': ['body']}), ] readonly_fields = ('get_original_question','get_name') get_original_question.short_description = 'question' get_name.short_description = 'author' Models.py class Question(models.Model): question = RichTextField(blank=True, null=True) question_code = models.CharField(max_length=15,unique=True) class Solution(models.Model): question_code = models.OneToOneField(Question, to_field='question_code', db_column='question_code') user_id = models.ForeignKey('Users',to_field='id' ,db_column='ID') body = RichTextField(blank=True, null=True) class Users(models.Model): id = models.AutoField(db_column='ID', primary_key=True) name = models.CharField(db_column='Name', max_length=255, blank=True, null=True) In django shell: >>> Solution.objects.get(pk=1490).user_id Traceback (most recent call last): File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__ rel_obj = getattr(instance, self.cache_name) AttributeError: 'Solution' object has no attribute '_user_id_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 184, in __get__ rel_obj = self.get_object(instance) File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 159, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get self.model._meta.object_name den.models.DoesNotExist: Users matching query does not exist. UPDATE: The following is my solution table UPDATE: add 1490 table UPDATE: >>> Solution.objects.get(pk=180).user_id <Users: John> >>> Solution.objects.get(pk=180).user_id.name 'John' >>> Solution.objects.get(pk=1490).user_id.name Traceback (most recent call … -
django admin doesn't display value
How to display the Author name correctly? It only display a 'dash' there. The following is my code. admin.py @admin.register(Solution) class SolutionAdmin(admin.ModelAdmin): def get_original_question(self, obj): se = obj.question_code return format_html(se.question) def get_name(self, obj): se = obj.Users.name return se fieldsets = [ ('question', {'fields': ['get_original_question']}), ('author', {'fields': ['get_name']}), ('solution', {'fields': ['body']}), ] readonly_fields = ('get_original_question','get_name') get_original_question.short_description = 'question' get_name.short_description = 'author' Models.py class Question(models.Model): question = RichTextField(blank=True, null=True) question_code = models.CharField(max_length=15,unique=True) class Solution(models.Model): question_code = models.OneToOneField(Question, to_field='question_code', db_column='question_code') user_id = models.ForeignKey('Users',to_field='id' ,db_column='ID') body = RichTextField(blank=True, null=True) class Users(models.Model): id = models.AutoField(db_column='ID', primary_key=True) name = models.CharField(db_column='Name', max_length=255, blank=True, null=True) In django shell: >>> Solution.objects.get(pk=1490).user_id Traceback (most recent call last): File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__ rel_obj = getattr(instance, self.cache_name) AttributeError: 'Solution' object has no attribute '_user_id_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 184, in __get__ rel_obj = self.get_object(instance) File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/fields/related_descriptors.py", line 159, in get_object return qs.get(self.field.get_reverse_related_filter(instance)) File "/home/aaron/.virtualenvs/django/lib/python3.5/site-packages/django/db/models/query.py", line 379, in get self.model._meta.object_name den.models.DoesNotExist: Users matching query does not exist. -
dronekit python vehicle timeout
after running vehicle_state.py example,it shows an error like below. Traceback (most recent call last): File "C:\Users\CVLAB\Downloads\dronekit-python-master\dronekit-python-master\examples\vehicle_state\test.py", line 5, in print vehicle.wait_ready('autopilot_version') File "C:\Python27\lib\site-packages\dronekit__init__.py", line 2199, in wait_ready timeout) APIException: wait_ready experienced a timeout after 30 seconds. -
dronekit python vehicle timeout
after running vehicle_state.py example, it shows an error like below. Traceback (most recent call last): File "C:\Users\CVLAB\Downloads\dronekit-python-master\dronekit-python-master\examples\vehicle_state\test.py", line 5, in <module> print vehicle.wait_ready('autopilot_version') File "C:\Python27\lib\site-packages\dronekit\__init__.py", line 2199, in wait_ready timeout) APIException: wait_ready experienced a timeout after 30 seconds. -
How to take a uploaded file in django and pass to a function
Hi upload csv files in the media folder and now i want to take this files to pass a list in python to make a pdf. How can i call this files in a fucntion in django or there is a better way to do it?? This is how i upload the files: def subir_archivos(request): if request.method == 'POST' and request.FILES['myfile']: myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'subir_csv.html', { 'uploaded_file_url': uploaded_file_url }) return render(request, 'subir_csv.html') And the method to pass a csv to a python list: def csv_empresas(request): lista = [] with open('media/empresas.csv') as csvfile: lector = csv.reader(csvfile, delimiter=',',quotechar='|') for row in lector: lista.append(row) return render(request,'preparar_pdf.html',{"lista": lista})