Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Importing Django module from a subfolder
I have a Django project where in the project's root folder (where manage.py is) I can do (venv) MyName-MacBook:mydjangoproject myname$ python >>> import django >>> from django.core.mail import EmailMessage, send_mail >>> However, when I create a subfolder, this doesn't work anymore (venv) MyName-MacBook:mydjangoproject myname$ mkdir subfolder && cd subfolder (venv) MyName-MacBook:subfolder myname$ python >>> import django >>> from django.core.mail import EmailMessage, send_mail Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/andrasnagy/Documents/drill/venv/lib/python3.6/site-packages/django/core/mail/__init__.py", line 11, in <module> from django.core.mail.message import ( File "/Users/andrasnagy/Documents/drill/venv/lib/python3.6/site-packages/django/core/mail/message.py", line 7, in <module> from email import ( File "/Users/andrasnagy/Documents/drill/email/email.py", line 2, in <module> from django.core.mail import EmailMessage, send_mail ImportError: cannot import name 'EmailMessage' >>> I realise this is a very basic question, but I am a bit stuck. It's strange that I can import django, but not the other functions. -
TemplateSyntaxError: Could not parse some characters:
A HTML file we're using in out project is working absolutely fine when ran independently but when inserted into DJANGO, this error occurs (it looks a bit over the top but it seems to be a problem with how JS methods/variables must be written in django?): TemplateSyntaxError at /rpg/play/ Could not parse some characters: var| a=i.objectName;i.typeName}return function(){function t(t,n,r){var i=l.children('[data-name="'+t+'"]'),o=a(n);i.length||(i=e('').appendTo(l)),i.empty().append(""+t+(r?""+r+"":"")+""+a(n)+"");var s=l.children();c.text(s.length+" Variable"+(1!==s.length?"s":""))}function i(){var r=[];l.children().each(function(i,o){o=e(o);var s=o.attr("data-name"),u=o.attr("data-value");s.startsWith("TwineScript")||(s in n.variables?(r.push(s),a(n.variables[s])!==u&&t(s,n.variables[s])):o.remove())});for(var i in n.variables)i.startsWith("TwineScript")|||r.includes(i)||t(i,n.variables[i])}var s=e("Turns: Debug View0 Variables"),u=s.find(".show-invisibles");u.click(function(){e(document.documentElement).toggleClass("debug-mode"),u.toggleClass("enabled")});var c=s.find(".show-variables"),l=s.find(".variables");c.click(function(){lc.is(".enabled")?"attr":"removeAttr",c.toggleClass("enabled")});var f=s.find("select");f.change(function(e){var t=e.target.value,r=t-n.pastLength;0!==r&&(n0>r?"rewind":"fastForward",o.showPassage(n.passage))}),n.on("forward",function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:!1,i=n.pastLength;i>1&&f.removeAttr("disabled"),r||(f.children().each(function(t,n){t>=i&&e(n).remove()}),f.append(""+(i+1)+": "+t+"").val(i))}).on("back",function(){n.pastLength<=1&&f.attr("disabled"),f.find("[selected]").removeAttr("selected"),f.val(n.pastLength)}).on("load",function(e){f.empty(),fe.length<=1?"attr":"removeAttr",e.forEach(function(e,t){return f.append(""+(t+1)+": "+e.passage+"")})}),n.on("forward",i).on("back",i),r.on("set",function(e,r,i){(e===n.variables||e.TwineScript_VariableStore)&&t(r,i,e===n.variables?"":e.TwineScript_VariableStoreName)}).on("delete",function(e,t){e===n.variables&&l.find('[data-name="'+t+'"]:not(.temporary)').remove()}),e(document.body).append(s) -
Formset created with inlineformset_factory doesn't render labels on page
I've got a formset: FormSet = inlineformset_factory( User, Profile, fields=('mychoice',), widgets={ 'mychoice': Select(choices=CHOICES) }, labels={ 'mychoice': _('mychoices:') } ) Instantiated in class based DetailView: class ProfileDisplay(DetailView): template_name = 'profile.html' model = User def get(self, request, *args, **kwargs): form = self.get_form() profile_form = ProfileFormSet(instance=self.request.user) return self.render_to_response( self.get_context_data(form=form, profile_form=profile_form) ) and shown in a template like: <form method="POST" action="."> <fieldset class="profile"> {{ profile_form.management_form }} {% for form in profile_form %} {% for field in form %} {{ field }} {{ field.label_tag }} {% endfor %} {% endfor %} </fieldset> </form> The problem is that label is not shown on the page, I'm getting only: <select name="profile-0-mychoice" id="id_profile-0-mychoice"> <option value="True" selected>mychoice true</option> <option value="False">mychoice false</option> </select> -
Django ORM group by, and find latest item of each group
Say we have a model as below class Cake(models.Model): baked_on = models.DateTimeField(auto_now_add=True) cake_name = models.CharField(max_length=20) Now, there are multiple Cakes baked on the same day, and I need a query that will return me a monthly cake report which consists of each day of the month, and the names of the first and last cakes baked on that day. For example, if the data is something like this: baked_on cake_name 11 Jan 12:30 Vanilla 11 Jan 14:30 Strawberry 11 Jan 20:45 Avocado 12 Jan 09:05 Raspberry 12 Jan 16:30 Sprinkles 12 Jan 20:11 Chocolate My query's output should look like date first last 11 Jan Vanilla Avocado 12 Jan Raspberry Chocolate How should I go about doing this in a single ORM call? -
Django rest-framework : Unit tests are using the production database
I'm currently working on a small app to learn about Django and Django-Rest-Framework and stumbled across a small issue related to unit testing. I just have two applications in my project : api (which provides a RESTful api to mess around with the DB), and web (which just sends queries to the api and applies a layout to render web pages). Nothing complicated. However, when launching unit tests, those testing the api work as expected and seem to use the temporary DB, but those testing the web application seem to use the production database. Here is my model (api.models) : class User(AbstractUser): country = models.CharField(max_length=32, verbose_name="Country of origin", name="country", blank=True, null=True) phone = models.CharField(max_length=32, verbose_name="Phone", name="phone", blank=True, null=True) field = models.CharField(max_length=32, verbose_name="Field of occupation", name="field", blank=True, null=True) occupation = models.CharField(max_length=32, verbose_name="Occupation", name="occupation", blank=True, null=True) birthdate = models.DateField(verbose_name="Birth Date", name="birthdate", auto_now_add=False, auto_now=False, blank=True, null=True) description = models.TextField(verbose_name="Description", name="description", blank=True, null=True) def __str__(self): return self.username Here is is the web view which causes problems (web.views): def profile(request, usrname): """Handles profile page behaviour and rendering""" stdlogger.info("PROFILE : request for home page") if request.method == "GET": # retrieve single profile stdlogger.debug("PROFILE_get : request for profile of '" + usrname + "' retrieval") r = … -
Bundling python dependencies in the project folder itself so as it can be easily shared and start application without downloading any dependencies
Whenever we download any python dependencies i.e django,MySQL by using 'pip' it get install in the root folder that would be c drive on windows( where we have install python). How can I install this dependencies in my project folder itself, so when I start my application it will read the dependencies from project folder rather from c drive. My purpose is whenever i give my application to user or third person he should directly start application instead of downloading all dependencies. -
multiprocessing django admin command
I have a django-admin command that reads from a database and then loops through the records returned, creates class instances and runs some methods. I would like to run some of these in parallel based on a group key. I've prepared the data so I would have a dictionary of groups with a list of items to process per group. results = {1: [{'id': 1}, {'id': 2}, {'id': 3}, 2: [{'id': 10}, {'id': 11}]} for each group number, 1 and 2, a separate process should be started, passing in the list of dictionaries containing the IDs. The called process will then loop through those IDs in turn. My simplified version of the admin command looks like this: from django.core.management.base import BaseCommand, CommandError import os import time import datetime from booker.models import BookingRequest from booker.automation.booking import Booker from django.conf import settings from itertools import groupby def shrink_dict(booking_dict, remove_list): for i in remove_list: del booking_dict[i] return booking_dict def make_booking_dict(qs): booking_dict = { key: [shrink_dict(b, ['group_id']) for b in group] for key, group in groupby(qs, lambda b: b['group_id']) } return booking_dict class Command(BaseCommand): help = 'Some help text' def add_arguments(selfsel, parser): pass def handle(self, *args, **options): requests = BookingRequest.objects.all() number_requests = len(requests) print('{} … -
Django - Truncated or oversized response headers received from daemon process
I'm using django (2.0.1) on Raspberry Pi 3 with DietPi on it. I've upgraded RPI today and got this error [Fri Mar 02 08:29:57.741991 2018] [wsgi:error] [pid 1564:tid 1861219376] [client 127.0.0.1:60308] Truncated or oversized response headers received from daemon process 'app': /home/user/app/app/wsgi.py, referer: http://app/ It worked well. My config for apache <VirtualHost *:80> TimeOut 120 ServerAdmin admin ServerName app ServerAlias app ErrorLog /home/user/app/logs/error_log CustomLog /home/user/app/logs/access_log common WSGIScriptAlias / /home/user/app/app/wsgi.py WSGIDaemonProcess appprocesses=6 python-path=/home/user/app:/home/user/app_env/lib/python3.5/site-packages header-buffer-size=65536 inactivity-timeout=300 WSGIProcessGroup app <Directory "/home/user/app"> Require all granted </Directory> Alias /robots.txt /home/user/app/static/robots.txt Alias "/static/admin/" "/home/user/app/root/admin/" <Location "/home/user/app/root/admin"> SetHandler None </Location> Alias "/media/" "/home/user/app/media/" <Location "/home/user/app/media/"> SetHandler None </Location> Alias "/static/" "/home/user/app/static/" <Location "/home/user/app/static/"> SetHandler None </Location> <LocationMatch "\.(jpg|gif|png|js|css)$"> SetHandler None </LocationMatch> <Directory "/home/user/app" > WSGIProcessGroup terminal WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> </VirtualHost> my /home/user/app/app/wsgi.py is standard from django. RPI connects trough USB0 to rfid-reader and because of this error I get a 500-error-page. I don't know where am I wrong. I hope you can help. -
How to render django select field in vuejs template?
I want to render a django form in Vuejs but I hit a wall. It's ok to render simple input like : <input id="my_field" name="my_field" > But I can't not use <select> in my vue template because I can't retrieve my select options. Do you know how to do or put me on track ? -
Django: Selectively Apply CSS Styles to Quiz Radio Buttons
I have users take a quiz. After each question, I want to show them whether their answer was correct or incorrect. The correct answer should be highlighted in Green, and their answer (if incorrect) should be highlighted in red (using Twitter Bootstrap styles). I am currently rendering the quiz results page in Django and HTML like so: {{ player.question }} <div class="myradio"> <label for="choice_1"><input id="id_1" type="radio" value="q1" disabled/> {{q1}}</label> </div> <div class="myradio"> <label for="choice_2"><input id="id_2" type="radio" value="q2" disabled /> {{q2}}</label> </div> <div class="myradio"> <label for="choice_3"><input id="id_3" type="radio" value="q3" disabled /> {{q3}}</label> </div> <div class="myradio"> <label for="choice_4"><input id="id_4" type="radio" value="q4" disabled /> {{q4}}</label> </div> <b><p>Correct Answer: {{solution}}</p><b> Total Score: {{total_score}} I am storing the solution to the question in {{solution}}. I have been trying to figure out how to selectively apply CSS filters if, for example, {{q1}} == {{solution}} that should be highlighted green. I can grab the participant's answer with {{player.submitted_answer}}, and so want to highlight a div element red if {{player.submitted_answer}} != {{solution}}. I have tried messing around with if statement blocks, but can't seem to get it right. Any ideas? -
error configuring Geodjango on Heroku
I've followed the steps laid out in Heroku to install geoDjango but am running into some obscure errors upon migration. I installed the dj-database-url library, and added the GDAL_LIBRARY_PATH settings to my settings as instructed here. I then got errors asking me to check that GDAL was installed. I searched around stackoverflow and figured I needed a buildpack for geodjango. I only installed this buildpack: https://github.com/cyberdelia/heroku-geo-buildpack and while it solved the initial errors, it now leaves me with this traceback: $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ paup... up, run.6303 (Free) /app/.heroku/python/lib/python3.6/site-packages/daphne/server.py:12: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on. UserWarning, Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, … -
How to set an expiry date for an object in django?
I am making a django app that shows routine orders for a college website. A particular order should remain for a week on the website and then disappear. This is my model. class RoutineOrder(models.Model): Subject = models.TextField() Details = RichTextUploadingField() LastEdited = models.DateTimeField(auto_now=True) Added = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('nitwro:home') What to do to accomplish this? -
Django modeltranslation too many fields
I want to translate the name field in the django application (1.11) using django-modeltranslation. I want to translate to en and fr, but in the admin panel I get 3 fields instead of two: name, name_en, name_fr. models.py class Country(models.Model): name = models.CharField(max_length=100) code = models.SlugField(max_length=20, default='') def __str__(self): return self.name admin.py class CountryAdmin(admin.ModelAdmin): list_display = ('name_en',) translation.py from events.models import Country class CountryTranslationOptions(TranslationOptions): fields = ('name',) translator.register(Country, CountryTranslationOptions) -
What's the sequence of middleware execution in django when error occurs in process_request?
I am looking into django middleware codebase. I looked into following diagram So, the diagram is quite clear. But I have some questions What happens when exception comes in process_request() middleware ? How is it handled ? Will the response_middleware be invoked ? Eg. if exception comes in process_view() of AuthenticationMiddleware, then will process_response() of MessageMiddleware be invoked ? What happens when in process_response() middleware returns response? Eg. if process_view() of AuthenticationMiddleware returns respones, then will process_response() of MessageMiddleware be invoked ? OR it'll turn back from AuthenticationMiddleware(ie, it'll invoke process_response() of AuthenticationMiddleware, but will not invoke process_response() of MessageMiddleware) I have debugged the behaviour of django in 1.10 where new style middleware classes are used, but I am not familiar about old MIDDLEWARE_CLASSES settings ? For django 1.10:- 1) If process_request() for AuthenticationMiddleware returns response, then process_template_response() and process_response() will be invoked as show in the figure given below for all the middlewares. 2) If process_request() for AuthenticationMiddleware raises exception, then also the behavior will be the same. Correct me, If I am wrong. Thanks in Advance. -
Django ORM Join on two columns
My models are following: waves/models.py class Assignment(models.Model): week = models.OneToOneField(Week) text = models.TextField() title = models.CharField(blank=True, max_length=255, default="") class Week(models.Model): wave = models.ForeignKey(Wave) ... class Wave(models.Model): name = models.CharField(unique=True, max_length=255) ... class AssignmentSubmission(models.Model): assignment = models.ForeignKey(Assignment) text = models.TextField() date_created = models.DateTimeField() ... waveexceptions/models.py class WaveException(models.Model): user = models.ForeignKey(User) wave = models.ForeignKey(Wave) deadline = models.DateTimeField() comments = models.TextField(blank=True) assignment = models.ForeignKey(Assignment, null=True, blank=True) ... I want to use django ORM to select the data from WaveException and annotate date_submitted which is the date when user from WaveException created AssignmentSubmission record. I did that using raw query: SELECT `waveexceptions_waveexception`.`id`, `waveexceptions_waveexception`.`user_id`, `waveexceptions_waveexception`.`deadline`, `waveexceptions_waveexception`.`comments`, `waveexceptions_waveexception`.`assignment_id`, `waves_assignmentsubmission`.`date_created` AS `date_submitted`, `auth_user`.`primary_key`, `auth_user`.`first_name`, `auth_user`.`last_name`, `waves_assignment`.`id`, `waves_assignment`.`week_id`, `waves_assignment`.`text`, `waves_assignment`.`title`, `waves_week`.`id`, `waves_week`.`end_date` FROM `waveexceptions_waveexception` INNER JOIN `auth_user` ON (`waveexceptions_waveexception`.`user_id` = `auth_user`.`id`) LEFT OUTER JOIN `waves_assignmentsubmission` ON (`auth_user`.`id` = `waves_assignmentsubmission`.`created_by_id` AND `waves_assignmentsubmission`.`assignment_id` = `waveexceptions_waveexception`.`assignment_id`) LEFT OUTER JOIN `waves_assignment` ON (`waveexceptions_waveexception`.`assignment_id` = `waves_assignment`.`id`) LEFT OUTER JOIN `waves_week` ON (`waves_assignment`.`week_id` = `waves_week`.`id`) Similar SQL query is generated with the following code: fields = ['deadline', 'user__first_name', 'user__last_name', 'comments', 'assignment__title', 'assignment__text', 'assignment__week__end_date'] queryset = WaveException.objects.select_related('user').select_related('assignment__week').only(*fields).annotate( date_submitted=F('user__assignmentsubmission__date_created') ) The only difference is that it does not do the join on assignment_id to waves_assignmentsubmission. How can I achieve this using ORM? I am using Python … -
Edit formset_factory
I am working on a small polling app where a user could edit the current choices of the question. I've been trying few different stuff but it seems not working at this moment. How would I edit the current choices (or add more choices) of the question? Here's what I got so far. Let me know what I could improve or miss in the code. Thanks. Views.py def edit(request, question_id): class RequiredFormSet(BaseFormSet): def __init__(self, *args, **kwargs): self.instances = kwargs.pop('instance') super(RequiredFormSet, self).__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False form.instance = True if question_id: question = get_object_or_404(Question, pk=question_id) else: question = Question() ChoiceFormset = formset_factory(ChoiceForm, max_num=10, extra=2, formset=RequiredFormSet) if request.method == 'POST': choice_formset = ChoiceFormset(request.POST, instance=question, prefix='choices') if choice_formset.is_valid(): for form in choice_formset.forms: form.save() return HttpResponseRedirect(reverse('polls:detail', args=(question.id))) else: choice_formset = ChoiceFormset(instance=question, prefix='choices') return render(request, 'polls/edit.html', {'question': question, 'choice_formset': choice_formset}) Edit.html <h2>{{ question.question_text }}</h2> <form action="" method="POST"> {% csrf_token %} {{ choice_formset.management_form }} {% for form in choice_formset.forms %} <div class="item"> {{ form.as_p }} <p style=""><a class="delete" href="#">Delete</a></p> </div> {% endfor %} <p><a id="add" href="#">Add another Choice</a></p> <input type="submit" value=" Submit " /> </form> Forms.py from django.forms import ModelForm, fields, models from .models import Question, Choice class QuestionForm(ModelForm): class Meta: model … -
Post in flask does not render new template
Let's say I have this setup Why after clicking "arrToPython" button flask does not redirect me to "query_result.html"? And more importantly, how can I make it to do so? I tried creating separate route like and using flask's "redirect" method, but it did not work for me either :( test.py: from flask import Flask from flask import request, url_for from flask import render_template from flask import redirect, Response app = Flask(__name__) @app.route('/', methods=['POST', 'GET']) def savingImage(): if request.method == 'GET': return render_template('test.html') if request.method == 'POST': return render_template('query_result.html') if __name__ == '__main__': app.debug = True app.run() Where test.html <!DOCTYPE html> <html> <head> <title></title> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <input id="arrToPython" type=button value="arrToPython" href="result" onclick = "arrToPython()"> <script type="text/javascript"> function arrToPython(){ var arr = ['one', 'two'] $.ajax({ type: 'POST', url: 'http://localhost:5000/', data: JSON.stringify(arr), }).done(function(){ console.log('sent'); }) } </script> </body> </html> And query_result.html <br> Hola amigo!</br> -
Deploy django with react on heroku, Uncaught SyntaxError
I have a simple django with react project and I want to publish it on heroku. I use webpack-bundle-tracker to get django and react working together. If I run it on my computer (first webpack, then runserver), everything works, but deployed on heroku, I get the Uncaught SyntaxError: Unexpected token < and if I open the bundle.js in chromes dev-tools, which is generated by the bundle-tracker and webpack, I see the same as in the index.html. I installed whitenoise helping with staticfiles, but this doesnt help. Here are the important files (lines): index.html <!DOCTYPE html> {% load render_bundle from webpack_loader %} <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>The App</title> <link rel="stylesheet" type="text/css" href="/static/dist/styles.css" /> </head> <body> <div id="container"></div> {% render_bundle 'main' %} </body> </html> settings.py (just the important lines) import django_heroku TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['static'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': '/dist/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } django_heroku.settings(locals()) package.json (just the scripts) "scripts": { "build:dev": "webpack", "build:prod": "webpack -p --env production", "test": "jest --config=jest.config.json", "heroku-postbuild": "yarn run … -
How to extend Django UserCreationForm to collect data on name, e-mail and D.O.B?
As stated in the title I would like my UserCreationForm to also include fields for D.O.B, name and e-mail. Here's my current views.py: from django.views import generic from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy # Create your views here. class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' Templates: {% extends 'base.html' %} {% block content %} <h3>Sign Up Page</h3> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Sign Up</button> </form> {% endblock %} -
Wildcard search in Django adminsite
am currently working on django. Now, I want achieve the wildcard search, to be more specifically, achieve precise searching using imprecise key words. For example, when I type 'a$c', all the matching results will be 'ac', 'abc', 'a!c', 'Ac', 'AC' and so on. Basically, '$(or maybe other characters)' could be numbers, could be letters or nothing. Is there any method to do this? BTW, my code for achieving the basic search function is written as below: class MetaboliteAdmin(admin.ModelAdmin): search_fields = ['id', 'name', 'compartment', 'charge', 'formula'] class ReactionAdmin(admin.ModelAdmin): search_fields = ['id', 'name','metabolites', 'gene_reaction_rule', 'subsystem'] class GeneAdmin(admin.ModelAdmin): search_fields = ['id', 'name', ''] I learned that I need to override the get_search_result to achieve my goal, but could someone tell me how to code? -
RabbitMQ or Redis exploding Celery queues with Django 2.0
I am encountering a problem with celery and Django 2. I have two running environments: Production: requirements.txt => No Issue amqp==2.2.2 django==1.11.6 celery==4.1.0 django-celery-beat==1.0.1 django-celery-monitor==1.1.2 kombu==4.1.0 redis==2.10.6 Development: requirements.txt =>Issue Present amqp==2.2.2 django==2.0.3 celery==4.1.0 django-celery-beat==1.1.1 django-celery-monitor==1.1.2 kombu==4.1.0 redis==2.10.6 The question What changed with Django 2 to make a system, which was stable with Django 1.11, unstable with exploding queue sizes, with the same effect in RabbitMQ and Redis? Application Settings Since I migrate my development environment to Django 2, my RabbitMQ queues or Redis queues are litterally exploding in size and my database instances keep on scaling up. It seems like the tasks are not removed anymore from the queues. I have to manually cleanup the celery queue which contains after a few days more 250k tasks. It seems that the TTL is set to "-1" however I can't figure out how to set it from django. After a few hours, I have more than 220k tasks waiting to be processed and growing. I use the following settings: available in file settings.py Warning: The names used might not be the correct ones for celery, a remap has been to correctly assign the values with the file celery.py # Celery Configuration … -
No module named 'raven' - when pushing to heroku
I'm using cookiecutter django. I do recall not setting raven when I initially started a new cookiecutter project, so I think it does make sense that raven was not installed. However, when I try to run heroku run python manage.py migrate, I am stopped with the error of ModuleNotFoundError: No module named 'raven' How can I get around this in order to push to heroku? Traceback: $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ paup... up, run.8760 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/logging/config.py", line 378, in resolve found = self.importer(used) ModuleNotFoundError: No module named 'raven' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/logging/config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "/app/.heroku/python/lib/python3.6/logging/config.py", line 708, in configure_handler klass = self.resolve(cname) File "/app/.heroku/python/lib/python3.6/logging/config.py", line 391, in resolve raise v File "/app/.heroku/python/lib/python3.6/logging/config.py", line 378, in resolve found = self.importer(used) ValueError: Cannot resolve 'raven.contrib.django.raven_compat.handlers.SentryHandler': No module named 'raven' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 22, … -
Gunicorn log HTTP requests made
I am running gunicorn with the below config $VIRT_ENV/gunicorn -c config.py utrade.wsgi:application \ --log-level=debug \ --timeout=0 \ --access-logfile=-\ --log-file=- However it won't log HTTP requests (POST/GET) like Django would do if ran standalone. Like the ones below INFO:django.server:"GET / HTTP/1.1" 302 0 INFO:django.server:"GET /login/?next=/ HTTP/1.1" 200 5676 -
i get the error of gevent isn't a socketpool backend when installing commcare-hq
i'm installing dimagi/commcare-hq https://github.com/dimagi/commcare-hq i've followed all the steps so far until i reached setting up the django environment, when ever i insert the command ./manage.py sync_couch_views i get the error below (commcare-hq) gasha@ubuntu:~/commcare/commcare-hq/commcare-hq$ ./manage.py sync_couch_views Traceback (most recent call last): File "./manage.py", line 123, in <module> from restkit.session import set_session; set_session("gevent") File "/home/gasha/commcare/commcare-hq/local/lib/python2.7/site-packages/restkit/session.py", line 41, in set_session backend=backend_name, **options) File "/home/gasha/commcare/commcare-hq/local/lib/python2.7/site-packages/socketpool/pool.py", line 53, in __init__ self.backend_mod = load_backend(backend) File "/home/gasha/commcare/commcare-hq/local/lib/python2.7/site-packages/socketpool/util.py", line 71, in load_backend raise ImportError(error_msg) ImportError: gevent isn't a socketpool backend -
Checkboxes to select objects in Django
I have Article model and user wants to select which articles should be exported to file. I want to use Django Form / ModelForm class to generate something like: <input type="checkbox" name="articles[0]">Article #0</input> <input type="checkbox" name="articles[1]">Article #1</input> <input type="checkbox" name="articles[2]">Article #2</input> <!-- ... --> How can I do that and then get selected articles?