Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Function chord from Celery getting "list index out of range" in Django app
My Django application is getting "list index out of range" error when it finishes my tasks and try to call my callback function. This is my code: tasks = [] playlists = ['uploads','likes','favorites'] for playlist in playlists: video_list_key = result["items"][0]["contentDetails"]["relatedPlaylists"][playlist] '''Get videos of the channel''' part = "part=snippet" json_data = requests.get('https://www.googleapis.com/youtube/v3/playlistItems?playlistId={0}&access_token={1}&{2}&maxResults=50'.format(video_list_key, access_token, part)).json() part = "part=snippet,statistics,contentDetails" for info in json_data["items"]: video = requests.get('https://www.googleapis.com/youtube/v3/videos?id={0}&{1}&access_token={2}'.format(info["snippet"]["resourceId"]["videoId"], part, access_token)).json() post = youtube_save_object.s(video, listen, followers_count, playlist) tasks.append(post) callback = add_subjects_categories.si(username, 'youtube') chord(tasks)(callback) This is the error: [2017-03-10 09:42:03,478: ERROR/Worker-1] Chord '5c4c50f4-e174-46e0-85cd-c127535f0f5a' raised: "Dependency ad25d24e-ded1-425f-9fea-963fab0fb381 raised IndexError('list index out of range',)" Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/backends/base.py", line 580, in on_chord_part_return ret = j(timeout=3.0, propagate=propagate) File "/usr/local/lib/python2.7/dist-packages/celery/result.py", line 691, in join_native raise value IndexError: list index out of range How can I solve this?? -
How can I print graph using AJAX in django?
I am creating a weather forecast APP and on the home page a date input box is given. Upon entering the date and clicking on submit graph should be displayed. I have created an url which gives a JSON string for next days of temperature. I am a beginner so I am not able to figure out the error. Please help me out here is my code: $('.submit-btn').click(function(){ $.getJSON("http://127.0.0.1:8000/plot/ (http://127.0.0.1:8000/plot/2017-03-10)" + $("#id_date").val() , function(data){ plotGraph(data); }); }); function plotGraph(data){ var chart = c3.generate({ bindto: '#chart', data: { columns: [data.temp], axes: { data1: 'temperature' } }, axis: { y: { max: 40, min: 0, } } }); } -
Django model not stored in the DB
It seems that I already asked this question and got an answer, but I can't find it. How to make a Django model not stored in the DB? (I want it to be a model (derived from models.Model) only in order to be able to retrieve it with get_model() method.) -
django rest framework serialize property field as date?
I have this : extra_kwargs = {'posting_date': {'format':'%d-%m-%Y'}, 'validation_date': {'format':'%d-%m-%Y'}, 'execution_date': {'format':'%d-%m-%Y'}, 'rejection_date': {'format':'%d-%m-%Y'}, 'deadline': {'format':'%d-%m-%Y'}} Every thing works fine with first 4 fields since they are datetime django model field. the last one (deadline) is a property and It's not treated as datetime by django serializer even if it returns a datetime so using format raises an exception. Any solution for this issue ? -
Django junction table with extra foreignkey
I have the following models class Company(models.Model): name = models.CharField(max_length=100) description = models.TextField( max_length=500, blank=True, help_text='Any text to describe a company' ) url = models.URLField('company URL', blank=True, null=True) email = models.EmailField(blank=True, null=True) created_on = models.DateTimeField('date created', default=timezone.now) class Meta: verbose_name = 'company' verbose_name_plural = 'companies' ordering = ['name', '-created_on'] def __repr__(self): return '<Company {0.name}>'.format(self) def __str__(self): return self.name class Project(models.Model): name = models.CharField(max_length=100) description = models.TextField( max_length=500, blank=True, help_text='Any text to describe the project' ) company = models.ForeignKey( Company, on_delete=models.PROTECT, ) created_on = models.DateTimeField('date created', default=timezone.now) class Meta: verbose_name = 'project' verbose_name_plural = 'projects' ordering = ['-created_on', 'company'] permissions = ( ("can_view_project", "Can view all project related work"), ) def __repr__(self): return '<Project {0.name}>'.format(self) def __str__(self): return self.name class Worker(models.Model): description = models.TextField( max_length=500, blank=True, help_text='Optional. Describe what the worker does or who they are' ) user = models.ForeignKey(settings.AUTH_USER_MODEL) company = models.ForeignKey(Company) class Meta: order_with_respect_to = 'user' def __repr__(self): return '<Worker {0.id}'.format(self) def __str__(self): return self.user.get_fullname() The problem I would like to add a ManyToMany relationship between Project and Worker so that I can view a list of workers under a certain project. However, I want to make sure that a worker can only be added to a project if … -
Pass a list to a celery worker with Django
I used Django 1.9 / Python 2.7 / Celery 3.1.23 / Redis 2.10.5 Celery works fine for many simple tasks, but when I am trying to pass lists to my Celery worker, it does not work. The general objective is to lighten the worker process by succesively transmitting chunks of ids to the worker, and not 30,000 all in one time. I understand I have to pass my list as Json format. Settings: CELERY_ACCEPT_CONTENT = ['json'] CELERY_RESULT_SERIALIZER = ['json'] CELERY_TASK_SERIALIZER = ['json'] tasks.py: @periodic_task(run_every=crontab(minute=29, hour=12)) def update(request=None): iddict = [23, 49, 81, 23] forceevaluation = list(sliceids) sliceids2 = json.dumps(forceevaluation) updatewikipediadescription2.apply_async(args=sliceids2, eta=now() + timedelta(seconds=a)) views.py @shared_task def updatetask(slice): for placeid in slice: print("ok") Celery always shows the following error: [2017-03-10 12:29:04,031: ERROR/MainProcess] Task googleautocomplete.tasks.updatetask[94cdded2-0b2d-4304-aa14-6d97257c947c] raised unexpected: ValueError('task args must be a list or tuple',) Any idea why I get this error ? -
Problems in my relationship :(
Im really sad... So, how can I explain what happened... I want a button to create a .pdf file. (with Python 2.7, Django 1.8) Also, I have 0 clue in how to express that to the machine. Started by reading some articles, trying to learn from the others how could that be done. Found an handy link from a brazilian man, Vitor Freitas: This Link Who kind of redirected me to the following links: Second Link Third Link So, in order to print as PDF, they say to use: ReportLab ok, pip install reportlab ReportLab relies on Pillow, which is a third-party Python Image Library. If you run: pip install Pillow, Youll see something like this: Requirement already satisfied: Pillow in c:\pythonprojects\virtualenvs\apis\lib\site-packages Requirement already satisfied: olefile in c:\pythonprojects\virtualenvs\apis\lib\site-packages (from Pillow) Great. Thats it. Nothing else seems to be needed at this level, so... ... lets start by making sure we have everything we need in the view then. (we can be import more things if needed. With balance) # views.py from django.http import response from django.core.files.storage import FileSystemStorage from django.shortcuts import render, HttpResponse from django.contrib.auth.decorators import login_required from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import … -
Django deltatime with the largest unit
I'm try to create a render for any objects Album, i get the last picture added and i would like to compare with now (the date for pictures is in picture.date). But in my render i when the largest unit of time. models: from django.utils.timezone import now class Album(models.Model): name = models.CharField( max_length=50) ... class Pictures(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='albums') date = models.DateTimeField( default=now) ... In the template i create a timeline of album, i use a loop : {% for a in album %} related album : {{ a.name }} last modif was {{ a.pictures.last.date }} ago. {% endfor %} For example the render will be something like: 5s 1min 2h 3days So if i have datetime.timedelta(0, 5, 279122) just return 5s, or if i have datetime.timedelta( 01 , 25, 279122) just return 1 min. So i try to find an operation between now and picture.date, something like truncated datetime.timedelta for is bigger unit is possible ? I don't want panoply of if conditions. -
Error: file object has no attribute size
I am using django-storages to store files into AWS S3. Uploading files used to working fine. But when I downgraded from django 1.10 to 1.8. I am getting strange error at line item.item_profile.save(filename.name,photofile). CODE: def PhotoUpload(request): if request.method == "POST": filename = request.FILES['profileimage'] item_id = request.POST['item_id'] item_name = request.POST['item_name'] zone_id = request.POST['zone_id'] photofile = tempfile.TemporaryFile() for chunk in filename.chunks(): photofile.write(chunk) print filename zone = Zone.objects.get(user=request.user, zone_id=zone_id) item = Item.objects.get(zone=zone, item_id=item_id) item.item_profile.save(filename.name,photofile) item.save() photofile.close() response_data = {} return JsonResponse(response_data) return JsonResponse({}) ERROR: AttributeError at /home/photoupload/ 'file' object has no attribute 'size' Request Method: POST Request URL: http://localhost:8000/home/photoupload/ Django Version: 1.8.17 Python Executable: /usr/bin/python Python Version: 2.7.3 Python Path: ['/home/sandesh/knowmenow/pythonserver', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/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/PIL', '/usr/lib/python2.7/dist-packages/gst-0.10', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client', '/usr/lib/python2.7/dist-packages/ubuntuone-client', '/usr/lib/python2.7/dist-packages/ubuntuone-control-panel', '/usr/lib/python2.7/dist-packages/ubuntuone-couch', '/usr/lib/python2.7/dist-packages/ubuntuone-installer', '/usr/lib/python2.7/dist-packages/ubuntuone-storage-protocol'] Traceback: File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132.response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/sandesh/knowmenow/pythonserver/home/views.py" in PhotoUpload 174.item.item_profile.save(filename.name,photofile) File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in save 106. self._size = content.size -
Why can I not install pip on windows 7?
so I'm trying to install pip for python because I want to use django. I've looked through the forum and plenty of others for about three days so I'm very frustrated because its probably an easy fix. so ive set the environment/path and pythons working. I've got the get-pip.py file I have Setuptools-34.3.1 They are both in the scripts folder? so if i use this in cmd it comes back like this; C:\Windows\system32>python Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> python get-pip.py File "<stdin>", line 1 python get-pip.py ^ SyntaxError: invalid syntax >>> This comes back for anything i ask it to do. After trying everything in the forums its just still not working I've even uninstalled and tried other versions of python. if anyone could help i would appreciate it. -
uploading a InMemoryUploadedFile (django) to s3
i am trying to upload an image from my local memory to amazon s3, but it shows following error: TypeError at /media/ invalid file: i guess the file uploaded to browser can not be uploaded directly to s3, i need a solution for this: view.py: from django.shortcuts import render from django.views import View from numera.service import s3 class Upload(View): template = 'media_upload.html' def get(self,request): return render(request,self.template) def post(self,request): file = request.FILES.get('myfile') s3.put_object(file) return render(request,self.template) s3.py: import boto3 from boto3 import Session from django.conf import settings boto3.DEFAULT_SESSION = Session( aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, ) client = boto3.client('s3') resource = boto3.resource('s3') numera_bucket = resource.Bucket('numera') def put_object(file_name): with open(file_name,mode='rb') as f: response = numera_bucket.put_object( Body=f, Key=file_name.split('/')[-1], # ACL='bucket-owner-full-control', ) print(response) -
ImportError: No module named base in html5lib
I suddenly can't start may Django server any more, running check: python manage.py check shows to the following error: apps.populate(settings.INSTALLED_APPS) File "/home/aym/.virtualenvs/prod_env/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/aym/.virtualenvs/prod_env/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/aym/workspace/CompanyP/apps/account/models.py", line 18, in <module> from apps.groups.models import SubscriptionGroup File "/home/aym/workspace/CompanyP/apps/subscription/models.py", line 8, in <module> from apps.member.models import Member File "/home/aym/.virtualenvs/prod_env/local/lib/python2.7/site-packages/bleach/__init__.py", line 5, in <module> from bleach.linkifier import File "/home/aym/.virtualenvs/prod_env/local/lib/python2.7/site-packages/bleach/linkifier.py", line 5, in <module> from html5lib.filters.base import Filter ImportError: No module named base Have you any idea? -
Increase model integer field according to repetition of words
Let's say I have two models, a Box model and a Thing model. The last one has Box as a Foreign Key. Each Box works as a container of string objects the user can add using a ModelForm. The models.py should be something like this: models.py class Box(models.Model): name = models.CharField(max_length=120, unique=True) def __str__(self): return self.name class Things(models.Model): box = models.ForeignKey(Box) name = models.CharField(max_length=120) thing_number = models.PositiveIntegerField(default=1) def __str__(self): return self.name Now, for each time a user insert the same string into the Form, I'd like to increase the "thing_number" Integer field by 1. Is there an easy way to do so? -
Filter JSON field django with greater than, less than and a range using _contains
Let's say that I have this model: class Item(models.Model): data = JSONField(blank=True, null=True) And then in the console: >>Item.objects.create(data={'size': 11}) >>Item.objects.create(data={'size': 12}) >>Item.objects.create(data={'size': 13}) How can I filter the results passing JSON data as follow but with the size in a range of numbers, and greater or less than a number? Item.objects.filter(data__contains={'size': *match this numbers*}) Or is there any other way not using data__size__gte so i can create JSON variables and filter them with freedom. -
logger function was conflicted between Django & RobotFrameWork
I've write a project based on Django & RobotFrameWork, Django use Logger in Setting to record issues, so when run this project, RF's [logger.info] won't work, can't print logs and the data in log.html is empty. what can I do to fix it ? -
Get ID from m2m instance
In a model with a M2M relationship. Is there any way to get the id of the field of this relation in a signal? class Foo(models.Model): field1 = ... bar = models.ManyToManyField(Bar) @receiver(post_save/m2m_changed, sender=Foo) def whatever(sender, instance, **kwargs): # get the ID of bar instance here I want to be able to get the id of the Bar instance being used. Any idea? -
Conversations In ChatBox
Hi We have developed chatbox in python and Django and now the problem is When I click on the other tab and return to chat tab my old/current conversations are not available. How to save the old/current conversations. -
Creating a voting system in Django rest framework by saving usernames on each vote
I am using DRF and I want to build my own voting system using likes, dislikes and neutral. I have the front end set up so when the user likes an image I want to his user id to be saved within the post model, and so on for the dislikes. class Posts(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE,related_name = 'user_posts') image = models.ImageField('optionalImage', upload_to='images/posts/', default='/images/posts/blank.png') likes = models.TextField(max_length=200, default=0) dislikes = models.TextField(max_length=200, default=0) neutral = models.TextField(max_length=200, default=0) I have the following questions: 1) How do I save a list of usernames like [14,33,22...] since I can't use a text field for the same. 2) Is it a good structure to maintain the likes and dislikes within the same post and update them on every put request by saving the userid of the user within the respective choice made(likes, dislikes) or should they be a separated into a different model? 3) What is the best way to check if the user has seen a particular post before using this model? Would I have to check through the likes, dislike and neutral list to see if the user has acted on the post? Or would I require another unique identifier? I need to … -
Django Chartit doesn't display on Ubuntu with wsgi
I'm getting an important problem with Django Chartit in my project on Ubuntu 15.04. I have two projects : I'm developping my Django website on OSX as a developement platform. I send my Django project on an Ubuntu server when it works owith OSX in order to make some tests. Ubuntu will be the operating system used by my project to the end. Ubuntu part looks like my product platform. So, I'm using Django-chartit in order to display some graphics, ... and it works fine with OSX. But when I copied my project to Ubuntu, I changed paths according to the OS, ... charts don't display on my website. I used python wsgi/apache2 with Ubuntu to display my Django website. This is what I have : File 1 : apache2.conf Alias /static/ /var/www/html/Etat_civil/static/Theme/ <Directory /var/www/html/Etat_civil/static/Theme/> Require all granted </Directory> <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> WSGIScriptAlias / /var/www/html/Etat_civil/Etat_civil/wsgi.py WSGIPythonPath /var/www/html/Etat_civil <Directory /var/www/html/Etat_civil/Etat_civil> <Files wsgi.py> Options Indexes FollowSymLinks Require all granted SetEnvIfNoCase Host .+ VALID_HOST Order Deny,Allow Deny from All Allow from env=VALID_HOST </Files> </Directory> #<Directory /srv/> # Options Indexes FollowSymLinks # AllowOverride None # Require all granted #</Directory> … -
Associating user data with session key
I have created a session in django1.10 for a user and i can see a row being created in django_session for each user.a user generates data and stores in tables in mysql.I want to associate these tables with session_key so that when a user logs out all these tables are truncated. -
TastyPie Custom error with debug = True
I am trying to throw a custom error in my api.py file with DEBUG = True. It throws the error { "error_message": "Sorry, this request could not be processed. Please try again later." } This is the default TASTYPIE_CANNED_ERROR message. I want the error to be something like this: {"error_message": "{'id': 2671, 'error': 'Duplicate'}"} I tried overriding _handle_500 method but that seems to return my website html page in response. -
Where to instantiate a client for an external service in Django?
What is the accepted practice in Django for creating an instance of a client for an external service (e.g. Zookeeper, Cassandra, Redis, etc.)? I need this client to perform a "set key" operation from inside a view and I don't want to create the client on each request due to high overhead. Currently I've declared it as a global variable in views.py, but that's not really ok, because it gets instantiated when I do python manage.py makemigrations too. -
How to get JSON format data in python
I calling below code line its working fine return HttpResponse( json.dumps(rows), content_type='application/json') getting output like below: ["f8823b39f5", "000002de", "176", "STAT", "NY"] I want JSON fromat because of that i run below code: return HttpResponse( json.dumps(dict(rows)), content_type='application/json') Getting below error: 'dict' object is not callable Excepting output like below: {"earning1": "f8823b39f5", "earning2": "000002de", ...} Please help me. How to solve this problem. -
raise TypeError('view must be a callable or a list/tuple in the case of include()
I'm fairly new to python and django. I do know what this error indicates though. It is saying I need to import views into the urls. The strange thing is on my laptop it runs fine and loads the page, but on my desktop it isn't. I am using a git repo, and just pulled the working changes from my laptop. I use the same Python interpreter on both machines(3.5.3).I get the same error message for all of the urls as the title states. Here is the Full Stack Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x000001FA9FAB7400> Traceback (most recent call last): File "C:\Users\Rpg Legend\mm\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Users\Rpg Legend\mm\lib\site-packages\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Users\Rpg Legend\mm\lib\site-packages\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Rpg Legend\mm\lib\site-packages\django\utils\functional.py", line 35, in __get__ … -
Validate date of birth greater than today?
how to validate html is greater than today? following is my code: <div class="form-group"> <label class="col-sm-2" for='id_dateOfBirth'>Birth Date </label> <div class="col-sm-10"> <input class='form-control' name="dateOfBirth" id='id_dateOfBirth' type='date'> </div> i want to check weather date is using javascript greater than today? basically i am working django project!!