Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery beat serving old (removed) task
Under supervisor, celery beat serves periodic tasks to celery workers for a Django app of mine. I have 4 tasks, task1, task2, task3, and task4. Recently I made a 5th task: task5. My problem is that I commented out task5 from my workers, removed its mention from settings.py and restarted celerybeat and my celery workers. But I still see task5 periodically showing up (throwing an error in the workers' logs naturally). Why is this happening, and how can I update the periodic tasks? In settings.py, I have: CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler' CELERYBEAT_SCHEDULE = { 'tasks.task1': { 'task': 'tasks.task1', 'schedule': timedelta(seconds=45), }, 'tasks.task2': { 'task': 'tasks.task2', 'schedule': timedelta(seconds=60), # execute every 60 seconds 'args': (), }, 'tasks.task3': { 'task': 'tasks.task3', 'schedule': timedelta(seconds=90), # execute every 90 seconds 'args': (), }, 'tasks.task4': { 'task': 'tasks.task4', 'schedule': timedelta(seconds=90), # execute every 90 seconds 'args': (), }, } /etc/supervisor/conf.d/celerybeat.conf contains the following: command=python manage.py celery beat -l info directory = /home/myuser/myproject/ environment=PATH="/home/myuser/envs/myenv/bin",VIRTUAL_ENV="/home/myuser/envs/myenv",PYTHONPATH="/home/myuser/envs/myenv/lib/python2.7:/home/myuser/envs/myenv/lib/python2.7/site-packages" user=mhb11 numprocs=1 stdout_logfile = /etc/supervisor/logs/celerybeat.log stderr_logfile = /etc/supervisor/logs/celerybeat.log autostart = true autorestart = true startsecs=10 stopwaitsecs = 600 killasgroup=true priority=999 Ask me for more info if you need it. Thanks in advance. -
Django BooleanField as a dropdown
Is there a way to make a Django BooleanField a drop down in a form? Right now it renders as a radio button. Is it possible to have a dropdown with options: 'Yes', 'No' ? Currently my form definition for this field is: attending = forms.BooleanField(required=True) -
Using third party Email system for Django Password Reset
I have a Django App hosted on Google Compute Engine(which doesn't allow port 25/465/587 to send Emails). So, I integrated a third party Email system in the Django App. Third party Email system works find on Google Compute Engine too. But when I use Django Reset Password, that email is still getting sent over by the Django Default Email System. Can this Django Default Email system for password Reset be changed ? If yes, Can someone please explain how it can be changed ? Thanks, -
How can I add more forms or fields in django-registration
I have reviewed some posts here on StackOverflow about adding more fields registration -record django I have tried many things , researched and have not been able to insert more fields in the registration form , I read must inherit from the registration -record django but I have not yet managed to do that , I ask your help please . My models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django_countries.fields import CountryField from django.db import models # Create your models here. class Profile(models.Model): user = models.OneToOneField(User) firts_name = models.CharField(max_length=100, blank=False, null=False) last_name = models.CharField(max_length=100, blank=False, null=False) phone = models.CharField(max_length=20, blank=False, null=False) code_school = models.CharField(max_length=100, blank=False, null=False) country = CountryField() picture = models.ImageField(upload_to='profile_images', blank=True) def __unicode__(self): return self.user.username My forms.py from registration.forms import RegistrationForm from django.forms import ModelForm #Create your forms here! class UserProfileRegistrationForm(RegistrationForm): first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs= {'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) phone = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'})) code_school = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) contry = CountryField(blank_label='(select country)', widget={'country': CountrySelectWidget()}) picture = forms.ImageField(required=False) class Meta: model = Profile() My views.py I have a question in this part , my question is if I put the username, email and password fields or not . Since I want to … -
I cannot start rabbitmq on my mac
I have brew installed rabbitmq on my mac and have tried the following rabbitmq-server start sbin/service rabbitmq-server start and neither work.How do I start it? -
Django Admin add edit/create buttons to Parent
I'm trying to add an add and edit link to my Django admin for the ForeignKey field category. I already have this on the schedule field, however this is handled by djcelery and i cannot figure out how they do this: My categories field currently looks like this: Both fields are simply added to the admin screen through a foreign key relation. Is there any default settings for this in Django admin? -
How to implement push notification in ios django
I am using django-gcm for android, is there any library for ios? -
Django get_or_create on reverse relationship
I'd like to use get_or_create instead of doing this: cart = client.cart cartitems_cart = cart.__cartitem_set if not cartitems_cart.filter(item=stockitem).exists(): cartitem = CartItem.objects.create(item=stockitem) else: cartitem = cartitems_cart.objects.get(item=stockitem) is it possible somehow? The models look like this: class CartItem(models.Model): item = models.ForeignKey(StockItem, blank=True) quantity = models.IntegerField(default=1, null=True) class Cart(models.Model): items = models.ManyToManyField(CartItem, blank=True) So, I need to get or create a CartItem that is related with a Cart. I'm not sure how to write that query. -
To how list group by values and values in that category
I want my template to display my group by category as a header, and then all the values for that group by category under it. For example, my table looks like this: ['John','Physics'] ['Jim','Physics'] ['Sam','Biology'] ['Sarah','Biology'] And I want the template to output this: Physics John Jim Biology Sam Sarah I'm not sure what to put in my veiws.py as I would usually do this in SQL --> first group by category, then return all results in that category. How would my veiws.py and template looks like to accomplish this? Thanks. My current veiws.py: def department(request): students = Students.objects.all().order_by('department') return render(request, 'department.html', { 'students':students, }) -
no module named AppConfig
I'm trying to run a server on my computer in Python/Django. In my installed_apps, I had a program called csvimport. It didn't work, so I had to install django-csvimport and I had to change it to csvimport.app.AppConfig in my installed-apps. However, I still get an importerror message saying "no module named AppConfig". (my version of django is 1.8, and django-csvimport is 2.4, by the way) Is this not the correct way to have csvimport in my installed_apps and my program? Thanks! -
Ember model hooking with data received as JSON with REST
I'm really new to ember and I'm trying to send a JSON data with my REST backend (I'm using Django REST framework with Django JSON API), but I'm getting some weird errors. Error: 1)Error while processing route: sampledata.index serializer.normalizeResponse is not a function normalizeResponseHelper@http://localhost:4200/assets/vendor.js:77763:30.... 2)normalizeResponseHelper@http://localhost:4200/assets/vendor.js:77763:30 _findAll/</<@http://localhost:4200/assets/vendor.js:77625:24 Backburner.prototype.run@http://localhost:4200/assets/vendor.js:10805:18.... My data sent is: { "links": { "first": "http://localhost:8000/api/sampledata?page=1", "last": "http://localhost:8000/api/sampledata?page=1", "next": null, "prev": null }, "data": [{ "type": "sampledata", "id": "4", "attributes": { "blind_id": "1-146788", "aliquots_circulation": 9, "total_dna": 120, "data_type": "WES" }, "relationships": { "projects": { "data": [], "meta": { "count": 0 } } } }], "meta": { "pagination": { "page": 1, "pages": 1, "count": 1 } } } My ember model (/app/models/sampledata.js): import DS from 'ember-data'; export default DS.Model.extend({ blind_ID: DS.attr('string'), aliquotsCirculation: DS.attr('number'), totalDna: DS.attr('number'), dataType: DS.attr('string'), projects: DS.hasMany('project') }); My adapter (/app/adapters/application.js): import DS from 'ember-data'; import ENV from 'frontend/config/environment'; export default DS.JSONAPIAdapter.extend({ host: ENV.host, namespace: 'api' }); My serializer (/app/serializers/application.js) import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ }); If I change my serializer to export default DS.RESTSerializer.extend({ primaryKey: '_id', serializeId: function(id) { return id.toString(); } }); I get the following WARNINGS and NO ERRORS, but no data is shown: WARNING: Encountered "links" in payload, but no model was found … -
Django refuses to accept my one-off default value for FloatField
I have a class and I'm trying to add a new FloatField to it. Django wants a default value to populate existing rows (reasonable). However, it refuses to accept any value I give it. You are trying to add a non-nullable field 'FIELDNAME' to CLASS without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: -1 Please select a valid option: -1 Please select a valid option: -1 Please select a valid option: float(-1) Please select a valid option: -1.0 Please select a valid option: float(-1.0) Please select a valid option: How do I get it to accept my value? -
Django 1.9 angularjs 1.5 template tags
I know there are quite a few solution out there it seems as I've already done some searching. However, it seems the vast majority of them are for older versions Django and AngularJS. That said, if I'm using Django 1.9 and AngularJS 1.5 - what would be the "best practice" way to implement Django and AngularJS with the well known issue of conflicting template tags. I'm using AngularJS to implement a site search feature and need a way to display the results. It seems that {% verbatim %} and {% endverbatim %} would be the simplest, cleanest way to achieve this? -
Django behave cannot connect to chromedriver
I'm running Windows 10, django 1.8.9, selenium 2.53.6, behave 1.2.5 and django-behave 0.1.5 I have installed chromedriver in my directory c:\apps and then added it to my PATH. I can type "chromedriver" anywhere and it runs with this message: Starting ChromeDriver 2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129) on port 9515 Only local connections are allowed. However, when I run my django tests: python manage.py test mytest I get the error: WebDriverException: Message: chrome not reachable (Driver info: chromedriver=2.23.409699 (49b0fa931cda1caad0ae15b7d1b68004acd05129),platform=Windows NT 10.0.10586 x86_6 4) -
Making a Twitter clone in Django, having trouble with displaying the right user when displaying tweets
I have user registration. Whenever I log in as a certain user, all the tweets are said to be tweeted by that user, even if it wasn't. forms.py from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'password', 'email'] models.py from django.db import models from django.core.urlresolvers import reverse from django.utils import timezone from django.contrib.auth.models import User class Howl(models.Model): author = models.ForeignKey('auth.user', null=True) content = models.CharField(max_length=150) published_date = models.DateTimeField(default=timezone.now) like_count = models.IntegerField(default=0) rehowl_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('howl:index') def __str__(self): return self.content index.html {% block content %} <h2>Index.html timeline!</h2> {% for howl in howls %} <div class="howl"> <h2><strong>{{user.username}}</strong></h2> <p class="lead">{{howl.content}} - {{howl.published_date}}</p> <span>Rehowls: {{howl.rehowl_count}}, Likes: {{howl.like_count}}</span> </div><!--howl--> {% endfor%} {% endblock %} I know that using user.username in index.html is the problem. It shows the current user logged in as the author of these tweets. How do I make it so that it displays the rightful owner of a tweet? -
Transfering existing users to python-social-auth
I have running django app with custom user model, that has "facebook_uid" field, that has been used for previous hand-written facebook login. Now I would like to transfer those existing facebook asociations to python-django-auth. I can just create records for those users to table social_auth_usersocialauth with obvious user_id and, provider and uid, but I am not sure if I can leave column extra_data empty (or empty json object). Is this correct approach? Is there anything else I need to do? Thanks! -
how to let user select two items to compare in html/django
I'm trying to create a simple webpage that'll let people select two items from search results to compare stats of each item. Item_One: 35lbs <select-box> Item_Two: 25lbs <select-box> Item_Three: 44lbs <select-box> select two items to compare It's a pretty common practice in e-commerce sites, but I'm having a tough time finding docs on setting something like this up. Thanks for any help! -
Django-tables2: ValueError at /interactive_table/ Expected table or queryset, not str
I was following along with the tutorial for Django-tables2 tutorial (which can be found here: https://django-tables2.readthedocs.io/en/latest/pages/tutorial.html). I've fixed all the errors up until now, but I've hit one that I cannot solve. It says that my code expected a table or queryset, not a string. I've looked around, and all the solutions to this problem all blame the version being out of date, but I have updated it and I still get this error. Does anybody know what I'm doing wrong? Here is my views.py: from django.shortcuts import render from interactive_table import models def people(request): return render(request, 'template.html', {'obj': models.people.objects.all()}) Here is my models.py: from django.db import models class people(models.Model): name = models.CharField(max_length = 40, verbose_name = 'Full Name') Here is my template.html: {# tutorial/templates/people.html #} {% load render_table from django_tables2 %} <!doctype html> <html> <head> <link rel="stylesheet" href="{{ STATIC_URL }}django_tables2/themes/paleblue/css/screen.css" /> </head> <body> {% render_table people %} </body> </html> -
decorate or wrap the return value of a model field attribute
Suppose I have a Person model: class Person(models.Model): first_name = models.TextField() last_name = models.TextField() I need a way to wrap first_name and last_name at a request-response layer (e.g through middleware). For example, I may want to slightly modify the first_name. One way is doing it in every single place that needs it. Another way is to add a get_first_name() function that would do that for me, but this would require me to change thousands of occurrences of code directly accessing first_name. Another theoretical way, is to somehow wrap around or decorate the attribute through a middleware so that I can make modifications on the fly. Perhaps something like this: class ModifyFieldMiddleware(object): def process_request(self, request): Person._first_name = Person.first_name Person.first_name = modify_value(foo) #somehow pass the actual first_name here Is there a way to do this in django without major hacking? -
Import css in Django
I use django1.10 i reference the official doc https://docs.djangoproject.com/en/1.10/intro/tutorial06/ my project name:mysite structure: mysite- - mysite - urls.py -views.py ... - templates - index.html - images - static - mysite - main.css In my index.html add {% load staticfiles % } <link rel="stylesheet" text = 'html/css' href="{% static 'mysite/static/main.css' %}" /> final i go go to the runserver i just see the original html and images css not work what should i notice? -
Post to nested fields with Django Rest Framework serializers
I have setup my serializer to return nested content successfully. However, I have not been able to post data within the nested fields. I don't get an error when posting the data- but it only posts to the non-nested fields. I would like for it to take the "name" field OR primary key (of model "TAG") for posting item. Models.py class Tag(models.Model): name = models.CharField("Name", max_length=5000, blank=True) def __str__(self): return self.name class Movie(models.Model): title = models.CharField("Whats happening?", max_length=100, blank=True) tag = models.ManyToManyField('Tag', blank=True) def __str__(self): return self.title Serializers.py: class TagSerializer(serializers.ModelSerializer): taglevel = filters.CharFilter(taglevel="taglevel") class Meta: model = Tag fields = ('name', 'taglevel', 'id') class MovieSerializer(serializers.ModelSerializer): tag = TagSerializer(many=True, read_only=True) info = InfoSerializer(many=True, read_only=True) class Meta: model = Movie fields = ('title', 'tag', 'info') def create(self, validated_data): tags_data = validated_data.pop('tag') movie = Movie.objects.create(**validated_data) for tag_data in tags_data: Tag.objects.create(name=name, **tag_data) return movie Sample of posting data: r = requests.post('http://localhost:8000/api/Data/',{ "title": "TEST_title", "tag": [ { "name": "test1", "name": "test2" } ], "info": [] }) -
OfflineGenerationError: You have offline compression enabled but key "%s" is missing from offline manifest
I'm posting here because im out of idea, and tried almost everything. I'm trying to use django-compressor with S3BOTO to serve all my static and media file directly from S3. Everything almost work, when I do the offline compression I get all my files on S3, same with collect static, but then I get this famous error the missing key in the manifest. I tried to search on a lot of different forum, website, tutorial, but couldnt help myself, and we have to deliver soon. Thank you for your help ! Settings.py : """ Django settings for Califun_travel_agent project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj_database_url #from boto.s3.connection import SubdomainCallingFormat # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Allow all host headers ALLOWED_HOSTS = ['*'] FULL_DOMAIN = 'hidden' # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'hidden' # SECURITY WARNING: don't run with debug turned on in production! if os.environ.get('DEBUG') == … -
Create a Django Database - Django Newbie
I'm new to django and am trying to figure out how to create a database... seems simple enough. This code works on other people's local computer - we arent running it in production yet. But mine isnt working. A coworker indicated that I need to actually create a database. Prior to using mysql, I was using sqlite, which didnt require this. When I run python manage.py runserver this is what I get: XX-MacBook-Pro:xx xx$ python manage.py runserver Performing system checks... Unhandled exception in thread started by <function wrapper at 0x104ebb668> Traceback (most recent call last): File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Library/Python/2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Python/2.7/site-packages/django/core/checks/model_checks.py", line 28, in check_all_models errors.extend(model.check(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 1170, in check errors.extend(cls._check_fields(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 1247, in _check_fields errors.extend(field.check(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 925, in check errors = super(AutoField, self).check(**kwargs) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 208, in check errors.extend(self._check_backend_specific_checks(**kwargs)) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 317, in _check_backend_specific_checks return connections[db].validation.check_field(self, **kwargs) File "/Library/Python/2.7/site-packages/django/db/backends/mysql/validation.py", line 18, in check_field field_type = field.db_type(connection) File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 625, in db_type return connection.data_types[self.get_internal_type()] % data File "/Library/Python/2.7/site-packages/django/db/__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], … -
django: is there something like crispy form for displaying a model?
This sounds like a LMGTFY question but I actually tried to look around on google and doesn't seem to find any. I am wondering if there is a module or app for django that handles displaying fields of a model beautifully since I am pretty sure it would look terrible if I do the front end manually. -
write django data from module into xlsxwriter
I need to extract all the data from a model I have and trigger a function to export it as a .xls file. I have found xlsxWriter not sure if I'm in the right path, is there a way I can just call my full model and write it into a file?