Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What's this after aggregation in django?
I see the following code from a django project. I understand it's aggregation, but what's ['kw__sum'] after the aggregation? Project.objects.filter(project = project).aggregate(Sum('kw'))['kw__sum'] Thanks -
How to use simple-menu in django?
I have below html code for submenu. Now i have to integrate with my django application. HTML Code : <nav class="main-navigation" data-height="auto" data-size="6px" data-distance="0" data-rail-visible="true" data-wheel-step="10"> <p class="nav-title">MENU</p> <ul class="nav"> <!-- dashboard --> <li> <a href="a.html"> <i class="ti-home"></i> <span>Dashboard</span> </a> </li> <li> <a href="javascript:;"> <i class="toggle-accordion"></i> <i class="ti-support"></i> <span>Category1</span> </a> <ul class="sub-menu"> <li> <a href="SubCategory1.html"> <span>Sub Category1</span> </a> </li> <li> <a href="SubCategory2.html"> <span>Sub Category2</span> </a> </li> </ul> </li> <li> <a href="javascript:;"> <i class="toggle-accordion"></i> <i class="fa fa-file-text-o"></i> <span>Category2</span> </a> <ul class="sub-menu"> <li> <a href="SubCategory7.html"> <span>SubCategory7</span> </a> </li> </ul> </li> </nav> I have used simple-menu module for that. but i don't understand how to apply bootstarp class in simple menu which are in below code. For this submenu i have to use simple-submenu ? i have try simple-menu Code is below. <nav class="main-navigation" data-height="auto" data-size="6px" data-distance="0" data-rail-visible="true" data-wheel-step="10"> <p class="nav-title">MENU</p> <ul class="nav"> {% for item in menu%} <li> <a href="{{ item.url }}"> <i class="ti-home"></i> <span>{{ item.title }}</span> </a> </li> <li> <ul class="sub-menu"> {% for child in item.children%} <li> <a href="{{ item.url }}"> <span>{{ child.title }}</span> </a> </li> </ul> </li> <!-- /ui --> </nav> On above code how to apply different classes in for loop for particular html tag ? -
Django not parsing URL as expected
I am currently working on a project using Django and Angular. I am trying to implement Django's Password-Reset app, which seems pretty easy to set up. I followed the instructions and I ran into a peculiar issue. I am trying to link to a FormView using <a href="{% url 'password_reset_recover' %}">Forgot password?</a> but for some reason Django is parsing the URL as http://127.0.0.1:8000/%7B%%20url%20'password_reset_recover'%20%%7D This causes this error to pop up: Error: malformed URI sequence Anyone know what could be Django to parsing the URL like this? I have the charset set as unicode and the url exists in my urls.py file so that isn't the issue. -
Django filter models.DateTimeField
Is it possible to filter a models.DateTimeField but only get the month in the filter object? The field is: time_stamp = models.DateTimeField( default=timezone.now) When I filter it, this is what I get: [datetime.datetime(2016, 9, 22, 15, 2, 48, 867473, tzinfo=), datetime.datetime(2016, 9, 22, 15, 4, 22, 618675, tzinfo=), datetime.datetime(2016, 9, 22, 15, 5, 20, 939593, tzinfo=)] The filter returns 3 rows, but clearly there is too much information. I only require the months, and maybe the year. How can I achieve this? Any help or direction would be appreciated, Thanks -
How to allow Tornado Web Server serve only local requests?
I am using Django for main project + Tornado for some async staff. So, some Django apps requests Tornado via http. And Tornado server is accessible by mywebsite.com:8888 in browser. I want to throw 403 error or disable it at all for users if possible, and make it work only for local request from Django. How can I do it? Can nginx help me? Or there is some cool feature in Tornado? Or some unix staff? Big thx for advices! -
I add plugin to my django cms when I to publish and view the page, It's alway report the error Project matching query does not exist
I add plugin to my django cms when I to publish and view the page, It's alway report the error Project matching query does not exist.All my plugin page report this error.Where is the error take palce? DoesNotExist at /dpdk/testcenter/testcase/ Project matching query does not exist. Request Method: GET Request URL: http://10.239.173.54/dpdk/testcenter/testcase/?preview=1 Django Version: 1.5.8 Exception Type: DoesNotExist Exception Value: Project matching query does not exist. Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in get, line 404 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/wuwenzhong/itms', '/home/wuwenzhong/itms/itrac_2', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Wed, 28 Sep 2016 08:57:01 +0800 Error during template rendering In template /home/wuwenzhong/itms/templates/testcase.html, error at line 9 Project matching query does not exist. 1 {% extends "frame.html" %} 2 3 {% block base_content %} 4 <div class="case_class"> 5 <div class="ui_head_area"> 6 <span class="head_title">TestCase Management</span> 7 <hr> 8 </div> 9 {% placeholder case_placeholder_01 %} 10 {% placeholder case_placeholder_02 %} 11 </div> 12 13 <div class="ui_footer"> 14 <span class="footer_text">iTMS | © Intel Corporation</span> 15 </div> 16 17 {% addtoblock "css" %} 18 <link href="{{ STATIC_URL }}casecenter/static/css/casecenter.css" rel="stylesheet" type="text/css"/> 19 {% endaddtoblock %} -
Django: how to set the path for the environ variable "DJANGO_SETTINGS_MODULE"
In Django, I used to write populating scripts and put them in the project root directory. For example, mysite/ mysite/ manage.py populateA.py The first few lines of populateA.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') import django django.setup() ... As there are more and more populating scripts, I would like to move them to another package populate: mysite/ mysite/ manage.py populate/ __init__.py populateA.py populateB.py populateC.py ... However, when I run the populating scripts (python populateA.py), I got the error message: ImportError: No module named 'mysite'. How to properly set the path for DJANGO_SETTINGS_MODULE? -
`manage.py runserver` and Ctrl+C (Django)
When I quit Django manage.py runserver with Ctrl+C, do threads running HTTP request finish properly or are they interrupted in the middle? -
cannot accessing a simple database in django
I went through the django doc polls example. Now I have a database name.info.db available. I put it in same directory as manage.py, also where db.sqlite3 is. I changed settings.py to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'name.info.db'), }} My models.py is class PItable(models.Model): pid_text = models.CharField(max_length=200) lname_text = models.CharField(max_length=200, null=True) fname_text = models.CharField(max_length=200, null=True) affs_text = models.CharField(max_length=2000, null=True) pmidlist_text = models.CharField(max_length=2000, null=True) clustering_text = models.CharField(max_length=2000, null=True) def __str__(self): return self.fname_text I deleted Question and Choice(from polls example) from views and models. I did python manage.py makemigrations pidb python manage.py migrate I got the following message which didn't show my database, still showed the deleted models(Question, Choice). What did I do wrong here? When I access from python shell PItable.objects.filter(id=1), it shows empty[]. Thanks for any help!! $ python manage.py sqlmigrate pidb 0001 BEGIN; -- Create model Choice CREATE TABLE "pidb_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL); -- Create model Question CREATE TABLE "pidb_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL); -- Add field question to choice ALTER TABLE "pidb_choice" RENAME TO "pidb_choice__old"; CREATE TABLE "pidb_choice" ("id" integer NOT NULL … -
Expanding a template in an other templates' block
I have to do a little websites rendering a few pages with static content. The pages are based on a base.html template, this template has a content block. The pages may have (or not) an aside element (always the same aside). Thus far I can do something like this : page.html : {% expands "base.html" %} {% block content %} {% include "page-content.html" %} {% endblock %} page-content.html : {% expands "content-with[out]-aside.html" %} {% block content %} foo {% endblock %} content-with-aside.html : <div> <div> {% block content %} {% endblock %} </div> <aside> aside <aside> </div> content-without-aside.html : <div> <div> {% block content %} {% endblock %} </div> </div> But that supposes using a template with no usefulness but defining if the page has or not the aside. I could also define a base-with-aside.html and a base-without-aside.html templates. But could I do something like this? page.html : {% expands "base.html" %} {% block content %} {% expandblock "content-with[out]-aside.html" %} {% block content %} foo {% endblock %} {% endexpandblock %} {% endblock %} In Jinja perhaps? At worst case I could define a custom template tag, but I would like to know it there already is a feature like … -
Editing a table entry that has a foreign key with inlineformset_factory and Jquery AJAX
I have been working on an simple address book app in Django. Id like to have a single Contact name with any number of Address connected to that contact via a foreign key...straightforward enough. My issue is that when the inlineformset is POST 'd to the server, it always adds a new table entry, despite the fact that the form was loaded and initialized correctly. Example, if a Contact has a work address and a home address, and I try to 'edit' the existing work address...the POST view creates a second work address with the all the updated info, the original entry I was trying to edit is still present, untouched. Here is my code...what am I missing. Model.py class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('__all__') class AddressForm(forms.ModelForm): class Meta: model = Address fields = ('contact','address_name') AddressFormSet = modelformset_factory( Address, AddressForm,) AddressInlineFormSet = inlineformset_factory( Contact, Address, fields=('address_name',), extra=0, min_num=1, max_num=1, can_delete=True) My POST conditional in my views.py Im thinking this is the problem...when Im editing how do line up the form Address form with Address Entry? if request.method == 'POST': ## On a POST, Retrieve the QueryDict data coming from AJAX POST JSON_Datalist = request.POST ## Convert … -
How can I filter exported tickets from database using Django?
I am working on a Django based web project where we handle tickets based requests. I am working on an implementation where I need to export all closed tickets everyday. My ticket table database looks like, ------------------------------------------------- | ID | ticket_number | ticket_data | is_closed | ------------------------------------------------- | 1 | 123123 | data 1 | 1 | ------------------------------------------------- | 2 | 123124 | data 2 | 1 | ------------------------------------------------- | 3 | 123125 | data 3 | 1 | ------------------------------------------------- | 4 | 123126 | data 4 | 1 | ------------------------------------------------- And my ticket_exported table in database is similar to ---------------------------------- | ID | ticket_id | ticket_number | ---------------------------------- | 10 | 1 | 123123 | ---------------------------------- | 11 | 2 | 123124 | ---------------------------------- so my question is that when I process of exporting tickets, is there any way where I can make a single query to get list of all tickets which are closed but ticket_id and ticket_number is not in ticket_exported table? So when I run functions it should get tickets with ticket_id '3' and '4' because they are not exported in ticket_export database. I don't want to go through all possible tickets and check one by … -
Could not browse django site
I'm trying to follow the the django tutorial but when when I get to the python manage.py runserver step, I can't browse http://127.0.0.1:8000/ in chrome or IE. But when I wget in bash, I was able to get the html from http://127.0.0.1:8000. I'm using windows 10 anniversary edition and I'm using virtualenv. -
How I spend a php code to python / django?
I need to make a txt file with data from post. They told me that the best way to use the python. How do I pass this to python or make this work in django? <?php if ($_POST["enviar"]){ $nomealuno = $_POST["nomealuno"]; $raaluno = $_POST["raaluno"]; $emailaluno = $_POST["emailaluno"]; $curso = $_POST["cursoaluno"]; $disciplina = $_POST["materia"]; $empresa = $_POST["empresa"]; $datainicio = $_POST["datainicio"]; $datafinal = $_POST["datafinal"]; $hrssemanais = $_POST["hrssemanais"]; $conteudo = "nome: $nome\rra: $raaluno\remail: $emailaluno\r curso: $cursoaluno\rmatéria: $disciplina\rempresa: $empresa\r periodo: de $datainicio até $datafinal\rhoras semanais: $hrssemanais\r\n"; $arquivo = "$raaluno" + "_$diciplina" + ".txt"; $abrir = fopen($arquivo, "w"); fwrite($abrir, $conteudo); fclose($abrir); } ?> <html> <body> <form action="/docs/enviado/" method="post">{% csrf_token %} <p>Matéria a solicitar matrícula: </p> <input type="radio" name="materia" id="MC018" value="MC018" /> <label>MC018</label><br /> <input type="radio" name="materia" id="MC019" value="MC019" /> <label>MC019</label><br /> <input type="radio" name="materia" id="MC020" value="MC020" /> <label>MC020</label><br /> <p>RA do aluno: </p> <input name = "raaluno" rows="1" placeholder="RA do aluno"></input> <p>Nome do aluno: </p> <input name = "nomealuno" rows="1" placeholder="Nome do aluno"></input> <p>Curso do aluno: </p> <input name = "cursoaluno" rows="1" placeholder="Curso do aluno"></input> <p>Email do aluno: </p><!--verificar @.unicamp.br--> <input name = "emailaluno" rows="1" placeholder="Email do aluno"></input> <p>Nome da empresa: </p> <input name = "empresa" rows="1" placeholder="Nome da empresa"></input> <p>Data de ínicio: </p> <input … -
channels.asgi.InvalidChannelLayerError: no BACKEND specified for default
I'm trying to use channels for a django app.I have installed all the required dependencies (i think). I have listed 'channels' on INSTALLED_APPS of myapp/settings.py.However,I run daphne ( daphne chat.asgi:channel_layer --port 8888)-( no error message on cmd), then when i run python manage.py runworker which gives an Error message that says - "channels.asgi.InvalidChannelLayerError: no BACKEND specified for default". . I'm novice for django, i have asgi.py as import os import channels.asgi os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chat.settings") channel_layer = channels.asgi.get_channel_layer() But in my myapp/settings.py, i have specified the BACKEND specified for default.Can you please suggest a solution to this error? Here is a probable solution,but the asgi_redis was current in my django1.10. CHANNEL_LAYERS = { "default": { "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { #"hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, "ROUTING": "mysite_djangogirls.chat.routing.channel_routing", }, } -
Django Google API Client Error..Trying to implement an application that adds events to a users google calendar after authentication
While using the OAuth authentication method I am unable to retrieve the authentication code from the url. Google redirects me to a url with code appended to its end ..I think I am making a mistake in the regex because after authenticating myself and giving the app the permission to manage my calendar I am redirected to http://127.0.0.1/Main/addloanpremium/?code=4/2wi1hu0Gv8YZuKo79kc-kjCmw7qj0W2EyLYa3qzIe7w# ..How do I extract the code from the url..The above url opens on a new tab and due to my urls.py displays the same form page however when I try to access the 'code' value using request.GET.get('code') it does not give any value.. Exception Value: Can't convert 'NoneType' object to str implicitly My views.py looks like: def addloanpremium(request): if request.method == 'GET': loan=Loan() premium=Premium() user=request.user #form=loan_pre_form(request.POST) if(request.GET.get('typelp')=='loan'): loan.user=user #premium.user=user #lots of code here..all values from fields are stored into the db if(request.GET.get("iscalendar")=="True"): print(" \n \n entered iscalendar =true \n") print(" \n \n entered calendar now trying to add event \n \n") SCOPES = 'https://www.googleapis.com/auth/calendar' flow=auth2client.client.flow_from_clientsecrets('C:/Users/ghw/Desktop/Expenze/Main/client_secrets.json',SCOPES,redirect_uri='http://127.0.0.1:8000/Main/addloanpremium/') storage = oauth2client.file.Storage('credentials.dat') credentials = storage.get() if not credentials or credentials.invalid: auth_uri = flow.step1_get_authorize_url() print("\n value of auth uri is "+auth_uri+"\n") webbrowser.open(auth_uri) auth_code = request.GET.get('code') print("\n value of auth code is "+auth_code+"\n") ### I am getting the … -
Adding permissions when user is saved in Django Rest Framework
I'm creating an instance of a User object. The creation itself is a standard User.objects.create_user call and that works ok - user is created. After that, I'm trying to add a few permissions to him or her: for name in ('view_restaurant', 'change_restaurant', 'delete_restaurant', 'view_meal', 'add_meal', 'change_meal', 'delete_meal', 'view_order', 'delete_order', 'view_historicalorder', 'add_historicalorder', 'change_historicalorder', 'view_orderitem', 'view_historicalorderitem', 'view_restaurantemployee', 'add_restaurantemployee', 'change_restaurantemployee', 'delete_restaurantemployee'): permission = Permission.objects.get(codename=name) print(permission is None) user.user_permissions.add(permission) user.save() print(user.has_perm(permission)) As you can see, in the last line I'm checking whether the user was assigned with an appropriate permission, and few lines above I'm checking if permission is None. The result is that the permission object is never none, but user.has_perm call always returns false. What am I doing wrong here? -
Changed Django model attribute and now getting error for it
I had a model with a DateField that worked just fine. I wanted to change it from a DateField to a CharField. Before: class NWEAScore(models.Model): test_date = models.DateField(default=date.today, verbose_name='Test Date') After: class NWEAScore(models.Model): year = models.CharField(max_length=50, choices=YEAR_CHOICES, default=SIXTEEN) season = models.CharField(max_length=50, choices=SESSION_CHOICES, default=FALL) Not sure what went wrong but now I'm getting an error. Making migrations is no problem. I make them and then upload them to my server, then when I migrate, I get an error. The Error I get when I try to apply my migrations: (venv) alex@newton:~/newton$ python manage.py migrate Operations to perform: Apply all migrations: admin, amc, auth, brain, contenttypes, ixl, nwea, sessions Running migrations: Rendering model states... DONE Applying brain.0021_auto_20160927_0038... OK Applying nwea.0011_auto_20160927_0038...Traceback (most recent call last): File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/models/options.py", line 612, in get_field return self.fields_map[field_name] KeyError: 'test_date' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/alex/newton/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/alex/newton/venv/lib/python3.4/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/home/alex/newton/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "/home/alex/newton/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 97, in … -
How to refresh an option list. DJANGO, AJAX & JQUERY
I need to refresh an option list of Remedios, after insert a new element in this object.. So when im in "Registrar Solicitud" i have the option to insert an element to Remedios object that send me to "Registrar Remedios". I just want to close the form when i finish and refresh the list in my first page "Registrar Solicitud" Registrar Solicitud.html here the most important part of the code <div class="form-group"> <label for="paciente" class="control-label col-md-2 col-md-2 col-md-offset-2">Paciente:</label> <div class="col-md-5"> {% for elemento in id_paciente %} <input class="form-control" id="id_paciente" name="id_paciente" type="hidden" value="{{elemento.id}}"/> <input class="form-control" type="text" readonly="readonly" value="{{elemento.apellido}}, {{elemento.nombre}}"/> {% endfor %} </div> </div> <div class="form-group"> <label for="medico" class="control-label col-md-2 col-md-2 col-md-offset-2">Medico:</label> <div class="col-md-4 text-left"> <select name="id_medico" id="id_medico" class="form-control col-md-1 chosen-select " data-placeholder="Busqueda..." required> <option value=""></option> {% for elemento in medico_enviado %} <option value="{{elemento.persona_ptr_id}}" >{{elemento.apellido}}, {{elemento.nombre}} --Dni: {{elemento.dni}}</option> {% endfor %} </select> </div> <a class="related-widget-wrapper-link add-related" id="add_id_medico" href="/aplicacion/registrarmedico/" target="_blank" title="Agregar otro/a medico"> <img src="/static/img/icon_addlink.gif" alt="Agregar" height="10" width="10"> </a> </div> <div class="form-group"> <label for="remedio" class="control-label col-md-2 col-md-2 col-md-offset-2">Remedio:</label> <!--THE DIV (LIST) THAT I NEED TO REFRESH--> <div id="contenido" class="col-md-4 text-left"> <select name="id_remedio" id="id_remedio" class="form-control col-md-1 chosen-select " data-placeholder="Busqueda..." required> <option value=""></option> {% for elemento in remedio_enviado %} <option value="{{elemento.id}}" >{{elemento.generico}}</option> {% endfor … -
TemplateDoesNotExist at /accounts/register/ Error
So I am new to Django and am currently trying to build registration into my app. I have already followed this guide. However I am running into an issue in which the application is not able to find the template somehow. Traceback: File "/usr/local/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/usr/local/lib/python3.5/site-packages/django/template/response.py" in render 109. self.content = self.rendered_content File "/usr/local/lib/python3.5/site-packages/django/template/response.py" in rendered_content 84. template = self.resolve_template(self.template_name) File "/usr/local/lib/python3.5/site-packages/django/template/response.py" in resolve_template 66. return select_template(template, using=self.using) File "/usr/local/lib/python3.5/site-packages/django/template/loader.py" in select_template 53. raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) Exception Type: TemplateDoesNotExist at /accounts/register/ Exception Value: registration/registration_form.html I have checked to make sure my URL are set and everything should be in order. I have spent the past 2 hours looking for a solution to this and nothing is working. The things that gets me the most is that in the error I can see where it checks for the template in the exact place I have it yet I am still seeing the following next to the actual path in which this template should be. (Source does not exist) Please help -
setup a database in django
I followed the django doc and went through the polls example. I have a sqlite db 'nameinfodb'. I want to access it by search last name online. I setup models.py as class Infotable(models.Model): pid_text = models.CharField(max_length=200) lname_text = models.CharField(max_length=200) fname_text = models.CharField(max_length=200) affs_text = models.CharField(max_length=2000) idlist_text = models.CharField(max_length=2000) def __str__(self): return self I copied name.info.db to where db.sqlite3 locates, changed settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'name.info.db'), } } Then I run python manage.py migrate python manage.py makemigrations pidb Then I checked if I did correctly $ python manage.py sqlmigrate pidb 0001 BEGIN; -- -- Create model Choice -- CREATE TABLE "pidb_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL); -- -- Create model Question -- CREATE TABLE "pidb_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL); -- -- Add field question to choice -- ALTER TABLE "pidb_choice" RENAME TO "pidb_choice__old"; CREATE TABLE "pidb_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "votes" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "pidb_question" ("id")); INSERT INTO "pidb_choice" ("id", "question_id", "choice_text", "votes") SELECT "id", NULL, "choice_text", "votes" FROM "pidb_choice__old"; DROP TABLE … -
Celery Beat - Worker Consuming Messages, But Never Acks. Them
I've got a simple Django site that I'd like to add some scheduled tasks to via Celery / RabbitMQ. I'm stuck, because, while the beat scheduler pumps out tasks with no issues, the worker fails to consume them. The worker never marks them as acknowledged in RabbitMQ. Here's my Celery configuration from ego.settings; from celery.schedules import crontab ... # Celery configuration BROKER_URL = os.environ.get('BROKER_URL', 'amqp://guest:guest@localhost:5672') CELERY_RESULT_BACKEND = os.environ.get('CELERY_RESULT_BACKEND', 'disabled') CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERYBEAT_SCHEDULE = { 'account-notifications': { 'task': 'ego.celery.account_alerts', 'schedule': crontab(), }, } My celery entrypoint (ego.celery; from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ego.settings') from django.conf import settings app = Celery('ego') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task def account_alerts(): print("nothing here, yet") No, I didn't forget ego.__init__ :) from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app The logs from beat look normal, but the worker is very quiet. … -
ProgrammingError: (1146, "Table 'intranet.django_session' doesn't exist")
Hola si alguien puede ayudarme error al momento de hacer migración en django desde sqlite 3 a mysql, al momento de hacer un migrate sale: ProgrammingError: (1146, "Table 'intranet.django_session' doesn't exist") [27/Sep/2016 14:38:46] "GET /admin/ HTTP/1.1" 500 59. Sin embargo hago un levantamiento del servidor a través de un runserver y levanta pero cuando ingreso la URL:127.0.0.1:8000/admin me dice: "A server error occurred. Please contact the administrator." -
DateTimeInput widget types in a custom form
What kind of types I can pass into a widget? Got a class Meta in forms.py and I want to override a 'deliver_till' field to display a date-time calendar to select proper data in a template. models.py deliver_till = models.DateTimeField(blank=False) forms.py widgets={ 'deliver_till' : forms.DateTimeInput(attrs={'type':'date'})} It works fine - I get a date field that pops up as a calendar. Is is possible to change the 'type' to achieve an admin-like calendar with time selection also? Or is it only possible using an extra jquery datetimepicker? -
How do I query a complex JSONB field in Django 1.9
I have a table item with a field called data of type JSONB. I would like to query all items that have text that equals 'Super'. I am trying to do this currently by doing this: Item.objects.filter(Q(data__areas__texts__text='Super')) Django debug toolbar is reporting the query used for this is: WHERE "item"."data" #> ARRAY['areas', 'texts', 'text'] = '"Super"' But I'm not getting back any matching results. How can I query this using Django? If it's not possible in Django, then how can I query this in Postgresql? Here's an example of the contents of the data field: { "areas": [ { "texts": [ { "text": "Super" } ] }, { "texts": [ { "text": "Duper" } ] } ] }