Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding periodic tasks in celery (django) inside an app
In celery 4> the periodic_task decorator is deprecated. The recommendation now is to define every periodic task inside where you initialize celery (based on what I can find, and the docs). In my django setup, I have a lot of small apps, and having a central place to setup period tasks won't do it. I am still learning my way around celery, but I think my solution is "good". Is this the wrong way to solve this, or is there another way now that periodic_task is gone? from celery.schedules import crontab from lib.celery_instance import app # The celery instance @app.task() def mytask(): # do something... return 123 app.add_periodic_task(crontab(hour=8, minute=45), mytask.s()) -
Django automatic remove whitespace in drop-down or select widget
django (1.10) removes automatic whitespaces in strings if they where displayed in a Listbox, dropdown or select widget. Example: original string is "Madrid Spain" is displayed as "Madrid Spain". This happens in my forms but also in the management forms. But I want to format my selection by 2 columns with 5 or more whitespaces as separator. I'm using the default render-settings: .. 'BACKEND': 'django.template.backends.django.DjangoTemplates', .. Thanks for any suggestions Regards Martin -
Django FilePathField doesn't work with relative path
There is a model Language. Language objects creates Admin through Django-admin. They have to choose from dropdown menu appropriate flag file. The problem is that there is not flag to choice when I deploy project. Since static files are being collected before deploy, I tried to set this path: flag = models.FilePathField(path='static/img/flags/550px',default='/static/img/icons/check-icon.png') But as you can see, it can't find anything. I can choose from flags if I do this: flag = models.FilePathField(path=settings.BASE_DIR+'/mainapp/static/img/flags/550px',default='/static/img/icons/check-icon.png') But then it doesn't work just calling language.flag because it returns absolute path. <img src = "{{ language.flag }}"> produce this: <img src="/home/django/MyProject/static/img/flags/550px/ar.png"> The only solution which comes to my mind is to create a property which strips path cutting "/home/django/MyProject/" but I'm not sure if it is a good idea. Is there a better way? class Language(models.Model): shortcut = models.CharField(max_length=40, help_text=_('Shortcut of the language'), unique=True) name = models.CharField(max_length=40, help_text=_('Name of the language'), unique=True, verbose_name=_("Language")) flag = models.FilePathField(path='mainapp/static/img/flags/550px',default='/static/img/icons/check-icon.png') def __str__(self): return self.name -
Custom Django management command not using the correct locale
I have a small open source website. Recently I started to move it to English as the default language making it easier to others people understand and contribute, but as my main target are Portuguese speakers I'm using translation strings. The running website correctly displays the Portuguese translated text, here. I have two commands that generates user facing content, which should also be presented in Portuguese. My problem happens with both commands generating English text, you can take a look of what I'm talking about on this Twitter profile, the "Missing" text should be "Desaparecido". My current understanding of the documentation is that I'd only need to set the leave_locale_alone option to True and it would use the locale present in the settings file. Am I missing some additional configuration? Note: I know that I can "lock" the language manually in the command but I'd like to avoid that, as I think it shouldn't be necessary. -
Decorator for CBV
I have this CBV: class GetStuff(View): def get(self, request, company_id): ... I want to decorate the get function with a custom function which takes the request and company_id arguments and check some permissions. Any idea on how to achieve this? Most information I've found about decorators focus on FBV. This is what I have so far: def custom_decorator(func_view): def wrapper(request, company_id): if not request.user.is_staff: # do_something() return func_view(request, company_id) return wrapper -
Can a change to a model from the front-end reflect on the model (history) at the back-end in Django?
I was just wondering, why? when I change a non staff user's name from the front end and post it it doesn't record that action e.g Guest01 logs in and he updates his profile adding first name and profile image but it doesn't show in the history yet I can see that the field has changed from the back-end. Now as the admin I decide to remove the profile image of Guest01 ,change the first name this time the action is recorded and goes to history. Now the question is can I make the change from the front-end reflect in the model history too or I have to use a 3rd party Audit Trail which would mean redundancy of the history button for my model? Please I'd like to know people's opinion on this If it makes any sense illustration of Model History -
Django Models outside of app directory migration not available
My models have been placed outside (as same level) of my Django app. Everything works fine, but when I run in my terminal: $ python manage.py makemigrations it returns: $ No changes detected my project tree is same as bellow: Project |_ app |_ migrations |_ admin.py . . . |_ models.py |_ urls.py |_ views.py |_config |_ settings.py |_ urls.py |_ wsgi.py |_core |_ MyModel.py I have just separated models outside of my app directory. How to add changes in MyModel.py to support migration? -
ImportError: cannot import name RequestSite
When trying to run python manage.py runserver I'm getting the following errors: Unhandled exception in thread started by <function wrapper at 0x103828e60> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate app_config.ready() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/admin/apps.py", line 23, in ready self.module.autodiscover() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/module_loading.py", line 50, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/registration/admin.py", line 2, in <module> from django.contrib.sites.models import RequestSite ImportError: cannot import name RequestSite I am running Django 1.10 and Python 2.7. -
Ajax Fail net::ERR_INCOMPLETE_CHUNKED_ENCODING
I'm doing ajax call to get some data from back-end to fill my datatables. get request status is 200, but I'm also getting this error net::ERR_INCOMPLETE_CHUNKED_ENCODING when get result is a big(for example more than 250 objects). So it nothing shows on my webpage. How can I solve this? Thanks!!! -
Django redirect() shortcut not working anymore?
If to redirect in the view like: @secure_required def school_index(request, school_id): school = get_object_or_404(School, pk = school_id) redirect('schools:school_events', kwargs= {'school_id': school.id} ) then I get the Error: Request Method: GET Request URL: http://127.0.0.1:8008/schools/20/ Django Version: 1.9.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'school_events' with arguments '()' and keyword arguments '{'kwargs': {'school_id': 20}}' not found. 1 pattern(s) tried: ['schools/(?P\d+)/events/$'] As I undestand, redirect() is just a shortcut which should return the HttpResponseRedirect for given object, url or a view. I provide correct name of the view, keyword argument but Django cannot match the url. What can be wrong? P.S. Everything is working fine if to use HttpResponseRedirect: @secure_required def school_index(request, school_id): school = get_object_or_404(School, pk = school_id) url = reverse('schools:school_events', kwargs= {'school_id': school.id}) return HttpResponseRedirect(url) -
Rendering images django and angular 1
In my project I use Django for the backend and Angular 1 for the frontend. When I try to add images to my html as follows {% static 'image/location/img.png'%} I get a 404 of this nature http://localhost:3000/%7B%%20static%20'image/location/img.png'%%7D 404 (Not Found) . Can anyone help me with setting up {% static .... %} to work. On the same note <img ng-src="/static/image/location/img.png"/> works okay but this approach seems rather hardcoded and would prefer to use the first approach. -
How to execute the ffmpeg thumbnail extraction command using sub-process in django?
The following code we are using to extract the thumbnail images from video ffmpeg -i low.mkv -vf thumbnail=10,setpts=N/TB -r 1 -vframes 10 inputframes%03d.png This code is working absolutely fine on terminal, but it is giving an error when we are processing the same with subprocess in django. Our aim is to generate 10 Thumbnails from any length of the video Here is the code vaild_fps = "'thumbnail=10,setpts=N/TB -r 1 -vframes 10'" subprocess.call([settings.FFMPEG_PATH, '-i', input_file_path, '-vf', vaild_fps, thumbnail_output_file_path, ] ) Error No such filter: 'thumbnail=10,setpts=N/TB -r 1 -vframes 10' Error opening filters! Proper solution is appreciable!! -
Define sorting key on Django model
I have two Django models, in which the one refers to the other. I want to be able to sort the second model based on the first. I think the code example below illustrates best what I want to achieve. class Record(models.Model): code = models.CharField(max_length=32) class Meta: ordering = ['code'] class Article(models.Model): code = models.CharField(max_length=32) def get_sorted_submodels(self): return sorted(self.submodels.all(), key=Submodel.key_sorting) class Submodel(models.Model): code = models.CharField(max_length=32) article = models.ForeignKey(Article, related_name='submodels') record = models.ForeignKey(Record, related_name='submodels' @staticmethod def key_sorting(obj): return (obj.record, obj.code) If I now call the method get_sorted_submodels, I get the following error: TypeError: unorderable types: Record() < Record() I already implemented the field ordering on model Record. How can I make this model orderable such that I can use this sorting mechanism? If that is not possible, is there another good way to enable sorting on Record first, and then on its own code? PS: I explicitly do not want to use class Meta and ordering on Submodel class, since this is basically a second ordering only used in this context. -
Django - live support chat
I'm using Django and I need to create a chat to give support to users... User has to be logged and he/she will only talk to support staff. I searched a bit and I found: django-message django-postman django-socketio Django-parakeet channels tornado centrifuge what chould I use? Can you tell me the best way to create this chat? Thanks! -
counter for number of NEW buttons clicked (HTML/Javascript)
I am new to programming and I am working with a table on otree were 256 different buttons are displayed using Javascript. Each buttons unveils an icon which is recalled by a simple function. In this function I have installed a simple click counter that increases by one each time a button is clicked. The simple click counter works fine (that is not my issue) :) The table: for(var r = 0; r < rows;r++) { table += '<tr>'; for(var c= 0; c< cols;c++) { var random = Math.floor(Math.random() * nums.length); table += '<td style="width:50px">' + '<button id="' + nums[random] + '" type="button" onclick="displayImage(this.id)">' + "show me" + '</button>' + '</td>'; nums.splice(random, 1); } table += '</tr>'; } The function: function displayImage(num){ document.canvas2.src = '{% static "bottone/'+ imagesArray[num]+ '.png" %}'; document.getElementById("YourImage2").style.visibility = "visible"; onClick(); } The counter: var clicks = 0; function onClick() { clicks += 1; document.getElementById("clicks").innerHTML = clicks; }; All good till here, there is a hidden HTML field and I manage to save the value of the counter when the user clicks the "next" button... My problem is the following: this counter counts the amount of buttons clicked, however I would like it to count only the … -
Django - variables in django templates
Is it possible to write something like this in django templates: {% for subcategory in category.subcategory.all %} <li style="padding-left:20px"> <a href="/{{category.slug}}/{{subcategory.slug}}"> {{ subcategory.name }} {{ sub_ + str(subcategory) }} </a></li> {% endfor %} <br> In my views.py I have: def index(request): context = {} categories = Category.objects.select_related() subcategories = SubCategory.objects.all() context['categories'] = categories context['subcategories'] = subcategories for subcategory in subcategories: sites = Site.objects.filter(subcategory=subcategory, is_active=True) print(sites.count()) context['sub_' + str(subcategory)] = sites.count() print(context) return render(request, 'mainapp/index.html', context) I need to count Sites in each subcategory. I thought I can do it by making sub_category1, sub_category2 variables. But I don't know how can I get it in my template. Any ideas? When I write {{ sub_category1 }} it works. I need to put -
QueryDict to a form
I have QueryDict: <QueryDict: {u'ok_txn_parent_id': [u'10'], u'ok_txn_fee': [u'10.00'], I need to extract all values from him to a form and then make form.is_valid How i can request all values? Thx for help. -
I have installed python 3.4 and attempted to use pip to manage packages but unfortunately i recieve this error
Operating System:Windows 10 C:\Python34>Ignoring indexes: https://pypi.python.org/simple/ 'Ignoring' is not recognized as an internal or external command, operable program or batch file. C:\Python34>Requirement already up-to-date: setuptools in c:\python34\lib\site-packages 'Requirement' is not recognized as an internal or external command, operable program or batch file. C:\Python34>Requirement already up-to-date: pip in c:\python34\lib\site-packages 'Requirement' is not recognized as an internal or external command, operable program or batch file. C:\Python34>Cleaning up... 'Cleaning' is not recognized as an internal or external command, operable program or batch file. I installed python 3.4.when i ran python -m endurepip,it says that is uptodate. But when I run this , it returns C:\Python34>pip install django 'pip' is not recognized as an internal or external command, operable program or batch file. even when i ran this command, C:\Python34>python -m pip --version pip 1.5.4 from C:\Python34\lib\site-packages (python 3.4) it displays pip. -
django.db.utils.ProgrammingError: multiple default values specified for column "id"
I was trying to change default primary key(automatic id index) to Facebook id, which now returns error I can't understand or avoid even by making everything as it was previously. So basically I'v just added this line to userporfile modal fb_id = models.BigIntegerField(primary_key=True) which resulted in following django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "blog_userprofile" How can I fix it? I am using Django 1.8 + PostgreSQL -
How to implement different permission in Django?
I have a model Payment with fields: date_created, comment, description, amount. Each payment belongs to User. class Payment(models.Model): author = models.ForeignKey('auth.User') amount = models.FloatField(max_length=10) description = models.CharField(max_length=128) created_date = models.DateTimeField( default=datetime.now()) comment = models.TextField(max_length=256) def __str__(self): return self.description Now I need to implement different roles for User: regular (can CRUD his payments), manager (can CRUD users), admin (can CRUD everything). So, the main question is how to implement this roles for users during registration (further it can't be changed). I also need to be able to set this role during registration via api (django rest framework). -
Redirect to login 'if user no authenticate'. App Django
Tell me please. How do redirect to 'login.html' from any other pages if user no athenticate? On Django. Thank you. Have a nice day! -
Distance in GeoDjango incorrect (gis.filter)
I am working on a project that would display all points in the database that are in range (10km). The problem is that the distance between point are incorrect, I have to increase the radius a lot in turn to get the points that are a lot closer in real life. I already looked for an answer and I found a lot of people mentioning SRIDs, but I don't know what they do and how to choose one. I am pretty new to this so I am not really sure what to do. I would be very thankful if somebody corrected my code and explained me what was wrong. I should probably mention that I use PostGis database. Views: from django.shortcuts import render from .models import item from django.contrib.gis.geos import GEOSGeometry from django.contrib.gis import measure def index(request): return render(request, 'search/index.html') def search(request): rad = request.GET['rad'] lat=float(request.GET['lat']) lon=float(request.GET['lon']) current_point = GEOSGeometry("POINT(%d %d)" % (lon, lat)) items = item.gis.filter(item_geom__distance_lte=(current_point, measure.Distance(km=rad))) return render(request, 'search/index.html',{'lat': lat,'lon': lon, 'rad': rad,'a': items}) Models: from django.db import models from django.contrib.gis.db import models as gismodels class item(gismodels.Model): item_title=models.CharField(max_length=100) item_description=models.TextField(max_length=500) item_geom = gismodels.PointField(u"longitude/latitude",geography=True, blank=True, null=True) gis = gismodels.GeoManager() objects = models.Manager() def __str__(self): return self.item_title+' - '+self.item_geom Thanks for … -
Python/Django upload in chunk, compute md5/sha1 on the fly in distributed system
I've a chunk upload system that allows people to upload a file in chunk. Now, at the end of the process I want to provide the md5 or sha1 of the whole file. md5/sha1 have the property update which should work great in case of chunks, you just need to update(content_of_the_chunk) for every chunk. The problem is: where and how I should store the md5/sha1 object? I'm using django, and i've several machine that handle the request. Such that I can't store the object in the session or in memory. I should put it in the database, but in the db I can only put the hexdigest (or a string) that then I can't sum or convert back to be used to do the update. How can I do? -
How to add a blank page and generate a menu using wagtail(nescode)?
I am using the open source nescode(The open source is below). https://github.com/nescode/wagtailcmsdemo I know how to create default wagtail's page. It can auto create the menu on the top bar when I select the "show in menus". And the result is below: But I don't know how to create a blank page. The blank page that I want to show highcharts figures(http://www.highcharts.com/). What is the processure for creating the page with highcharts? Thank you. -
Keycloak and Django
I have a Django app which I need to authenticate to via Keycloak. I am not very familiar with Keycloak so I don't really know what that entails and I can't seem to find anything about something similar at all. Has it been done at all? Can someone give my any pointers at all of what it would entail?