Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ModelForm with ManyToManyField showing all possible objects
I need your help with this. I tried to find the solution for a couple of days, but no luck so far. Here is the set up: There can be several projects, tasks and people can be assigned to projects, a person can be assigned to several tasks, and the same task can be assigned to different people. No problems so far... When I try to show a form for a specific task (which is assigned to 1 project), it shows all people from all projects, but I need to see people only from the project associated with the selected task. Thank you very much in advance! class Project(models.Model): project_name = models.CharField(max_length=50) def __str__(self): return self.project_name class Person(models.Model): person_name = models.CharField('Person Name',max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) def __str__(self): return self.person_name class Task(models.Model): task_name = models.CharField('Task Name',max_length=50) project = models.ForeignKey(Project, on_delete=models.CASCADE) people = models.ManyToManyField(Person) def __str__(self): return self.task_name class TaskForm(forms.ModelForm): class Meta: model = Task fields = ('task_name','people',) -
Using filters on Django 2.0
Please help to find the reason of error. Have two objects which ones returning from my view : def managment_users_form(request): users = User.objects.all() usersinfo = usersinfo_model.objects.all() count_objects = users.count() if request.user.is_authenticated: username = request.user.username context = { 'users': users, 'usersinfo': usersinfo, 'count_objects': count_objects, } return render(request, 'users.html', context) else: return redirect('login_form') And on my template I want to make for cycle from first one and filter by id in cycle another one. First is working well, but second one I'm getting error when try to use filter. Teamplate {% for user in users %} <div class=""> <h4 class="m-b-5">{{ user.first_name }} {{ user.last_name }}</h4> <p class="text-muted">{{ useremp|user_info_filter:user.id }} <span></p> </div> {% endfor %} filter from django import template register = template.Library() @register.filter(name='user_info_filter') def user_info_filter(useremp, id): return useremp.filter(user_id=id) Please help to understand the mistake. Error is : "Invalid filter: 'user_info_filter'" -
How to return 400 error for unique_together constraint violation?
I am using Django-Rest-Framework and have a model with the following constraint: unique_together = ("title", "owner") When that error is encountered the server sends a 500 response to the client, but I want to return a 400 error and detail of the constraint, so I can show it to the user. Here is the serializer code: def create(self, validated_data): title = validated_data.pop('title') try: poll = Poll.objects.create(title=title, slug=slugify(title), **validated_data) p = Poll.objects.get(id=poll.id) [p.tags.add(tag) for tag in validated_data['tags']] return poll Is it possible to raise the error there? -
django-admin.py not running
I'll add another django-admin.py question, as none of the other questions seem to cover my issue: I've installed django via pip: $ pip install django My pip and Python versions are: $ pip -V pip 9.0.1 from /usr/lib/python2.7/dist-packages (python 2.7) Specifically, python is version 2.7.14. At this point I expected to run $ django-admin startproject myTestProject which would then create my project folders in the current directory. However, this returns Cannot find installed version of python-django or python3-django This confuses me, since when I ran $ echo $PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin Further, I checked where the file django-admin.py is located: $ find -iname "django-admin.py" ./.local/bin/django-admin.py ./.local/lib/python2.7/site-packages/django/bin/django-admin.py So it seems like django-admin.py is in my PATH. Why then can I not run it? (extra info: I do have python 3.6.3 installed, too. But I don't think this version has anything to do with pip or django.) -
Good practice for doing a Django media backup
Is there any good practice for doing a Django media backup? I know there are tools like https://github.com/django-dbbackup/django-dbbackup but I can't make it work with management.call_command("mediabackup") when using options, I want to specify the generated tar file name, so I can upload it to a remote storage. I actually opened an issue about that https://github.com/django-dbbackup/django-dbbackup/issues/278 So, I'm looking for a way of doing my own backup. It looks like making a compressed version of the media folder is just what's necessary, but I'm not sure (mediarestore seems to to some stuff on the background) so I'm looking for good practices or example. -
Strange behavior of super() in Django Model
I use django 1.8.8, django-rest-framework 3.3.0 and python 2.7.12 on ubuntu gnome 16.04. I have a django model MyModel. In that model I override the save method in the following way: def save(*args, **kwargs): ... super(MyModel, self).save(*args, **kwargs) ... The problem that I found is that sometimes super is called as a usual function and after its call the next line is executed. But sometimes it is call itself recursively and we go to the first line of the function. When it is called from unit tests as self.client.post(...) the behavior is recursive. When it is called from unit tests as MyModel.save() the behavoiur is normal. Also I found that when it is called from client there are empty args and kwargs. But when it is called as MyModel.save() there are the following kwargs: kwargs = {'using': 'default', 'force_insert': True} I modified my code: def save(*args, **kwargs): ... kwargs.update({'using': 'default', 'force_insert': True}) super(MyModel, self).save(*args, **kwargs) ... But this don't change the recursive behavior. It would be great if someone tell me how to fix that. -
Correct setup of django redis celery and celery beats
I have being trying to setup django + celery + redis + celery_beats but it is giving me trouble. The documentation is quite straightforward, but when I run the scripts, nothing logs to any terminal, as if no tasks where being run. I have only one task, all that it does is printing and logging something. This is my folder structure: - aenima - criptoball - celery_aenima - __init__.py - celery_setup.py - tasks.py celery_setup.py looks like this: from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aenima.settings') app = Celery('criptoball.celery_aenima') app.conf.broker_url = 'redis://localhost:6379/0' # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() app.conf.timezone = 'UTC' @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and tasks.py looks like this: from __future__ import absolute_import, unicode_literals from datetime import datetime, timedelta from criptoball.celery_aenima.celery_setup import app import logging from django_celery_beat.models import PeriodicTask, IntervalSchedule cada_10_seg = IntervalSchedule.objects.create(every=10, period=IntervalSchedule.SECONDS) actualizar_candles = PeriodicTask.objects.create(interval=cada_10_seg, name='actualizar_candles', task='celery_aenima.tasks.actualizar_candles', expires=datetime.utcnow()+timedelta(seconds=30)) @app.task def actualize_candles(x, … -
Django Rest Framework - self.request.user in model method
I have a model: User is the django User model from django.contrib.auth.models # drink/models.py class Drink(models.Model): name = models.CharField(max_length=32) bartender = models.ForeignKey('bartender.Bartender') # bartender/models.py class Bartender(models.Model): name = models.CharField(max_length=64) owner = models.ForeignKey(User) # property/models.py class Rating(models.Model): bartender = models.ForeignKey('bartender.Bartender') owner = models.ForeignKey(User) I use django rest framework and would like a serializer Field as such: # bartender/serializers.py class BartenderSerializer(serializers.ModelSerializer): rating = serializers.IntegerField(source='get_rating', read_only=True) class Meta: model = Bartender fields = [] My Viewset is class BartenderViewset(viewsets.ModelViewSet): queryset = Bartender.objects.all() serializer_class = BartenderSerializer how do I add a model method to my Bartender model, such that it returns the Rating object for whatever User is making the call. I tried this modification to my Bartender class: # bartender/models.py class Bartender(models.Model): name = models.CharField(max_length=64) owner = models.ForeignKey(User) def get_rating(self): return Rating.objects.get(bartender=self.id, owner=self.request.user) However self has no request. Therefore, I would like to know how to implement this so it is callable via drf viewsets. -
Django. Get field and subtract automatically
I want to realize something that looks like a client balance field. So: class Product(models.Model): name = models.CharField(max_length) price = models.PositiveIntegerField() class Client(models.Model): name = models.CharField(max_length) balance = models.DecimalField() class Order(models.Model): client = models.ForeignKey(Client) product = models.ForeignKey(Product) price = models.ForeignKey(Product) model is above i need to write query that takes orders total price and subtract from client balance field automatically.Is it possible? Thnaks -
python convert timezone issue
I have Jalaali date and time as Iran timezone,what I want to do is convert them to Gregorian date and UTC time respectively and separately and then create a Django datetime object to save it in my model ,everything works fine but when I try to save it , it saves previous value for them (before converting with astimezone), but if remove the tzinfo from datetime object the save problem goes away this is my code: import datetime import pytz gregorian_dict = {'gy':2018,'gm':2,'gd':3} time_list = [9,0,0] gregorian_date_iran_time = pytz.timezone('Iran').localize(datetime.datetime(gregorian_dict['gy'], gregorian_dict['gm'], gregorian_dict['gd'],time_list[0],time_list[1],time_list[2])) gregorian_date_utc_time = gregorian_date_iran_time.astimezone(pytz.utc) so far everything is Okey and the output is desired, but when i try to save it the value for gregorian_date_iran_time is save instead eventhough the prints is desired values suggestion = Suggest() suggestion.request = online_request suggestion.teacher = teacher suggestion.session_length = length print(gregorian_date_utc_time) # 2018-02-03 05:30:00+00:00 suggestion.date = gregorian_date_utc_time print(suggestion.date) # 2018-02-03 05:30:00+00:00 suggestion.save() but when i do this,i get correct result after save gregorian_date_utc_time = gregorian_date_utc_time.replace(tzinfo=None) I dont know if I am making a dumy mistake or forget something what is the solution for this? -
How do I test logging in using Django Rest + JWT
question here. I'm having trouble testing my login feature using DRF + JWT. It all works OK outside of test environment, I can login as an admin using exact same method and I get my token back. from django.test import TestCase from django.contrib.auth.models import User from rest_framework.test import RequestsClient TEST_USER = { 'username': 'test1', 'email': 'test@test.com', 'password': 'qwe123qwe', } BASE_URL = 'http://testserver/' API_LOGIN = 'http://testserver/' + 'api-token-auth/' class TestAuthentication(TestCase): def setUp(self): User.objects.create(**TEST_USER) self.requests = RequestsClient() def test_user_can_login(self): user = User.objects.first() self.assertEqual(User.objects.count(), 1) response = self.requests.post(API_LOGIN, TEST_USER) print(response.content) the output is: b'{"non_field_errors":["Unable to log in with provided credentials."]}' .. ---------------------------------------------------------------------- Ran 2 tests in 0.018s I would really like to include login/logout in my tests as it is base of my project. If I can provide any more information that would help you help me please comment, I will be watching this thread until it is solved, I have nothing better to do :) -
any idea on how to resolve this PYTHONHOME
```Could not find platform independent libraries Could not find platform dependent libraries Consider setting $PYTHONHOME to [:] Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings' Current thread 0x00007fe39e395700 (most recent call first): ``` -
Django: How to filter related objects based on different criteria?
I'm working on a 'workflow management website' where different workflows with different steps can be tracked. A workflow is defined by a number of steps with a given order. A 'Job' realizes the workflow and 'Tasks' realize the steps. class Workflow(models.Model): name = models.CharField(_('Name'),max_length = 100, unique = True) class Step(models.Model): workflow = models.ForeignKey( Workflow, on_delete=models.CASCADE, ) name = models.CharField(_('Name'), max_length = 100) order = models.SmallIntegerField(_('Reihenfolge')) class Job(models.Model): workflow = models.ForeignKey( Workflow, on_delete=models.CASCADE, ) def current_task(self): # first task without finished date my_tasks = self.task_set\ .filter(finished__isnull=True)\ .order_by('step__order') if my_tasks.exists(): return my_tasks.first() return False class Task(models.Model): job = models.ForeignKey( Job, on_delete=models.CASCADE, ) step = models.ForeignKey( 'Step', on_delete=models.CASCADE, ) assigned_to = models.ForeignKey( User, on_delete=models.CASCADE, ) The current task of a workflow is the 'first' task without a 'finished' date (ordering is given by task.step.order). If there is no such task, the job is finished. My question is how to filter current tasks for a number of jobs. For example I want to filter Jobs where the current task is assigned_to some user. So far I used a for-loop and checked job.current_task().assigned_to for each job, but this obviously is a pretty slow/dumb way of doing that. Is there a more efficient way? I … -
Redirecting to a separate Django view after Ajax request is successful
Django/Python server-side dev here. And also a JS newbie (8 days old). This question is about Ajax-initiated page reloads. Here's a JS snippet where I'm processing the JSONResponse from a Django view I POSTed some data to. Depending on success or failure, you'll see that I'm calling a redirect to another Django view: var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var resp = JSON.parse(this.responseText); if (!resp.success) { console.log("Failed!"); } else { console.log("Success! Redirect to: ", resp.success_url); window.location.href = resp.success_url; window.location.reload(); } } }; xhr.open('POST', e.target.action); xhr.setRequestHeader("X-CSRFToken", get_cookie('csrftoken')); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.send(form_data); Specifically, the following lines do the trick: window.location.href = resp.success_url; window.location.reload(); My problem is that when this gets executed in Firefox, I am made to see the following dialog box: It seems the POST parameters are being sent again ?! How do I just do a plain old GET type redirect to resp.success_url instead? Please advise and let me know if you need more information. Note: let's stick to pure JS for the scope of this question - I'm learning vanilla JS these days and don't want to get into JQuery prematurely. -
no display name and no $DISPLAY environment variable django and matplotlib
I have views.py like bellow: import matplotlib.pyplot as plt import matplotlib def anyfunction(request): a1=[i.created_date.strftime("%D") for i in model.objects.all()] b1=dict((x,a1.count(x)) for x in set(a1)) c1=sorted(d1.items(), key=lambda x: x[0]) c11=[i[0] for i in c1] c12=[i[1] for i in c1] matplotlib.use('Agg') fig = plt.figure() ax = fig.add_subplot(111) ax.plot(c11,c12) plt.bar(c11, c12, align='center') plt.title('Per Day User Visit Count') plt.ylabel('No of Per Day User Visit axis') plt.xlabel('Date ') fig.savefig('test.png') return render_to_response('sa.html') When i run it with django shell , its running fine , but when i put these codes in views.py , i am getting following error. no display name and no $DISPLAY environment variable Can i get some help here . -
Annotate queryset and display data in admin - Django
I'm new to both Django and Python. Currently I'm trying the Django Admin by doing. I've three models for a Django app, which are GoodsItem, SoldGoodsItem and FinishedGoodsItem. The models.py is: from django.db import models class GoodsItem(models.Model): name = models.CharField(max_length=255) size = models.DecimalField(max_digits=4, decimal_places=2) INCHES = 'IN' NUMBER = 'NUM' GOODS_ITEM_SIZE_UNITS = ( (INCHES, 'Inches'), (NUMBER, '#'), ) size_unit = models.CharField( max_length=4, choices=GOODS_ITEM_SIZE_UNITS, default=INCHES, ) def __str__(self): if(self.size_unit == self.NUMBER): return "%s #%s" % (self.name, (self.size).normalize()) else: return "%s %s\"" % (self.name, (self.size).normalize()) class FinishedGoodsItem(models.Model): date = models.DateField() goods_item = models.ForeignKey(GoodsItem, on_delete=models.CASCADE, related_name="finished_name") weight = models.DecimalField(max_digits=6, decimal_places=3) def __str__(self): return str(self.goods_item) class SoldGoodsItem(models.Model): goods_item = models.ForeignKey(GoodsItem, on_delete=models.CASCADE, related_name="sold_name") date = models.DateField() weight = models.DecimalField(max_digits=6, decimal_places=3) def __str__(self): return str(self.goods_item) And here is admin.py: from django.contrib import admin from django.db.models import Sum from .models import GoodsItem, FinishedGoodsItem, SoldGoodsItem @admin.register(SoldGoodsItem) @admin.register(FinishedGoodsItem) class FinishedGoodsItemAdmin(admin.ModelAdmin): fields = ('date', 'goods_item', 'weight') list_display = ('date', 'goods_item', 'weight') @admin.register(GoodsItem) class GoodsItemAdmin(admin.ModelAdmin): list_display = ('__str__', 'finished_good', 'sold_good', 'stock_available') def get_queryset(self, request): qs = super(GoodsItemAdmin, self).get_queryset(request) qs = qs.annotate( finished_good=Sum('finished_name__weight'), sold_good=Sum('sold_name__weight'), stock_available=Sum('finished_name__weight') - Sum('sold_name__weight'), ) return qs def finished_good(self, obj): return obj.finished_good def sold_good(self, obj): return obj.sold_good def stock_available(self, obj): return obj.stock_available In stock_available for each GoodsItem, I want … -
python 3.5 -> 3.6 Tablib TypeError: cell() missing 1 required positional argument: 'column'
Migrating from python 3.5 to 3.6, my unit tests reveal a problem with django-import-export & tablib: TypeError: cell() missing 1 required positional argument: 'column' File "<path>/lib/python3.6/site-packages/tablib/formats/_xlsx.py", line 122, in dset_sheet cell = ws.cell('%s%s' % (col_idx, row_number)) TypeError: cell() missing 1 required positional argument: 'column' The line in tablib: cell = ws.cell('%s%s' % (col_idx, row_number)) So indeed, there is no argument for the column My view code: my_resource = MyModelResource(queryset=my_queryset) dataset = my_resource.export() response = HttpResponse(dataset.xlsx, content_type='application/vnd.ms-excel') This works fine in python3.5 but fails under 3.6 requirements.txt: ... tablib==0.12.1 django-import-export==0.7.0 Django==1.11.7 ... -
Django template display first 3 related to that category
In reference to this model: My Model I want to show the first three items in one column / for loop, then another 3 in another column / for loop, e.g. Category 1 Item 1 Item 4 Item 2 Item 5 Item 3 Item 6 I tried using slices, but that only retrieves the first three in the object, so if the first two item belongs to Category 1, and the last item belongs to Category 2, it only show 2 items. I want to grab first 3 items for each category, then vice versa, last three items. -
Django Rest Framework Backend and Html/Javascript is Frontend call the url happened Uncaught SyntaxError: Unexpected identifier
$.ajax({ type:'GET' url:'http://127.0.0.1:8000/leave/requests/?format=json' success:function(data){ $.each(data, function(index, data){ var check_status = "Pending" if(data.approval_status == check_status){ if(username == data.reporter){ $('#waiting_for_approval').append (""+data.employee_name+""+ ""+data.from_date+""+ ""+data.to_date+""+ ""+data.no_days+""+ ""+data.leave_type_name+""+ ""+data.reason+""+ ""+data.approval_status+"" ) } } }); } }); }); -
Pycharm not recognizing package that shell does recognize. Django
I have installed a package, django_celery_beat. I can import it in the shell: >>import django_celery_beat >> But Pycharm shows me an error, it underlines the import as if the package wasn't installed. Why could this be? -
Can't get images to work in django
I'm getting a 404 error when trying to serve user uploaded files in local. I've tried a lot of suggestions from the forums but I can't get it to work. This is the error I can see on the logs. The image get uploaded properly to media/images but when I try to use that same image I get a 404 not found. I've tried to put the absolute path and didn't work either. Could anybody please help me? Thanks [03/Feb/2018 23:32:00] "GET /idealistos/30/ HTTP/1.1" 200 483 Not Found: /media/images/_D3L8637.jpg [03/Feb/2018 23:32:01] "GET /media/images/_D3L8637.jpg HTTP/1.1" 404 2239 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Media files MEDIA_ROOT = 'media/' MEDIA_URL = '/media/' models.py from django.db import models from django.forms import ModelForm from django.utils import timezone from django.contrib.admin.widgets import AdminDateWidget # Create your models here. class Anuncio(models.Model): title = models.CharField(max_length=40) description = models.CharField(max_length=300) price = models.CharField(max_length=10) city = models.CharField(max_length=20) state = models.CharField(max_length=20) country = models.CharField(max_length=20) postcode = models.CharField(max_length=20) foto = models.FileField(null=True, blank=True, upload_to='images/') pub_date = models.DateTimeField(default=timezone.datetime.now()) def __str__(self): return self.title def __unicode__(self): return price class AnuncioForm(ModelForm): class Meta: model = Anuncio fields = ['title', 'description', 'price', 'city', 'state', 'country','postcode','foto'] views.py from django.http import Http404, … -
You don't have permission to access admin (Django, wsgi, Apache)
I want to configure my Debian server to provide my Django application. Everything is working fine but my Apache2 is blocking the access to my admin site. So when I am trying to access www.mydomain.com/admin the Apache2 says that I don't have permission to access that site. I can't get why. Alias /static /etc/website/portal/static Alias /media /etc/website/portal/static/media Alias /admin /etc/website/portal/static/admin <Directory /etc/website/portal/static/admin > Require all granted </Directory> <Directory /etc/website/portal/static> Require all granted </Directory> <Directory /etc/website/portal/static/media> Require all granted </Directory> <Directory /etc/website/portal/Portal> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess portal python-home=/etc/website/ python-path=/etc/website/portal WSGIProcessGroup portal WSGIScriptAlias / /etc/website/portal/Portal/wsgi.py The structure of my project on the server: -etc ---website 'that is my virtualenv' -----portal 'my project folder' -------manage.py -------templates -------Portal 'main project' -------SomeApp -------static ----------admin -------------'files of admin' ----------img ----------media ----------static I thought that I gave access with configuring following in the admin: Alias /admin /etc/website/portal/static/admin <Directory /etc/website/portal/static/admin > Require all granted </Directory> I also changed the permissions on the admin folder with chmod 777 and chown :www-data but it is still not working. I don't know if it is relevant but I use a MySQL database. Thank you for your help ! If some information are missing just let me know … -
ValueError at /accounts/upload_save/
I got an error,ValueError at /accounts/upload_save/ The view accounts.views.upload_save didn't return an HttpResponse object. It returned None instead. Always image cannot be sent normally. I wrote in views.py def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): if request.method == "POST": print(444) form = UserImageForm(request.POST, request.FILES) if form.is_valid(): print(5555) image1 = form.cleaned_data.get('image1') image2 = form.cleaned_data.get("image2") user = request.user ImageAndUser.objects.create( User=user, image=image1, image2=image2, image3=image3, ) return redirect('registration/accounts/photo.html') else: print(666) form = UserImageForm(request.POST or None) return render(request, 'registration/profile.html',{'form':form}) in profile.html <main> <div> <img class="absolute-fill"> <div class="container" id="photoform"> <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <div class="input-group"> <label> <input id="image1" type="file" name="image1" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="image2" type="file" name="image2" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="image3" type="file" name="image3" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <input id="send" type="submit" value="SEND" class="form-control"> </form> </div> </div> </div> </main> in forms.py class UserImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = ImageAndUser fields = ('image1','image2','image3') I really cannot understand why this error happens.I surely send images so I think type is not None.What is … -
Send data to Django template via simple_tag
My aim is to draw plots with Echart library separate from my main view. Thar is why I created an custom template to send chart data to the template html file. If I do this with render method the data sending is working. I attach my working render view and the custom view (this would be my aim). Working view and template: View: def chart(request): data=Test.objects.all() data=[i['data'] for i in data] attr=[i['attr'] for i in data] bar = Bar("Teszt Chart") bar.add("Tropo",attr, data, is_stack=True) bar_chart = bar context = dict( myechart=bar_chart.render_embed(), host=DEFAULT_HOST, script_list=bar_chart.get_js_dependencies() ) return render(request, 'test/chart.html', context) Template <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Test chart</title> {% for jsfile_name in script_list %} <script src="{{host}}/{{jsfile_name}}.js"></script> {% endfor %} </head> <body> {{myechart|safe}} </body> </html> My custom template: (not working) View: register = template.Library() @register.simple_tag(takes_context=True) def chart(): data=Test.objects.all() data=[i['data'] for i in data] attr=[i['attr'] for i in data] bar = Bar("Teszt Chart") bar.add("Tropo",attr, data, is_stack=True) bar_chart = bar myechart=bar_chart.render_embed() host=DEFAULT_HOST script_list=bar_chart.get_js_dependencies() data={ 'myechart':myechart, 'host':host, 'script_list': script_list, } return data Template: <!DOCTYPE html> <html> {%load chart%} <head> <meta charset="utf-8"> <title>Proudly presented by PycCharts</title> {% for i in chart %} <script src="{{i.host}}/{{i.jsfile_name}}.js"></script> {% endfor %} </head> <body> {%for i in chart%} {{i.myechart}} {%endfor%} </body> </html> … -
Deploy Django/Python App to Heroku
I'm usign pyhon 2.7.14 but have errors when i tried to deploy my app. I'm working in windows. This is the build log: -----> Python app detected -----> Found python-3.6.4, removing -----> Installing python-2.7.14 -----> Installing pip -----> Installing requirements with pip Collecting backports.shutil-get-terminal-size==1.0.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 1)) Downloading backports.shutil_get_terminal_size-1.0.0-py2.py3-none-any.whl Collecting certifi==2018.1.18 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 2)) Downloading certifi-2018.1.18-py2.py3-none-any.whl (151kB) Collecting chardet==3.0.4 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 3)) Downloading chardet-3.0.4-py2.py3-none-any.whl (133kB) Collecting configparser==3.5.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 4)) Downloading configparser-3.5.0.tar.gz Collecting dj-database-url==0.4.2 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 5)) Downloading dj_database_url-0.4.2-py2.py3-none-any.whl Collecting Django==1.11.10 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 6)) Downloading Django-1.11.10-py2.py3-none-any.whl (6.9MB) Collecting django-bootstrap3==9.1.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 7)) Downloading django-bootstrap3-9.1.0.tar.gz Collecting enum34==1.1.6 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 8)) Downloading enum34-1.1.6-py2-none-any.whl Collecting flake8==3.5.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 9)) Downloading flake8-3.5.0-py2.py3-none-any.whl (69kB) Collecting gunicorn==19.7.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 10)) Downloading gunicorn-19.7.1-py2.py3-none-any.whl (111kB) Collecting idna==2.6 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 11)) Downloading idna-2.6-py2.py3-none-any.whl (56kB) Collecting mccabe==0.6.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 12)) Downloading mccabe-0.6.1-py2.py3-none-any.whl Collecting pathlib==1.0.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 13)) Downloading pathlib-1.0.1.tar.gz (49kB) Collecting pew==1.1.2 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 14)) Downloading pew-1.1.2-py2.py3-none-any.whl Collecting Pillow==5.0.0 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 15)) Downloading Pillow-5.0.0-cp27-cp27mu-manylinux1_x86_64.whl (5.8MB) Collecting pipenv==9.0.3 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt (line 16)) Downloading pipenv-9.0.3.tar.gz (3.9MB) Collecting psutil==5.3.1 (from -r /tmp/build_9dacbaf0fe2d1033eff0e512d820cce8/fabianmedina09-PA05Inception-3d7a5e7/requirements.txt …