Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django page to find and replace text
I'm hoping to get some assistance so I will try and be clear and concise as possible. I need to create a webpage that will allow me to paste into a text box a configuration file.. and then put anchors within it so that when submitted it will allow those anchors to be variables where I can put my own text in. I'm basically looking to do exactly what 4peg.com does but need it to be on a private server. I'm just starting out my scripting journey and would love to do this myself but I'm feeling that it's quite tough. Any help would be appreciated. Cheers, Thomas. -
Using multiprocessing in Django on Windows
I have a class that uses a multiprocessing method to quickly grab values. This class/method is called within my Django app, specifically through views.py. But every time I run my server with python manage.py runserver and then call the appropriate views method which then calls the multiprocess method in my test class I get the IOError [Errno 22], Invalid argument. The code worked fine on unix, and after doing some research I realize you need to put the multiprocess call in an if condition if __name__ == "__main__":. My problem is I have no idea where I should put this conditional. Django's manage.py already includes this statement, so I'm somewhat lost in why the code isn't working. If I put this statement in the actual class method, nothing executes. Any help would be appreciated! Here is my example class/object # class 1 import multiprocessing class test: def __init__(self): pass def multiprocess(self,values): # create a manager to handle return values manager = multiprocessing.Manager() return_dict = manager.dict() # list of processes that will run jobs = [] # create multiple processes for value in values: t = multiprocessing.Process(target=self.multiprocess_callback,args=(value,return_dict)) jobs.append(t) t.start() # make processes run at the same time for job in jobs: … -
Django postgres remove all data created after a point in time
How can I remove all the objects which were created after some timestamp t in django? Plainly, I need to remove all the objects (all rows in all tables) which have created_at > t. Is there any better solution than writing this: models = [Model1, Model2, ..., ModelN] for model in models: model.objects.filter(created_at__gt=t).delete() -
Javascript - load template in html of element
I have a template that i want to render inside html element on click of element. I want to do something like ( i am using jquery): $(".btn")on("click", function(){ $("#element").html(partial_template.html) }); Buto this of course wont work. How can i achieve this? Thanks! EDIT: I am using Django, if this matters! -
Django: Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I'm working on implementing Django Rest Framework into my current Django project. I have followed the DRF tutorial/getting started guide and made some minor alterations to allow the drf code to work with my existing apps and models. My problem is that I get the following error whenever I try to run the application: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f83fb31dd08> Traceback (most recent call last): File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/vagrant/.virtualenvs/python/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/home/vagrant/.virtualenvs/python/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 … -
how to set StructuredRel using django-neomodel and modelForm
this is my forms.py: from django import forms from .models import Position, PositionRelForm class PositionForm(forms.ModelForm): class Meta: model = Position fields = '__all__' class PositionRelForm(forms.ModelForm): class Meta: model = PositionRel fields = '__all__' and this is my models.py from django.db import models from datetime import datetime from django_neomodel import DjangoNode from neomodel import StructuredNode, StringProperty, DateTimeProperty, UniqueIdProperty, Relationship, StructuredRel from django.core.urlresolvers import reverse class PositionRel(StructuredRel): since = DateTimeProperty(default=lambda: datetime.now(pytz.utc)) distance = StringProperty() class Meta: app_label = 'highways' class Position(DjangoNode): kind = StringProperty(unique_index=True) created_at = DateTimeProperty(default=datetime.utcnow) road_to = Relationship('Position','ROAD_TO', model=PositionRel) class Meta: app_label = 'highways' def get_absolute_url(self): return reverse('position_list') and when I run the server I got this error : AttributeError: type object 'Position' has no attribute '_meta' -
django admin "Key 'category' not found in 'SpecificationParameterForm'. Choices are: help_text, name, units, value_type."
When I view the change list in the admin interface I can see the 'name', 'category', 'value_type', 'help_text' fields, proving that the category field is fine. But when I click on a Parameter to get to the change form I get the above error. This seemed to appear when I upgraded from Django 1.9 to 1.10, but there doesn't appear to be a change in the release notes affecting it.. Here's my admin: @admin.register(SpecificationParameter) class SpecificationParameterAdmin(SortableAdminMixin, admin.ModelAdmin): """ For administering Specification Parameters """ # Fields shown in lists list_display = ('name', 'category', 'value_type', 'help_text') list_per_page = 20 # related field needs __ due to foreign key search_fields = ['name', 'category__name'] # Change 'Save and add another' to 'Save as new' to easily create similar entries save_as = True # django 1.10 will default to staying on the page after creating a new one; redirects in 1.9 :( # for this purpose, show the id readonly_fields = ('id',) # Modify the layout of the form, put the optional choices last fieldsets = ( (None, {'fields': (('name', 'id'), 'category', 'units', 'help_text')}), (_('Type'), {'fields': ('value_type',)}), ) def get_form(self, request, obj=None, **kwargs): """ Override get_form to dynamically display choices if multiple choice or checkbox … -
Django: maintaining server side data whilst obtaining POST request?
I'm new to Django and now that I have complete the 7 part tutorial I am trying to learn more while making my own application. One part of my application takes input from the user and then requires some non-trivial server-side calculation (e.g. the user will experience some wait) before producing the output. So instead of calculating everything all at once, I would like to have several small forms, each sending data to the server calculating part and waiting until it receives the next. For example: my_app: will have a form which asks the user for three numbers, it will subtract the first from 100, then add the second number to the result, and finally multiply the new result by the third input: e.g. my form 1st: 5 2ed: 7 3rd: 2 result: (((100 - 5) + 7) * 2) = 204 While the above example is trivial, what I am doing will take some time (but, if it is not the first field, is dependent on the results from the previous result). I learned how to properly have a view post to itself here: Django: proper way to handle form with POST to the same page So how can … -
django - How to return object with its ManyToManyField object
I have a model, for example, A has a field xxx (ManyToManyField with B model). How can I query and return like: { 'f1': 'xxx', 'f2': 'yyy', photos: [{photo1}, {photo2},...] } Any help is appreciated. I'm django newbie :D -
Django Admin : How to update/change the image from the list_display itself without opening the change form for the entry
My models.py looks like class User_Detail(models.Model): user_image = models.ImageField(upload_to='users',default = 'users/profile.png') user_image_thumbnail = ImageSpecField(source='user_image', processors=[ResizeToFill(75, 100)], format='JPEG', options={'quality': 60}) My Admin.py looks like class UserAdmin(admin.ModelAdmin): list_display = ('profile_pic',) def profile_pic(self, obj): # receives the instance as an argument url = reverse('admin:%s_%s_change' %(obj._meta.app_label, obj._meta.model_name), args=[obj.id] ) url_string = '<a style="margin: 2px;" href="%s">Update</a>' %(url) return '<img width=75 height=75 src="{thumb}" />'.format( thumb=obj.user_image_thumbnail.url, ) + url_string profile_pic.allow_tags = True profile_pic.short_description = 'User Picture' I want the django administrator to update the imagefield from the admin list display itself by providing an update button next to displayed thumbnail and save it without opening the change form for the entry. I am using the django-imagekit for generating the thumbnails. -
ModelForm in Django - select is not populating with appropriate data?
I've got a model form in Django that displays nicely - but it's not pulling the appropriate information. The select dropdowns appear, but are not populated with the options and I am struggling to figure out why. My models look like this: class Mileage(models.Model): start_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='start_locations') end_location = models.ForeignKey(Location, on_delete=models.PROTECT, related_name='end_locations') miles = models.DecimalField(max_digits=8, decimal_places=2) user_id = models.IntegerField(null=True) def __str__(self): return self.miles class Location(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255, null=True) latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True) user_id = models.IntegerField(null=True) def __str__(self): return self.id class Trip(models.Model): start_location = models.CharField(max_length=255) end_location = models.CharField(max_length=255) miles = models.DecimalField(max_digits=7, decimal_places=2) user = models.ForeignKey(User, on_delete=models.PROTECT) trip_date = models.DateTimeField('trip date') def __str__(self): return self.id My ModelForm looks like this: class TripsForm(ModelForm): class Meta: model = Trip fields = ['start_location', 'end_location', 'miles', 'trip_date'] widgets = { 'start_location': forms.Select( attrs={ 'class': 'form-control', 'id': 'start_location' } ), 'end_location': forms.Select( attrs={ 'class': 'form-control', 'id': 'end_location' } ), 'miles': forms.NumberInput( attrs={ 'class': 'form-control', 'id': 'miles', 'readonly': 'readonly' } ), 'trip_date': forms.TextInput( attrs={ 'class': 'form-control monthpicker datepicker', 'id': 'trip_date' } ), } In my view I'm calling it like this from view.py: # Create trip def trip_create(request): # if this is a POST request we … -
Elastic Beanstalk running mod_wsgi Django app with multi processes causing 302 loop
I have been investigating for a while now, and all the docs seem to say this is possible, but whenever I increase our elastic beanstalk mod_wsgi NumProcesses config above 1, our admin site is inaccessible. I have created a reduction where I tested with a default django app, and the behaviour is still present. I have also tried to replicate locally, however my apache and mod_wsgi config cannot replicate the issue. Basically, what I am seeing, is that every attempted login, causes a 302 Found redirect back to the login page. I have cleared the sessions out of the database, and I can confirm that the application creates a new entry during the login POST, but the user is still directed back to the login page (see config and logs below). We also have a load balancer and sticky sessions configured on the Elastic Beanstalk instance(s). Here is the python contained config from our .ebextensions option_settings: "aws:elasticbeanstalk:container:python": WSGIPath: site/settings/wsgi/__init__.py NumProcesses: 4 NumThreads: 15 Here is the resulting wsgi.conf taken from the instance WSGIPythonHome /opt/python/run/baselinenv WSGISocketPrefix run/wsgi WSGIRestrictEmbedded On <VirtualHost *:80> Alias /static/ /opt/python/current/app/site/static/ <Directory /opt/python/current/app/site/static/> Order allow,deny Allow from all </Directory> WSGIScriptAlias / /opt/python/current/app/site/settings/wsgi/__init__.py <Directory /opt/python/current/app/> Require all granted </Directory> … -
Django rest framework: how to turn off/on pagination in ModelViewSet
I'm using Django REST framework with djangorestframework-csv with default pagination settings, but when request is with format "CSV", there is no need in paginaion. Is possible to disable pagination with: pagination_class = None can I change it dynamically? class ObjectViewSet(BaseViewSet, viewsets.ModelViewSet): queryset = Object.objects.none() serializer_class = ObjectSerializer pagination_class = None # if format is "CSV" # pagination_class = None # if fromat isn't "CSV" Thanks. -
Django: namespacing for flatpages?
So I am new to Django (and complete the 7 part tutorial) as well as read the flatpages app documentation. At the end of which, whoever wrote the Django documentation gives a demonstration as to how one would retrieve all the flatpages: {% load flatpages %} {% get_flatpages as flatpages %} <ul> {% for page in flatpages %} <li><a href="{{ page.url }}">{{ page.title }}</a></li> {% endfor %} </ul> I now have flatpages working (e.g. if I go to /pages/my_flatpage/ the default template I have renders. as I have included url(r'^pages/', include('django.contrib.flatpages.urls')) in the urlpatterns. So I am now in another app of mine and want to link to these flatpages. Using the code above I create the links. However, when I click on them, they do not render as they are routed to /my_flatpage/ rather than /pages/my_flatpage/. So I tried including the url pattern in my app, but that didnt work. How can I get the to go to the right place? -
Django single DB connection
I'm have a Django micro-service, that constantly runs a lot of tasks in the background (using a few child processes that run multiple threads), regardless of the request-response flow. Since every thread uses the ORM constantly, at some point I get an error for "too many clients" connected to the DB, and after that happens, it persists even after restarting the worker that got the exception. This is weird, since the app never spawns more than around 30-40 threads in parallel, and the PostgreSQL DB supports 100, but I guess every thread makes Django create a few connections of something like that... I've tried using db.connection.close() at the end of each thread, but it seems to have no effect. Is there any way to make Django use a single connection cursor for each process? Why does it even create new connections for each thread/query/whatever? NOTE: I am not sharing the connection between the worker processes. Before spawning the child processes, I used db.connections.close_all() -
Creating Django Filter in a bootstrap dropdown based on the django-admin created categories
I am 2 months into Python-Django and I do not have the full experience to carry on with my what I want to do. I like to create a Filter or a Dropdown Filter such that anyone can choose from the for-loop rendered categories in the dropdown to filter or search by category. I managed to create a full search with Haystack with Whoosh (You can test my Haystack Search here and search with category called marketing) Can someone shed more light on how I can filter my list based on categories looped in a dropdown? Am really confused. Here the code to my working Haystack Search search_indexes.py import datetime from haystack import indexes from haystack.query import EmptySearchQuerySet from .models import Mentor from .models import * class MentorIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) author1 = indexes.EdgeNgramField(model_attr='first_name') author2 = indexes.EdgeNgramField(model_attr='last_name') author3 = indexes.EdgeNgramField(model_attr='category') author4 = indexes.EdgeNgramField(model_attr='email') author5 = indexes.EdgeNgramField(model_attr='location') def get_model(self): return Mentor def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() home.html <form method="get" action="/search/" class="navbar-form"> <div class="form-group" style="display:inline;"> <div class="input-group" style="display:table;"> <input class="form-control" name="q" placeholder="Search Mentors Here. You can search by Location, Email, Name, e.t.c." autocomplete="off" autofocus="autofocus" type="text"> <span class="input-group-btn" style="width:1%;"> <button class="btn btn-danger" … -
Django - How change all values of a colum to null?
Sorry for my bad english. I had a problem, i make some changes in my models, because i had a field Integer, and change it to fk. Well for error i assign to all the objects in the field derived_to the value 1. I like to put all values in null now. How can i make this? this is my last 2 migrations class Migration(migrations.Migration): dependencies = [ ('work_order', '0026_auto_20170603_1517'), ] operations = [ migrations.AlterModelOptions( name='workorder', options={'verbose_name': 'work order', 'verbose_name_plural': 'work orders'}, ), migrations.AlterField( model_name='workorder', name='derived_to', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'), preserve_default=False, ), ] And the last one class Migration(migrations.Migration): dependencies = [ ('work_order', '0027_auto_20170605_0836'), ] operations = [ migrations.AlterField( model_name='workorder', name='derived_to', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='store.OutsourceOption', verbose_name='outsource'), ), ] Well thats all i need to make a new migration to assign null to all the objects in work_order in the colum derived_to, because now all the objects have derived_to pointing to the first register on OutsourceOptions and that is not correct. Thanks! -
django - how to return two serializer in a response
I have two variable that i want to return: - serializer1.data and serializer2.data. I don't know how return 2 variable like : return Response(serializer1.data (and) serializer2.data, status=...). Any help is appreciated. -
Django unit test suite "--functions=" couldn't be empty
I'm upgrading a Django app from version 1.10.7 to 1.11.2. After the upgrade, runserver command works well, but when I try to run the unit test suite the following error raised: CommandError: Option `--functions=...` couldn't be empty To run the unit test suite, I'm using the following command: python src\main\manage.py test --noinput As you can see, I'm not using any --function parameter and this is the same command that I used before the upgrade. I reach the same situation if I run the test suite specifying the file to run. I have also tried to run the help function for the manage command and no --functions parameter is showed. I'm a little bit confused on this issue, and I don't find any information about this error in both, documentation and release notes. Anyone knows how this error is raised and how to fix it? I'm running Django 1.11.2 and Python 2.7 Thanks in advance -
Django DateTimeField was messy with naive and aware timestamp field in PostgreSQL
Version: Django 1.11 PostgreSQL 9.6 (AWS RDS) Django settings.py: TIME_ZONE = 'Asia/Seoul' USE_TZ = False My Problem: In last year, My django app migrated database from MySQL to PostgreSQL. It was fine. But I found big trouble. Tables that was generated in MySQL have DateTimeField, which correspond to naive timestamp field (without timezone) in PostgreSQL. But tables that was generated in PostgreSQL have DateTimeField, which correspond to aware timestamp field (with timezone). It stores all timestamp in UTC. So My DB tables was messy with naive and aware timestamp field. How do I fix this issue at best? The Followings are solutions I think, Convert naive timestamp fields to aware timestamp fields. I think It's best practice. But naive timestamp fields are too many. and I'm afraid that I lost data due to converting. Convert aware timestamp fields to naive timestamp fields. I think It's one of easy ways. But I heard naive timestamp fields are not practice. Nothing changed. Actually, I didn't know timestamp field is messy until I examine DB. Djano application has worked well now. But I worry It's big trouble in the future. Change timezone setting in AWS RDS. Is it possible and solution? Sorry for … -
The model has two many-to-many relations
Could someone kindly put me in the right direction?. trying to create multiple relations through the contact model. thanks class Contact(models.Model): user_from = models.ForeignKey(User, related_name='rel_from_set') user_to = models.ForeignKey(User, related_name='rel_to_set') hat_from = models.ForeignKey(User, related_name='hat_from_set') hat_to = models.ForeignKey(User, related_name='hat_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ('-created',) def __str__(self): return "{} is now a fan of {}'s page".format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField('self', related_name='fans', symmetrical=False)) User.add_to_class('follows', models.ManyToManyField('self', through_fields = ('hat_from', 'hat_to'), through=Contact, related_name='hats', symmetrical=False)) -
Fetch Json Field value using Values in Django
I have a JSON field in my model and by using values option, I would like to get the key value present in the JSON field. My Json Be like {"key1":"value1","key2":"value2"} Eg : MyClass.objects.values("field1","field2","JSON Key") Let JSON Key be "Key1" Expected O/P: [{field1:Value1,field2:value2,Key1:value1}] like this -
Embeding bokeh plot into a template (django)
I'm trying to embed a bokeh plot into a template (home.html), but nothing is displayed after executing the code. here's the code. views.py (all packages are imported) def home(request): s = [1,4,6,8] h = [1,5,9,8] p = figure(plot_width=600, plot_height=600) p.vbar(x=s, width=0.5, bottom=0, top=h, color="black") script, div = components(p, CDN) return render(request, 'home.html', {'div': div, 'script': script}) home.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Experiment with Bokeh</title> <script src="http://cdn.pydata.org/bokeh/release/bokeh-0.8.1.min.js"></script> <link rel="stylesheet" href="http://cdn.pydata.org/bokeh/release/bokeh-0.8.1.min.css"> </head> <body> <h1>hello</h1> {{ div|safe }} {{ script|safe }} </body> </html> it displays nothing at the end, there's no error message, but and the page is completely blank Help, Please!! -
Django newsetter by tag
I have some Django app, in which you can add tagged objects. There's sth like auto_tags = TagAutocompleteField(_(u'Tags'), default='', blank=True) in models.py file. How can I create a newsletter which will send an e-mail notification when a new object tagged with one of subscribed tags is created? Thanks in advance :D -
tasks being created with same task_id in queue
I am using Django-celery and Redis backend to push the tasks in celery queue. I am pushing tasks with same custom task_id in the queue. The documentation says that task_id is UUID which should be unique. But I am able to add more than one task with the same task_id in the queue. It is expected that it should raise an exception if a task with the same task_id is already there in the queue. @task def register_task(a, b): print a + b @task def deregister_task(a, b, c): print a + b + c taskid=str(UUID(md5('test').hexdigest())) register_task.apply_async(args=('hello', 'world'), task_id=taskid, countdown=60) deregister_task.apply_async(args=('sample', 'hello', 'world'), task_id=taskid, countdown=60) i = inspect() i.scheduled() {u'celery@Suyashs-MacBook-Pro.local': [{u'eta': u'2017-06-05T17:15:33.947002', u'priority': 6, u'request': {u'acknowledged': False, u'args': u"('sample', 'hello', 'world')", u'delivery_info': {u'exchange': u'celery', u'priority': 0, u'redelivered': None, u'routing_key': u'celery'}, u'hostname': u'celery@Suyashs-MacBook-Pro.local', u'id': u'098f6bcd-4621-d373-cade-4e832627b4f6', u'kwargs': u'{}', u'name': u'flight.tasks.deregister_task', u'time_start': None, u'worker_pid': None}}, {u'eta': u'2017-06-05T17:15:44.234537', u'priority': 6, u'request': {u'acknowledged': False, u'args': u"('hello', 'world')", u'delivery_info': {u'exchange': u'celery', u'priority': 0, u'redelivered': None, u'routing_key': u'celery'}, u'hostname': u'celery@Suyashs-MacBook-Pro.local', u'id': u'098f6bcd-4621-d373-cade-4e832627b4f6', u'kwargs': u'{}', u'name': u'flight.tasks.register_task', u'time_start': None, u'worker_pid': None}}]}