Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Rollup in Django ORM
Is it possible to use ROLLUP aggregation in Django ORM without writing raw SQL? -
Django-cms no reverse match using apphook from admin
i hope you can help me. I'm using django 1.11 and django-cms. I created an apphook to manage urls from a certain page. I already created the page (with all translations) and associated it with my application so everything works fine. My problem occurs when, from admin, i'm inside the change page related to an instance of a model. I see the button 'view on site' that uses an url created this way: /admin/r/content_type_id/object_id/ django.contrib.contenttypes.views.shortcut admin:view_on_site Clicking on it i get the error Reverse for 'myapp_mymodel_detail' not found Do you know the correct way to make it works? -
TinyMCE editor not showing up in Django-Zinnia custom admin
I'm trying to use django-blog-zinnia 0.19 with tinymce and admin. In order to allow non-staff users to use Django's admin interface, I registered an extra BlogAdminSite class and added the necessary urls to point to the custom admin pages. This is what should be used to edit blog entries. When using the regular admin interface using the url http://localhost:8000/en/admin/zinnia/entry/1/change/ tinymce is used as desired. However, when calling the custom blog admin interface using the url http://localhost:8000/en/blog/admin/zinnia/entry/1/change/ tinymce is not shown, just the regular textarea widget. Looking at the HTML source, I find tinymce's files missing in the latter case: I installed django-tinymce 2.2.0 and zinnia-wysiwyg-tinymce 1.4 packages. In settings.py's INSTALLED_APPS sections the relevant apps are added in this order: 'blog', # BlogAdminSite app 'tinymce', 'zinnia', 'zinnia_tinymce', 'django.contrib.admin', Thanks for your help. -
download django data model as csv
how can i turn data collected from Django site, and download it as a .csv file. I want it to be so that there is a button in django admin that downloads all the data as a .csv file this is my model: from django.db import models class Auto(models.Model): YNC = ( ('N', 'No'), ('Y', 'Yes'), ) NYC = ( ('N', 'No'), ('Y', 'Yes'), ) NNY = ( ('N', 'No'), ('Y', 'Yes'), ) nw = ( (1, 'Really Bad'), (1, 'Bad'), (3, 'Average'), (4, 'Good'), (5, 'Really Good'), ) Team = models.CharField() Scout = models.CharField() StartWithCubeLoaded = models.CharField(max_length = 1, choices = YNC, default = 'N') CrossAutoLine = models.CharField(max_length = 1, choices = YNC, default = 'N') RobotCrossCenterLine = models.CharField(max_length = 1, choices = YNC, default = 'N') PlaceCubeInWrongScale = models.CharField(max_length = 1, choices = YNC, default = 'N') RobotHitOtherAllianceRobotInNullZone = models.CharField(max_length = 1, choices = YNC, default = 'N') MisPlaceCube = models.CharField(max_length = 1, choices = YNC, default = 'N') DroppedCubes = models.IntegerField(default = 0) DoubleStackScale = models.CharField(max_length = 1, choices = NYC, default = 'N') Foul = models.CharField(max_length = 1, choices = NYC, default = 'N') KnockedOffCubes = models.IntegerField(default = 0) MissedCubes = models.IntegerField(default = 0) Climbed = … -
Property allowing attribute access
To make part of the django-tables2 API usable in templates, I want to define a property on a class that translates the attribute name to an argument to another method. The current implementation looks (vaguely) like this: class Row(object): _cells = {'first_name': 'James', 'last_name': 'Charland'} def get_cell(self, name): return self._cells[name] This makes it impossible to access a specific cell from a django template, because django templates do not allow passing arguments to functions. I want to support something like row.cell.first_name, which would be easy if the internal structure contained a dict _cells. In reality, the implementation is a bit more complex (getting the value involves calling a function). Computing a dict for all possible cells is not desirable either because it might involve doing unnecessary work. My naive solution looks like this: class Row(object): _cells = {'first_name': 'James', 'last_name': 'Charland'} def get_cell(self, name): return self._cells[name] @property def cell(self): class CellReader(object): def __init__(self, row): self.row = row def __getattr__(self, name): return self.row.get_cell(name) return CellReader(self) Which works and doesn't use too much code, but it feels a bit verbose. Is there something in the standard library I did not think of to implement this functionality in a more concise way? -
Extending/overriding Django TestCase class
My application has three levels of access (i.e. User, Manager, Admin). In my unit tests I have something like this: from django.test import TestCase class DocumentViewTest(TestCase): def setUp(self): # Create 3 users def test_view_url_exists_at_desired_location(self): self.client.login(username='manager', password='xx') resp = self.client.get(reverse('view_upload')) self.assertEqual(str(resp.context['user']), 'manager') Testing all three levels could be defined by the same routine: login user post/get to some url create assertions to check the post/get response I wanted to encapsulate all the steps in some wrapper class or extend the TestCase, so that redundancy is avoided. I was thinking about something like this: from django.test import TestCase class DocumentViewTest(TestCase): def setUp(self): # Create 3 users def test_view_url_exists_at_desired_location(self): self.client.login(username=['manager','admin','simple_user'], password=['xx','x','xxx']) resp_manager, resp_admin, resp_simple_user = self.client.get(reverse('view_upload')) self.assertEqual(str(resp_manager.context['user']), 'manager') self.assertEqual(str(resp_admin.context['user']), 'admin') self.assertEqual(str(resp.resp_simple_user['user']), 'simple_user') Does anyone have suggestions how I could override get/post/login methods? Would creating a wrapper class around TestCase be easier? Any other suggestions? Thanks! -
Django, ImportError: cannot import name Celery
Why is this happening? My celery.py: import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) my init.py # import celery from .celery import app as celery_app I even tried renaming celery.py to something else and the error still persisted. Could it be because of my python version? -
How to add a foreign key to an existing model of a newly created model in DJango?
class Person(models.Model): first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) DOB = models.DateField() username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __str__(self): return self.first_name + self.last_name class Entry(models.Model): writer = models.ForeignKey(Person, on_delete=models.CASCADE,default="What should I write here?") title = models.CharField(max_length=100, default='Title') moment = models.DateTimeField() text = models.TextField() def __str__(self): return self.title + ' | ' + str(self.moment.strftime("%I:%M %p - %A, %B %d %Y")) Above are my two models, Entry is an old model, Person is a new one. Meaning, I have many instances of Entry but zero of Person. But I want to link Entry with Person. So what I did is, I removed the writer field from entry. Updated the database, made an Instance of Person. So, currently I have 1 instance of Person and n instances of Entry. How can I link them using a foreign key? I don't know what to put in default parameter. -
Django Mathfilter do not working with comparison operator
I have a statement where I use mathfilter in Django template and it do not want to turn to false despite the mathfilter is working. Which is the correct syntax for this? Thank you in advance! {% load mathfilters %} {% if 9|sub:10 > 2 %} # (9-10) > 2 -
django invalid field name(s) for model content type
i looked all around internet i can't find a solution for this error in django this script is worked on by one of the developers before me i'm trying to run ./manage.py migrate but it keeps getting this output django.core.exceptions.FieldError: Invalid field name(s) for model ContentType: 'name'. and this is the whole traceback this is the content of manage.py #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "smsg.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) -
How to handle url collisions in django/wagtail
how to handle two different views witch match for the same url? (Both views need a database call to determine if the called element is available. Changing the url structure is not an option.) url(r'^', include(wagtail_urls)), This wagtail url is matching all url's and is raising an 404 if the according page/slug is not in the database. But, I also have my own view witch behaves similar. How can I tell django to continue with the next url instead of raising a 404? (I could place my own view before the wagtail view and modify it, but I don't know how to return to the next url?) -
How to keep different files(/versions of files) on local branches and not show them in git status?
Me: I work (develop) on a Django project in a team. And we use postgresql as the database. I had untracked the migrations folders (and files) for obvious reasons. Problem: Sometimes I work on multiple branches and when there is a difference in the models which extend django.db.models.Model the makemigrations fails. My approach on the Problem: I decided to have a different database on my machine for each branch. Found out that this could be done using pygit2 (keep the name of database same as that of the branch). Problem with my approach: The migrations are same in every branch as I have them untracked. I dont want to track migrations because pushing them would disturb the production server migrations. Requirement: Whenever i switch branch, the migrations should change, but at the same time they should remain not pop up during 'git status'. Thank you in advance -
Validate Sign Up User data in serializers - Django Rest Framework
I have an issue with Validate Sign Up User data in serializers - Django Rest Framework. Hope your guys help me! My request: I want to create sign up form with user enter Duplicate email, it'll raise serializer object which duplicate. My serializers: class UserDuplicateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'full_name', 'first_name', 'last_name', ] class UserSignUpSerializer(ModelSerializer): username = CharField(required=True, allow_blank=False) class Meta: model = User fields = [ 'username', 'email', 'password' ] extra_kwargs = {"password": {"write_only": True}} # Validate duplicate username def validate_username(self, value): data = self.get_initial() username = data.get("username") username_qs = User.objects.filter(username=username) if username_qs.exists(): duplicate_obj = User.objects.get(username=username) serializer = UserDuplicateSerializer(duplicate_obj) print(serializer.data) raise ValidationError("This username has been registered!" + serializer.data) else: pass return value def create(self, validated_data): username = validated_data['username'] ... user_obj.save() return validated_data Error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\generics.py" … -
Rsync inside container
I have a command inside my django application to copy file from server to local using rsync. It was working fine normally. But when i containerized the code, the file is not getting copied. How am i supposed to copy file using rsync inside container? COMMAND="rsync -avzhe ssh @:/path/test.txt /destination/path/" ssh = subprocess.Popen(COMMAND, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print ssh result = ssh.stdout.readlines() print result result gives [] after containerizing, while normally i had [received xx bytes, sent xx bytes etc] -
How to plot bullet chart using python-nvd3?
I am completely new to python web development and this is my first web app using Python and Django. For plotting purposes I am using python-nvd3. I followed the instructions here : http://python-nvd3.readthedocs.org/en/latest/introduction.html#documentation In python-nvd3 has lots of chart types like Barchart,Line Chart and pie chart etc..In my project i need to plot a Bullet Chart but i didn't get.I have no idea to plot bullet chart using python-nvd3. If anyone have idea to plot bullet chart using python-nvd3 kindly share with me. Thanks in advance. -
hwo to connect redis server with django in dockerizing it?
Currently i am working on django app and trying to work with reddis server. i have add all configuration settings for reddis server in settings.py my settings are like this. redis_host = os.environ.get('REDIS_HOST', 'my-ip-of-reddis-server') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6380)], }, "ROUTING": "multichat.routing.channel_routing", }, } its working fine when i run python manage.py runser or python manage.py runworkers but when i dockerize this django app, it does not make connection with reddis server. it gives following error. redis.exceptions.ConnectionError: Error -2 connecting to redis:6380. Name or service not known. 2018-01-30 06:00:47,704 - ERROR - server - Error trying to receive messages: Error -2 connecting to redis:6380. Name or service not known. 201 my dockerfile is this. # FROM directive instructing base image to build upon FROM python:3-onbuild RUN apt-get update ENV PYTHONUNBUFFERED 1 ENV REDIS_HOST "redis" # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 #RUN python manage.py runserver RUN daphne -b 0.0.0.0 -p 8000 --ws-protocol "graphql-ws" --proxy-headers multichat.asgi:channel_layer # CMD specifcies the … -
Safari: Video is not playing from aws or heroku both
I have developed django-framework website video is playing in Chrome, Firefox, IE but i am facing problem with playing video on safari mac. Video is uploaded on aws ec2 ubuntu machine <video id="video" muted controls class="col p-0" poster="http://54.197.43.10/static/images/bg/poster.png" preload="auto"> <source src="http://54.197.43.10/media/video/cds_1nTIdN6.mp4" type="video/mp4"> <source src="http://54.197.43.10/media/video/cds_1nTIdN6.ogg" type="video/ogg; codecs=theora, vorbis"> <source src="http://54.197.43.10/media/video/cds_1nTIdN6.webm" type="video/webm; codecs=vp8, vorbis"> </video> Is there anything which block server videos on safari ?? -
Django-notification delete API from front-end
Can you please help me about django-notification??? I am able to implement it, but stuck in delete from front end using this API delete/(?P\d+)/ what I suppose to provide in place of (?P\d+)/ , when I call this API -
Django Channels and websockets are not working when run as Docker Image
Django Channels and websockets are not working when run as Docker Image with error Meassage:Error trying to receive messages: Error -2 connecting to redis:6380/6379. Name or service not known. -
how to implement date, consist in two date field in django orm?
this is my model, class HonorKegiatan(models.Model): id = models.AutoField(primary_key=True) jenisKegiatan = models.CharField(max_length=100, null=True, choices=masterkegiatan) honor = models.IntegerField(null=True, blank=True) keterangan = models.CharField(max_length=100, null=True, blank=True) startdate= models.DateField(null=True) enddate= models.DateField(null=True) i want to show honor from this django orm filter where datetime.datetime.now() include between startdate and enddate fields . How to use django orm implement it? honor = HonorKegiatan.objects.filter(startdate__gte=datetime.datetime.now(),enddate__lte=datetime.datetime.now()).values_list('honor',flat=True) but it's not return value? is my django orm is true? -
Python Client error: [Errno 111] Connection refused
hey guys i doont really know the problem but i go an error connection refused. i dont know what to do please help me. im trying to send a count when the button is pressed on android app and im using nanpy to connect to arduino but i got an error. import socket from nanpy import (ArduinoApi, SerialManager) ledpin = 13 buttonpin = 12 buttonpin1 = 2 buttonpin2 = 3 buttonstate1 = 1 buttonstate2 = 1 buttonstate3 = 1 connection = SerialManager() a = ArduinoApi(connection = connection) a.pinMode(ledpin, a.OUTPUT) a.pinMode(buttonpin, a.INPUT) a.pinMode(buttonpin1, a.INPUT) a.pinMode(buttonpin2, a.INPUT) ADDR2 = ('192.168.1.7', 21568) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(ADDR2) while True: try: buttonstate1 = a.digitalRead(buttonpin) buttonstate2 = a.digitalRead(buttonpin1) buttonstate3 = a.digitalRead(buttonpin2) if buttonstate1: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) if buttonstate2: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) if buttonstate3: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) finally: sock.close this is the error some know how to fix this? Traceback (most recent call last): File "/home/pi/Desktop/counter.py", line 24, in <module> sock.connect(ADDR2) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 111] Connection … -
Autofilling the models in one app with that of another
So basically I want to autofill all model fields in one app with that of another. I want make it clear though I am not talking about only using the save function inside the model as I have already done that The idea is that once I have filled and submitted the information for App A I dont have access the form for App B as the fields for the second field would be automatically filled APP 1 model class Product(models.Model): user=models.ForeignKey(user,on_delete=models.CASCADE,default=1) Name=models.CharField(max_length=120,null=True,blank=True) Category=models.CharField(max_length=80,choices=CATEGORY_CHOICES,null=True,blank=True) Type=models.CharField(max_length=10,choices=GENDER_CHOICES,null=True,blank=True) slug=models.SlugField(null=True,blank=True) Image=models.ImageField(null=True) Description=models.TextField(null=True,blank=True) Price=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) Color=models.CharField(max_length=10,null=True,blank=True) Size=models.CharField(max_length=10,choices=SIZE,null=True,blank=True) Delivery_date=models.DateTimeField(null=True,blank=True) Delivered=models.BooleanField(default=False) Timestamp=models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('Products:DetailView', kwargs={'slug': self.slug}) def __unicode__(self): return self.name def __str__(self): return self.Name App2 Model class Category(models.Model): name=models.ForeignKey(Product,on_delete=models.CASCADE,null=True,blank=True) type=models.CharField(max_length=13,null=True,blank=True) category=models.CharField(max_length=13,null=True,blank=True) image=models.ImageField(null=True,blank=True) categoryslug=models.CharField(max_length=10,null=True,blank=True) typeslug=models.CharField(max_length=10,null=True,blank=True) slug=models.CharField(max_length=90,null=True,blank=True) color=models.CharField(max_length=10,null=True,blank=True) size=models.CharField(max_length=10,null=True,blank=True) price=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) def save(self, *args, **kwargs): self.category=self.name.Category self.type=self.name.Type self.image=self.name.Image self.typeslug=(self.name.Type).lower() self.slug=self.name.slug self.color=self.name.Color self.size=self.name.Size self.price=self.name.Price super(Category,self).save(*args,**kwargs) def Category_slug(instance,sender, **kwargs): instance.categoryslug=(instance.category).lower() def rl_post_save_reciever(sender, instance,created,*args,**kwargs): print("saved") pre_save.connect(Category_slug, sender=Category) post_save.connect(rl_post_save_reciever, sender=Category) -
why am I getting jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got 'string'
{% for game in scoreecard|slice:":1" %} <tr> <th class="bg-danger text-lg-left">{{game['2nd-innings-runs']}}-{{game["2nd-innings-wickets"]}}({{game["2nd-innings-overs"]}}) </th> <th class="bg-danger text-lg-left">{{game["2nd-innings-batteam"]}} </th> </tr> {% endfor %} I'm trying to break the for loop after one iteration. -
Django Admin DateTimeField Showing 24hr format time
I tried on google but i did not found the solution , In Django Admin side , i showing start date and end date with time . But time is in 24 hr format i want to it in 12 hr format class CompanyEvent(models.Model): title = models.CharField(max_length=255) date_start = models.DateTimeField('Start Date') date_end = models.DateTimeField('End Date') notes = models.CharField(max_length=255) class Meta: verbose_name = u'Company Event' verbose_name_plural = u'Company Events' def __unicode__(self): return "%s (%s : %s)" % (self.title, self.date_start.strftime('%m/%d/%Y'), self.date_end) I also found some thing but this is not helping me What i found I am new in python and django please help me out . -
unable to make RDS queries on heroku
I can access my RDS postresql database on a local machine no problem. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xxxxxxx', 'USER': 'XXXXXXXX', 'PASSWORD': 'XXXXXXXX', 'HOST': 'XXXXXXrds.amazonaws.com', 'PORT': '5432', } I pushed this to Heroku and I get a ProgrammingError at /saferdb/query/ In manage.py shell on heroku I tried to access the database: from saferdb.models import Question q = Question.objects.all() q.count() got the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "saferdb_question" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "saferdb_question" ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 387, in count return self.query.get_count(using=self.db) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/query.py", line 491, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/query.py", line 476, in get_aggregation result = compiler.execute_sql(SINGLE) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1063, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise …