Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Does using multiprocessing thread pool in gunicorn result in memory leak?
We have a django application named "x" in its __init__.py we are creating a thread pool to handle async tasks : from multiprocessing import Pool POOL = Pool(processes=10) Now wherever we decide to do a task asynchronously, we import POOL variable and call apply_async on it. I believe there is a potential memory leak problem when a gunicorn instance is being reloaded. I know for a fact that there are a lot of times that a gunicorn instance get reloaded. We are running 100 gunicorn workers and if we create 10 async worker per each gunicorn instance per each reload, I believe we will run into a memory leak problem. Is this claim true? Does it happen as I explained? If yes, is there any workaround for this problem? -
How to use the ORM for the equivalent of a SQL count, group and join query?
I have tags which can be associated with images and locations. Tags are unique. Images and locations can have many tags. A Tag_Item model is used to link everything together. Here are the models: LOCATIONS = ( ('US', 'USA'), ('UK', 'United Kingdom'), ('FR', 'France'), ) class Location(models.Model): location = models.CharField(choices=LOCATIONS) class Image(models.Model): image = models.ImageField(verbose_name='Image') class Tag(models.Model): tag = models.CharField(max_length=150, unique=True) class Tag_Item(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) location = models.ForeignKey(Location, null=True, blank=True, default=None) image = models.ForeignKey(Image, null=True, blank=True, default=None) created_at = models.DateTimeField(auto_now_add=True) I want to write a query which means "select the five most frequent tags for USA". If I was using SQL I would join Tag, Tag_Item, and Location where location is 'US', group it by tag and order it by a count of Tag_ID (or something along those lines), but I can't figure out how to even start with this the Django ORM. Could you please help me understand how to write these sorts of complex relationship queries? Thank you. -
Save the same file to multiple db entries in Django
In my Django app the user fills in a form and uploads a file. I need to create multiple db entries, but they all should reference the same file. In other words, if there's 10 objects that need to be created, I don't want to save the uploaded file 10 times to my storage backend. I want to save the file once and then each db entry should reference the same file. Below is what I currently have, but it creates the file multiple times class MyModel(models.Model): price = models.FloatField() my_file = models.FileField() class BatchTradeForm(forms.Form): price = forms.FloatField() my_file = forms.FileField() def create(self): new_items = [] for x in range(10): entry = MyModel(**self.cleaned_data) new_items.append(entry) MyModel.objects.bulk_create(new_items) class MyView(FormView): def form_valid(self, form): form.create() I'm guessing I need to save the file manually first to my storage backend and then save the reference some how, but I'm sure there must be a simpler way to achieve this? -
Separation the string with comma when occurs "\r\n"
I have a string in which there are "\r\n", wants to remove and insert a comma there and have a couple of elements in the array. This is my code: def test_method(self): my_list = self.texts.filter(code='open') for i in my_list: return strip_tags(i.text.replace('\r\n', ',').split(',')) my_list is: <class 'django.db.models.query.QuerySet'> I only have one string with commas. -
'str' object is not callable - SuccessMessageMixin
I get this error in a project whith SuccessMessageMixin and and not know why. This is my code in view.py. from django.contrib.messages.views import SuccessMessageMixin from django.views.generic import CreateView class CampanaNueva(SuccessMessageMixin, CreateView): model = Campana template_name = "licencias_campana_nueva.html" fields = ['temporada', 'descripcion'] success_message = "a" And Raise this error on save: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/licencias/editar/1 Django Version: 1.9.4 Python Version: 3.4.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'home', 'widget_tweaks', 'socios', 'equipaciones', 'licencias'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'cc_corbelo.middleware.LoginRequiredMiddleware'] Traceback: File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python34\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post 279. return super(BaseUpdateView, self).post(request, *args, **kwargs) File "C:\Python34\lib\site-packages\django\views\generic\edit.py" in post 222. return self.form_valid(form) File "C:\Python34\lib\site-packages\django\contrib\messages\views.py" in form_valid 14. messages.success(self.request, success_message) Exception Type: TypeError at /licencias/editar/1 Exception Value: 'str' object is not callable I have this function working in another project without problems... -
Repeater objects appearing on all detail views - django
I have two models with a foreign key, one to many relationship so that I can get a repeater model (images) in the admin. The image repeater works fine, my problem is that the images for the field - video_stills saved on one of the film post/objects repeats across all film posts. Here is my code: model.py from __future__ import unicode_literals from django.db import models from embed_video.fields import EmbedVideoField from sorl.thumbnail import ImageField class Timestamp(models.Model): created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: abstract = True # Film Model class Film(Timestamp): title = models.CharField(max_length=255) order = models.PositiveIntegerField(default=0, blank=False, null=False) meta_description = models.TextField('Meta Description', max_length=170, help_text='Content for description meta tag - Max 170 Characters') slug = models.SlugField(unique=True) image = models.ImageField(upload_to='thumb') video = EmbedVideoField(blank=True) director = models.CharField(max_length=255,blank=True) cinematographer = models.CharField(max_length=255,blank=True) producer = models.CharField(max_length=255,blank=True) publish = models.BooleanField(default=False) date_published = models.DateTimeField() # thumb for admin def image_thumb(self): return '<img src="%s" height="200" width="300"/>' % (self.image.url) image_thumb.short_description = 'Image' image_thumb.allow_tags = True # override the admin name + add ordering class Meta(object): ordering = ('order',) verbose_name_plural = "Film Projects" def __unicode__(self): return self.title # helper method def get_absolute_url(self): return "/film/%s/" % self.slug def save(self, *args, **kwargs): super(Film, self).save(*args, **kwargs) # Film Stills Image Model class FilmStillsImage(models.Model): … -
django admin why my ForeignKey do'nt display?
In django admin page, it have default value on IDC filed,But in edit page,it not display. what method can resulove it? one image rt two image code class IDC(models.Model): uuid = UUIDField(auto=True, primary_key=True) name = models.CharField(max_length=64,verbose_name=u'机房名称') class Server(models.Model): idc = models.ForeignKey(IDC, blank=True, null=True, verbose_name=u'机房', on_delete=models.SET_NULL) class ServerAdmin(admin.ModelAdmin): model = models.Server exclude = ('memo',) -
No module named 'kebab' in django devserver
I created an app called 'kebab' locally and it all works fine. I've added it to settings.py and url's and it's all good. However, when we pull our local changes onto the development server, ubuntu returned the "no module named 'kebab'" error. We added it to settings.py on the devserver but still no luck. A little stumped at the moment. Any suggestions? We're running Ubuntu and an Apache server. -
Django + mod_wsgi + apache2: ImportError: No module named <project>
I'm trying to get to the bottom of my problem regarding running any "migrate" command on my django project. I have a django app deployed in a virtual env and with mod_wsgi and apache2 the app is served properly at www.mysite.com/test/simulatore. The problem came when I edited the models, so I had to run python manage.py makemigrations After some initial troubleshooting I think I have isolated the problem on wsgi.py If I try (from my virtualenv) to try to run the command python -i /home/carma/mycarma_test/mycarma/mycarma/wsgi.py this is the result ['/home/carma/mycarma_test/mycarma/mycarma', '/home/carma/mycarma/testenv/lib/python35.zip', '/home/carma/mycarma/testenv/lib/python3.5', '/home/carma/mycarma/testenv/lib/python3.5/plat-x86_64-linux-gnu', '/home/carma/mycarma/testenv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/carma/mycarma/testenv/lib/python3.5/site-packages', '/home/carma/mycarma_test/mycarma/mycarma/..', '/home/carma/mycarma_test', '/home/carma/mycarma_test/mycarma'] Traceback (most recent call last): File "/home/carma/mycarma_test/mycarma/mycarma/wsgi.py", line 22, in <module> application = get_wsgi_application() File "/home/carma/mycarma/testenv/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/home/carma/mycarma/testenv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/carma/mycarma/testenv/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__ self._setup(name) File "/home/carma/mycarma/testenv/lib/python3.5/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/home/carma/mycarma/testenv/lib/python3.5/site-packages/django/conf/__init__.py", line 97, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/carma/mycarma/testenv/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File … -
Migrating MySQL DB version 5.6 to 5.5 (Django) structure dump import fails
Locally I was working on Django project with MySQL version 5.6 I am trying to host a DB on Azure and unfortunately ClearDB support 5.5 and not yet 5.6. I am migrating the data using the export/import functionality on MySQL Workbench. I dump the structure of the database first and that fails in syntax not sure why. 02:09:05 Restoring C:\Users\Saher\Documents\dumps\Dumpauthmodels.sql Running: mysql.exe --defaults-file="c:\users\saher\appdata\local\temp\tmpb3d1gg.cnf" --protocol=tcp --host=us-cdbr-azure-west-b.cleardb.com --user=b42d1da1703a84 --port=3306 --default-character-set=utf8 --comments --database=mytravelsdb < "C:\\Users\\Saher\\Documents\\dumps\\Dumpauthmodels.sql" ERROR 1064 (42000) at line 79: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6), `is_superuser` tinyint(1) NOT NULL, `username` varchar(30) COLLATE utf8' at line 4 Operation failed with exitcode 1 02:09:07 Import of C:\Users\Saher\Documents\dumps\Dumpauthmodels.sql has finished with 1 errors This is simply part of the Django table model. I know I can simply ignore these tables and just recreate with Django migrata/syncdb commands, but I am curious what Create table syntax changed between 5.5 and 5.6 causing syntax error. Here is the table structure in the dump from the localhost MySQL 5.6 -- -- Table structure for table `auth_user` -- DROP TABLE IF EXISTS `auth_user`; /*!40101 SET @saved_cs_client = @@character_set_client … -
Set dynamic domain name in Url of emain - DJANGO
I am buiding a web app using Django. When I use reset password, it sends an email to user. That url in the email has static domain - the domain that i set in admin/site. But I want that domain in the url of email changing dynamically. For example: if I run server on port 8000, url is http://localhost:8000/...., when I run on port 8001, url is http://localhost:8001/..... Can anyone give me a solution ?. I used get_curent_site(request), but It doesn't work. -
Django - stop synchronisation between different variables based on filters on same object
Sorry about the confused question, not sure how to describe it properly. Say that I have a model named News, a variable news will be used to store the filter results of the un-read News with the attribute read=False and mark these news to read=True, then return these news to template. The problem is that after update read=True, the original variable news which should store initial un-read news will become empty. What's the methods behind this and how to stop this synchronisation? Code example: class News(models.Model): ... read = models.BooleanField(default=False) def foo(self): news = News.object.filter(read=False) # get un-read news correctly news.update(read=True) # update stored news successfully, but news will become empty return news # return empty news instead of original filter result Thanks for your answers. -
django: AttributeError: 'DatabaseWrapper' object has no attribute 'introspection'
I'm using django1.10, python3.4. When trying to use migrations for the first time (Project was django1.6 python2.7), I get the following error: (venv) ruben@erd959:~/Projects/prot-zboss/zboss$ python manage.py makemigrations utils Traceback (most recent call last): File "manage.py", line 8, in <module> execute_from_command_line(sys.argv) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/core/management/commands/makemigrations.py", line 106, in handle loader.check_consistent_history(connection) File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history applied = recorder.applied_migrations() File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/home/nfs/ruben/Projects/prot-zboss/venv/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): AttributeError: 'DatabaseWrapper' object has no attribute 'introspection' It looks something with the database is not doing ok. Well, It seems that if I removed the DATABASE_ROUTERS, it works again but I need to have that for my LDAP functionality. DATABASES = { 'default': { #'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'prot', # Or path to database file if using sqlite3. 'USER': 'prot', # Not used with sqlite3. 'PASSWORD': '1234', # Not used with sqlite3. 'HOST': 'localhost', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '5432', … -
Adding cache.clear() to global save in Django
Hopefully somebody knows a simple way to do this. Is it possible to run the cache.clear() function on every save to any model? I know Django docs show you how to implement per model, and overhead isn't an issue. I would like to clear the cache each and every time a change is made. -
How to reorder data based on the "next" field
Hi I am programming using python and I want to display the list in correct order based on next field. I have a model which looks like: Task() id name next 1 task1 3 2 task2 0 3 task3 2 I do not know how to display it because I only know the basic taskList = Task.objects.all() so when I display it, it should look like task1 task3 task2 Please help me. Thank you in advance -
Using python as a backend
I am a beginner, PLEASE do not roast me! I have seen the use of Python in the backend. How does this work? More specifically, what does one do working as a backend dev with python? Do you handle the SQL Databases as well? Do you use Django? Thanks! -
Google App Engine vs Amazon AWS for Django Deployment
I have a requirement to deploy my django code on Google App Engine. But I read that it does not support Many-To-Many and ImageFields (source: gae django ) ? Also there are some limitations with using django ORM ? Should I drop the idea and consider Amazon AWS or Digital ocean? -
Sending a list of checkboxes via Ajax to Django
I have a list of checkboxes in a table in my Django app. The user selects some of them and then clicks an action button. A small popup modal form then pops up, where they fill in info related to the selected items and they can also upload a file in the in the popup. I need to send the selected checkboxes' ids and the form fields in the modal to Django via ajax I've wrapped the modal in a form tag and that all works well. I'm struggling sending the list of selected IDs to Django. When the user selects id 31 and 32, it sends it as '31,32' as a string and Django can't decode it. I'm sure it is a quick fix, but my javascript knowledge is limited. Below is my code: Html: <tr> <td ><input class="selection-box" type="checkbox" name="action" value="{{ item.id }}"></td> <td>...</td> </tr> <tr> <td ><input class="selection-box" type="checkbox" name="action" value="{{ item.id }}"></td> <td>...</td> </tr> Javascript: submitHandler: function () { var matches = []; $(".selection-box:checked").each(function() { matches.push(this.value); }); var form = document.forms.namedItem("fileinfo");// This is the popup form that contains that file upload box and other fields var oData = new FormData(form); if (matches.length) { oData.append('action', matches); } … -
Django Sort by backward foreign key
I currently have the following models class ChatRoom(models.Model): creator = models.ForeignKey('User') # points to the initial user class Message(models.Model): room = models.ForeignKey('ChatRoom') text = models.CharField(max_length=500) date = models.DateTimeField() from = models.ForeignKey('User') # points to some user For any given user who logs into my website, I want to display a list of the chat rooms they have created, ordered by the date of their last message (latest activity) along with the last message entered to the chatroom So something like Your chat rooms --------------- science - "hey guys, anyone know how to do calculus?" 5m art - "hey guys, I like art" 10m How would I perform this query in django? Keep in mind that a person might have many, many, many chat rooms and thus we can't just load all the chat_rooms with ChatRoom.objects.all() and manually iterate through it. -
How to load form with one value pre filled?
I'm using using Django forms to collect information from users. But when I change between pages I want to use one of the value from url to be displayed in a from in the next page. Example. I have url for checking out a book like http://127.0.0.1:8000/checkout/780374157067 780374157067 is the ibn of the book Next page has a form where I get the ISBN and card id of the user. How to fill the form with the ISBN and show the form to user. rather than the user giving the ISBN again. ISBN Filed should be pre filled with thw isbn in URL. -
coreapi must be installed to use 'get_schema_fields()'
So I installed django-rest-swagger as shown in django rest documentation. And on from django.conf.urls import url from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ url(r'^$', schema_view) ] I keep on getting following error, File ".../local/lib/python2.7/site-packages/django_filters/rest_framework/backends.py", line 97, in get_schema_fields assert compat.coreapi is not None, 'coreapi must be installed to use get_schema_fields()' AssertionError: coreapi must be installed to use get_schema_fields() I have the following packages installed: coreapi==2.0.8 Django==1.9.6 django-filter==0.15.3 django-rest-swagger==2.0.7 djangorestframework==3.5.0 -
DJANGO: Mass update field by adding a prefix
I wish to update a Django model field of objects in a queryset. To be specific, I want to add a prefix on one of the fields i.e. if an object has a name like 'Wilson', I want to prefix it with 'OLD', then it will become 'OLDWilson'. I can think of the following using loops: my_objs = MyObjects.objects.filter(name='some_name') # This has over 40000 records for obj in my_objs: obj.name = 'OLD{0}'.format(obj.name) obj.save() I was hoping of a more elegant way to take advantage of the UPDATE method as specified here: Django Mass Update Something like the following: MyObjects.objects.filter(name='some_name').update(name='OLD+name_here') Any pointers on how I can achieve this? -
How to create stopwatch time in django
I want for create a field that can take input in the form: mm:ss.xx currently I am using the following code, but it only interprets hours:mins:secs models.TimeField(default='7:00') My applologies for the basic question but my googles and documentation searches have been to no avail -
How to render the text of the selected option in template?
I have a ModelForm that has a widget of type Select class MyModelForm(ModelForm): ... widgets = { 'my_field': Select( choices=[('1', 'Choice 1')] ), } In my view I'm retrieving an already stored model and passing the form as my_form to the template: <div>{{ my_form.my_field.value }}</div> As expected, this outputs: 1 How can I get the text 'Choice 1' instead? -
which django authocomplete should I use?
I have a form which has input as name. It search the lastname and firstname field in a database. I need to autocomplete when users type the name. I see there's several django autocomplete package. Which one should I use? Is django-autocomplete-light a easy one? I followed that tutorial, but has error even at the beginning, and it seems hard to understand. Thanks for any suggestion!