Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Data column(s) for axis #0 cannot be of type string
i am trying to draw a chart using google chart but this error appears : Data column(s) for axis #0 cannot be of type string My initial data is in this form : 20160413,100000.0,100000.0 20160414,100017.287579,98685.5322684 20160415,99918.8444214,99054.1977814 20160418,100572.410945,100190.134483 20160419,100882.626944,101014.591377 20160420,100959.460628,100361.830561 20160421,100435.070735,100055.642158 My python code is : import string from datetime import datetime, date plotFil=open('sergPlotOut20170426','r') plotLis = [pf.strip().split(',') for pf in plotFil] plotFil.close() plo = [] for pl in plotLis: plo.append( { 'date': date( int(pl[0][:4]), int(pl[0][4:6]), int(pl[0][6:]) ), 'x1': float(pl[1]), 'x2': float(pl[2]), } ) print plo plo is similar to this : [{'date': datetime.date(2016, 4, 13), 'x2': 100000.0, 'x1': 100000.0}, {'date': datetime.date(2016, 4, 14), 'x2': 98685.5322684, 'x1': 100017.287579}, {'date': datetime.date(2016, 4, 15), 'x2': 99054.1977814, 'x1': 99918.8444214}, {'date': datetime.date(2016, 4, 18), 'x2': 100190.134483, 'x1': 100572.410945}, {'date': datetime.date(2016, 4, 19), 'x2': 101014.591377, 'x1': 100882.626944}, {'date': datetime.date(2016, 4, 20), 'x2': 100361.830561, 'x1': 100959.460628}, {'date': datetime.date(2016, 4, 21), 'x2': 100055.642158, 'x1': 100435.070735}, {'date': datetime.date(2016, 4, 22), 'x2': 99788.7762971, 'x1': 100439.87284}, {'date': datetime.date(2016, 4, 25), 'x2': 98821.2141171, 'x1': 100257.873052}, {'date': datetime.date(2016, 4, 26), 'x2': 99935.6382386, 'x1': 100445.635367}, {'date': datetime.date(2016, 4, 27), 'x2': 101294.648959, 'x1': 100611.307997}, {'date': datetime.date(2016, 4, 28), 'x2': 102358.175333, 'x1': 99682.5808434}, To display the chart this is the code : <div id="chart_div" style="width: 100%; height: … -
Failed to load resource: the server responded with a status of 405 (METHOD NOT ALLOWED) in django
i am making an app in django. this is my index.html page. <!DOCTYPE html> <html> <head> <title>The index page</title> </head> <body> <h1>Choose the name of student</h1> <form action= "{% url 'detail' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <select name="namedrop"> {% for name in student_list %} <option>{{name.stuname}}</option> {% endfor %} </select> <input type="submit" name="submit"> </form> </body> </html> it creates a drop down list of the name of students. when i select one and click on submit button, it opens a new page detail but fails to show anything on the page. the error it is showing is Failed to load resource: the server responded with a status of 405 (METHOD NOT ALLOWED). my views.py is as below: from .models import student,subject from django.views import generic from django.views.generic import View from django.shortcuts import render class IndexView(generic.ListView): template_name= 'studinfo/index.html' context_object_name= 'student_list' def get_queryset(self): return student.objects.all() class DetailView(generic.DetailView): model= student,subject template_name='studinfo/detail.html' def getname(request): if request.method=='POST': name=request.get['namedrop'] return render(request, 'detail.html', {'name':name}) please help soon. -
Integration of Django based plug-ins into wagtail
Can anyone describe the general actions when integrating addons or widgets built originally for django in to wagtail? For a novice user, it's hard to understand exactly how to edit the code so that it works in wagtail cms. For example, I'm trying to integrate two very useful Django addons(widgets) into my project and I encounter in both cases the problem, when it comes to customizing and inserting code into settings.py In both cases i have to customize some code but we don't have settings.py in wagtail and if ill try to put this code: COUNTRIES_OVERRIDE = { 'XZ': _('Tibet') } in to base.py I'm getting an error: (env) C:\Users\xakep\Documents\GitHub\database\blemmy>manage.py runserver Traceback (most recent call last): File "C:\Users\xakep\Documents\GitHub\database\blemmy\manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Python36\lib\site-packages\django\core\management\__init__.py", line 307, in execute settings.INSTALLED_APPS File "C:\Python36\lib\site-packages\django\conf\__init__.py", line 56, in__getattr__self._setup(name) File "C:\Python36\lib\site-packages\django\conf\__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "C:\Python36\lib\site-packages\django\conf\__init__.py", line 110, in__init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", … -
Gunicorn async workers (gevent) not working with Django-Oscar: 500 Internal server error
Brief Django-Oscar web application running in production and staging environment, hosted in virtual environment, running as systemd daemon using Gunicorn. Nginx is used as proxy, gunicorn is working normally left to the default "worker-class" which is "sync", but its not suitable for our case, I need to change it to async, specifically "gevent", usually its done by adding the following parameters to ExecStart --worker-class gevent --worker-connections 768 But the workers did not start and I got the following error [2017-08-15 08:42:35 +0000] [25425] [INFO] Starting gunicorn 19.7.1 [2017-08-15 08:42:35 +0000] [25425] [DEBUG] Arbiter booted [2017-08-15 08:42:35 +0000] [25425] [INFO] Listening at: unix:/tmp/myapp.sock (25425) [2017-08-15 08:42:35 +0000] [25425] [INFO] Using worker: gevent [2017-08-15 08:42:35 +0000] [25430] [INFO] Booting worker with pid: 25430 [2017-08-15 08:42:35 +0000] [25425] [DEBUG] 1 workers [2017-08-15 11:42:37 +0000] [25430] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/workers/ggevent.py", line 190, in init_process super(GeventWorker, self).init_process() File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/home/ubuntu/.virtualenv/myapp-env/local/lib/python2.7/site-packages/gunicorn/util.py", … -
How to extract values from log file simultaneously while a process is running in django view
To update my progress bar, i need to compute the percentage of progress of a process running in my django view, to do this; i have to retrieve some values simultaneously from a log file generated while this one is running so that i can compute the percetage equivalent to 0/5000, 19/5000... as shown in the picture. I'm new to django and programming in general. How can I do that please in a function in my django views.py? or if there is a way to it with javascript will be also good solution. Thank you in advance. The log file which is generated looks like this: -
celery received tasks and execute it step by step (Singleton)
in my Django project with celery I have celery task function that needs received all incoming tasks but starts it step by step like Singleton. I can do this like: Pseudo-code_ def sing_func(id): while (function is Busy): time.sleep(10) .....start this task.... but I think this is not the correct way to use this inside Celery, I think must be the better way to implement this -
Revert migration on deleted not null field
I've got a model with a non-null field which I deleted: class Spam(models.Model): slug = models.SlugField(allow_unicode=True) # deleted After I made the migrations and applied them, I wanted to revert them. But obviously, this results in django.db.utils.IntegrityError: NOT NULL constraint failed: eggs_spam.slug How can I revert the migration? -
AuthTokenSerializer. Invalid data. Expected a dictionary, but got Request. Django
Sorry for my english. I have learning django rest and i want create token authorization. I did it by tutorial, but i have error, when send data to server { "non_field_errors": [ "Invalid data. Expected a dictionary, but got Request." ] } my setting file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'users', ] .. .. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',), 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } my url urlpatterns = [ url(r'^authtoken', views.ObtainAuthToken.as_view()), ] my view class ObtainAuthToken(APIView): permission_classes = (permissions.AllowAny,) serializer_class = AuthTokenSerializer def post(self, request): serializer = self.serializer_class(data=request) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}, status.HTTP_201_CREATED) i dont understand why i have error -
Django referencing Javascript variable in server side template code
I have a page that adds textboxes dynamically, and on the dynamically added text boxes, I want to access the relevant context variable. To do so, I somehow need to use the 'i' variable inside the javascript code/template code to reference it's value in the context. Here's my javascript code where I need to use 'i' as an index for a context list: <script> var i = 2 function add_field() { var table = document.getElementById("tbl_location").getElementsByTagName('tbody')[0]; var input_name = document.createElement("th") input_name.appendChild(document.createTextNode("S/N " + i)) var input_tb = document.createElement("td") var input = document.createElement('input'); input.setAttribute("name", "sn" + i); {% if curr_sn.i %} input.setAttribute("value", {{ curr_sn.i }}); {% endif %} input_tb.appendChild(input) var input_row = document.createElement("tr") input_row.appendChild(input_name) input_row.appendChild(input_tb) table.appendChild(input_row); i++; } The specific lines are: {% if curr_sn.i %} input.setAttribute("value", {{ curr_sn.i }}); {% endif %} Where 'i' is a javascript veriable, and curr_sn is a list the python code gives as a context. The html part where I need to use 'i': {% for i in max_board_list %} {% if curr_sn.i %} <tr> <th>S/N {{ i }}</th> <td><input type="text" name="sn{{ i }}" value="{{ curr_sn.i }}"></td> </tr> {% endif %} {% endfor %} Here 'i' is generated by a for loop, but I still need … -
Django render arguments
I am having model Post and application blog This is my view.py from django.shortcuts import render, get_object_or_404 from .models import Post def post_list(request): posts = Post.published.all() return render(request,'blog/post/list.html',{'posts': posts}) From Django documentation, render(request, template_name, context=None, content_type=None, status=None, using=None) What is my template_name? Why do I have 'posts': posts ? -
Ordering a Django queryset based on other list with ids and scores
I'm a bit mentally stuck at something, that seems really simple at first glance. I'm grabbing a list of ids to be selected and scores to sort them based on. My current solution is the following: ids = [1, 2, 3, 4, 5] items = Item.objects.filter(pk__in=ids) Now I need to add a score based ordering somehow so I'll build the following list: scores = [ {'id': 1, 'score': 15}, {'id': 2, 'score': 7}, {'id': 3, 'score': 17}, {'id': 4, 'score': 11}, {'id': 5, 'score': 9}, ] ids = [score['id'] for score in scores] items = Item.objects.filter(pk__in=ids) So far so good - but how do I actually add the scores as some sort of aggregate and sort the queryset based on them? -
Django - saving partially filled form to prevent data loss
I have a form which takes quite a long time for the user to fill. I would like to set up a feature (some AJAX) which saves the currently filled values every N seconds so that the user does not lose their data in case of connection problems/misclick/internal server error. Sure, I can do this on my own by saving the user and filled values in some serialized form (say JSON) into a manually created table in the database. But I wonder, can Django do this for me? I hope it makes sense at least a bit and thanks in advance for your ideas! -
Django register api with two User profile models
I am trying to create user, where User model has two User profiles, e.g. Teacher and Student. At the time of creating user, I want to create User instance in Teacher or Student profile also. Here's my Serializer classes: class StudentSerializer(serializers.ModelSerializer): class Meta: model = StudentUser fields = ('id', 'user_id') class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = ('id', 'user_id') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'username', 'password', 'email', 'user_type' ) extra_kwargs = { 'password': {'write_only': True}, } def create(self, validated_data): user = User.objects.create_user(**validated_data) return user Here's the custom register view: class CreateUserView(CreateAPIView): model = User permission_classes = [ permissions.AllowAny # Or anon users can't register ] serializer_class = UserSerializer Right now, I am able to create User and but creating user profile according to the user_type parameter is a challenge for me. So, if user_type is student, I need to create User instance for the StudentProfile as well(a new row in student profile table) -
Can I cut out the string in the Django template?
This is my code in templates: {% for wine_con in data.winry_consult %} <li><a href="/article_list_content-{{win_con.id}}/"><p>{{ win_con.content }}</p><i class="font">&#xe6aa;</i></a></li> {% endfor %} I found the win_con.content is too long for my website, I only want 5 count characters, how can I cut out the win_con.content in template? -
DRF Response content-type set to None during tests
I'm using Django Rest Framework (version 3.6.2) to create REST API. I've defined my viewset that inherits from GenericViewSet and have overriden retrieve method to implement custom behaviour. class FooViewSet(viewsets.GenericViewSet): serializer_class = FooSerializer def retrieve(self, request, *args, **kwargs): ... serializer = self.get_serializer(data) return Response(serializer.data) I want to have BrowsableAPI while accessing this endpoint from the browser and receive json response when accessing this endpoint e.g. from the code. I've configured DRF with the following settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'TEST_REQUEST_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'TEST_REQUEST_DEFAULT_FORMAT':'json' } Everything works as expected, I can access the browsable API from the browser and when making request with the Postman tool I get json response. Unfortunately, I can't achieve the same result during tests. class GetFooDetailViewTest(APITestCase): def test_get_should_return_json(self): response = self.client.get(self.VIEW_URL) self.assertEqual(response.content_type, "application/json") I expect the response to have content_type set to application/json (this is the header that I can see in the responses from browser and Postman). But this test fails - response.content_type is set to None. While debugging this test, I've discovered that response._headers dictionary looks like this { 'vary': ('Vary', 'Cookie'), 'x-frame-options': ('X-Frame-Options', 'SAMEORIGIN'), 'content-type': ('Content-Type', 'application/json'), 'allow': ('Allow', 'GET, PUT, DELETE, OPTIONS') } So it seems like … -
Can I change Django's "Starting development server" link?
When I start my in-development Django site I get the following message: System check identified no issues (0 silenced). August 15, 2017 - 12:03:00 Django version 1.11.3, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. It would be convenient to just click the provided link. However, 127.0.0.1 is not one of my ALLOWED_HOSTS, so it doesn't work. Can I set or override this message so that it uses a valid link? -
Custom model validation for many to many field in django
Hi there I have a model like this: class Team(models.Model): owner = models.ForeignKey(User) members = models.ManyToManyField(User) Now One Owner can have multiple teams but a particular member will only belong to one team. So let's say if there is a team with member John, user can't create team with the same member again. For that, I am trying to add custom model field validation: def clean_fields(self, exclude=None): super(MentorTeam, self).clean_fields(exclude=exclude) self.candidates # This returns error because the team instance is not saved yet. How can I do this validation? -
Django rest pagination next url is not correct
I have created a Django rest api using ModelViewSet. Deployed in staging and now in production.Production is working fine,but staging has some incorrect "next" url. See the key "next" in both images, first image is the staging response and second one is the production response.In staging next key, "nub.staging.scoretrends.com" appears twice.Same code is used in both environment.Working fine in localhost too.What makes it happened like this? The ModelViewSet is shown below. class EntityDetail(viewsets.ModelViewSet): """ Retrieve a spider. """ queryset = Entity.objects.all() serializer_class = EntitySerializer filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter) filter_class = EntityFilter filter_fields = ('name', 'entity_type', 'gender', 'active', 'verified', 'date_created', 'date_modified') ordering_fields = ('name', 'date_created', 'date_modified') def get_queryset(self): queryset = Entity.objects.all() name = self.request.query_params.get('name', None) industry = self.request.query_params.get('industry', None) entity_types = self.request.query_params.get('entity_types', None) if name: queryset = Entity.objects.filter(name__icontains=name) if industry: queryset = Entity.objects.filter(meta__primary_industry__iexact=industry) if entity_types: entity_types = [int(id) for id in entity_types.split(',')] queryset = queryset.filter(entity_type__in=entity_types) return queryset def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) if request.query_params.get('nopaginate') is None: page = self.paginate_queryset(queryset) if page is not None: serializer = EntitySerializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = EntitySerializer(queryset, many=True) return Response(serializer.data) def update(self, request, *args, **kwargs): instance = self.get_object() serializer = EntitySerializer(instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save(entity_id=instance.pk, **serializer.validated_data) return Response(serializer.data) def partial_update(self, request, *args, … -
How to I manipulate form.as_p in a Django form?
I am trying to submit two forms at once. And It appears that I have to use {{form.as_p}}. But now I face two problems. 1. How do I get the id of {{form.as_p}}. 2. Within each form I have input fields. How do I edit the width of these fields? Thank you! <form id = "form" action="." method="POST">{% csrf_token %} {{form1.as_p}} <div > <input id = "geoButton" type="button" class = "btn" value="{{geoFormButtonValue}}" onclick = "formHandler()" /> </div> <hr> {{form2.as_p}} <div > <input id = "totalRiskButton" type="button" class = "btn" value="{{geoFormButtonValue}}" onclick = "formHandler2()" /> </div> </form> <div> <input type="button" class = "btn" value="Run" onclick="SubmitForm()" style="float:right"/> </div> -
Django. How to set default option use generic CreateView
Model: class MyModel(model.Models) status = models.ForeignKey(Statuses, on_delete=models.PROTECT, null=True, blank=True) Views: class MyViewCreate(CreateView): model = MyModel form_class = MyFrom template_name = 'mymodel_form.html' Forms: class MyForm(ModelForm): class Meta: model = MyModel fields = '__all__' How i can in form set default or first value on the option list > -
Forbidden (403) CSRF verification failed. Request aborted
I created a custom template form for signup, and whenever I try to signup in my Django application. i get this error message CSRF verification failed. Request aborted. I created a custom template form for signup, and whenever I try to signup in my Django application. i get this error message CSRF verification failed. Request aborted. CSRF token missing or incorrect. Just really don't to do again. I have not being able to by pass this error. views.py from django.shortcuts import render_to_response from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.template import RequestContext from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from django.core.mail import EmailMessage from .forms import SignupForm def index(request): return render_to_response('accounts/index.html') def register(request): if request.method == "POST": form = SignupForm(request.POST) if form.is_valid(): username = request.POST.get('uname') first_name = request.POST.get("fname") last_name = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") dob = request.POST.get("dob") gender = request.POST.get("optradio") new_user = Signup('username', 'first_name', 'last_name', 'email', 'password', 'dob', 'gender') new_user.is_active = False new_user.save() current_site = get_current_site(request) message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) mail_subject = 'Activate your linkzone … -
django - Form ValidationError not working
I'm trying to raise Validation error where : 1) if the date selected in the start_date field is the day before today then it will raise and error 2) if end date is a date before the start date, it will raise another error. I know this is not the first time somebody ask this question but I followed the answer given by others and it's not working, where I do wrong? Any help is much appreciate. Below is my code : model.py: class Leave(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='+') start_date = models.DateField() end_date = models.DateField() duration = models.FloatField() form.py : class LeavesDetailForm(forms.ModelForm): class Meta: model = Leave fields = ('employee', 'type', 'status', 'start_date', 'end_date', 'duration', 'comment') widgets = {'start_date': forms.DateInput(attrs={'type': 'date'}), 'end_date': forms.DateInput(attrs={'type': 'date'}), 'employee': forms.HiddenInput(), 'duration': forms.HiddenInput(), 'status': forms.HiddenInput()} def clean_date(self): start_date = self.cleaned_data.get('start_date') if start_date < datetime.date.today(): raise forms.ValidationError("The date cannot be in the past!") return start_date view.py : def my_leaves_view(request): form = LeavesDetailForm(request.POST or None) leaves_log = Leave.objects.all().filter(employee=request.user.profile.employee.id) if form.is_valid(): inst = form.save(commit=False) inst.start_date = form.cleaned_data['start_date'] inst.end_date = form.cleaned_data['end_date'] duration = (inst.end_date - inst.start_date).days inst.duration = duration inst.save() return HttpResponseRedirect('my_leaves_content.html') context = {'form': form} return render(request, 'hrm/my_leaves/my_leaves_content.html', context) -
How to put default Django Login in Bootstrap Modal?
I created a login template and imported the default url routing following MDN's guide, but now I want to put that into a modal to not have the user go through so many redirects. I realize variants of this question have been asked, but I read through so many and am still really confused. I have the template as configured in the MDN link, but if I try taking the content and pasting it directly into my modal in another template, it does not show the fields since they depend on Django template variables. I believe the default url config is from django.contrib.auth import views as auth_views url(r'^accounts/login/$', auth_views.LoginView.as_view()), but I'm also pretty confused about it since it was built in. All I had to do to implement the login form was write the login template and add url(r'^accounts/', include('django.contrib.auth.urls')), to my project urls, so it is pretty daunting to create the modal login from here. Do I have to write a new LoginView class as well? Should I be using something like django-crispy-forms? I currently just post the data, but will I need to use AJAX instead for when a field is incorrect? Any guidance is so appreciated. Much … -
Heroku keeps deleting online added data
I deployed a django project on heroku. For media storage, I used aws s3 storage. The project has an admin interface, from which I can add data. The problem is that, after some time, the data I added online on heroku is lost. Only the original data (that was in my databse before deploying on heroku ) is conserved. I'm using heroku only for test, but still this is bothering. Is there's a way to overcome this behaviour? I though about storing data also in aws s3 but I don't know how to do it. -
get_template_names(self) doesn't work in TemplateView
I'm trying to use PDFView from django-pdfkit. The problem is that I don't have one template. Instead I have 4 templates. The template chosen depends on request.GET parameter. So I've created a View called Test which extends PDFView. class Test(PDFView): def get_template_names(self): # don't bother with chosing template for now return ["pdf/dobropis_pdf_template.html"] def get_context_data(self, **kwargs): doklad = get_object_or_404(Doklad, pk=self.request.GET.get('id')) return {'doklad':doklad} The problem is that if I don't specify template_name, It returns: TemplateDoesNotExist at /render/doklad/ None So I suppose the get_template_names method isn't even called. Why is that so? How can I make it work? This is from urls.py: url(r'^render/doklad/', views.Test.as_view(), name="doklad_to_pdf"), This is a PDFView (in case it helps): class PDFView(TemplateView): #: Set to change the filename of the PDF. filename = None #: Set to default the PDF display to inline. inline = False #: Set pdfkit options dict. pdfkit_options = None def get(self, request, *args, **kwargs): """ Return a HTTPResponse either of a PDF file or HTML. :rtype: HttpResponse """ if 'html' in request.GET: # Output HTML content = self.render_html(*args, **kwargs) return HttpResponse(content) else: # Output PDF content = self.render_pdf(*args, **kwargs) response = HttpResponse(content, content_type='application/pdf') if (not self.inline or 'download' in request.GET) and 'inline' not in request.GET: …