Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show received message in chat-box in Django?
I'm working on chat application using Django framework. I wanna show received message instantly when the sender sends the message in the chatbox. I mean, when two users chat in inbox then all messages show dynamically using AJAX call. Someone, please help me out and give me reference link of working code or tutorial related to this. -
Getting an Ebay OAuth Token
I've been working on the ebaySDK for most of the week. I've managed to integrate the Trading and Shopping APIs into my project. For the trading API, I was using an Auth n Auth token which has a validity of upto 18 months. The OAuth Token which I need for the Sell APIs is valid only for a day, so I'll need to fetch it regularly before it expires. I followed the documentation on the site and even tried looking through python repos on github but I haven't been able to move forward as of yet. Here's a quick snippet of my request code, What am I doing wrong? import requests, json, base64, xmltodict AppSettings = { 'app_id' : 'my_app_id', 'app_secret' : 'my_app_secret', 'dev_id': 'my_dev_id', 'ruName': 'the_ruName_for_my_app' } authHeaderData = AppSettings['app_id']+':'+AppSettings['app_secret'] encodedAuthHeader = base64.b64encode(authHeaderData) session = requests.Session() print encodedAuthHeader url = 'https://api.ebay.com/identity/v1/oauth2/token' session.headers.update({ 'Content-Type':'application/x-www-form-urlencoded', 'Authorization':'Basic '+encodedAuthHeader }) data = { 'grant_type':'client_credentials', 'redirect_uri': AppSettings['ruName'], 'scope':'https://api.ebay.com/oauth/api_scope' } response = session.post(url, data=data).json() print response The response I'm getting is: {u'error_description': u'client authentication failed', u'error': u'invalid_client'} I checked all the keys. I even tried to get the token via the production signin provided by ebay but to no avail. The response I got from … -
Django inconsistency of uwsgi and dev servers
I faced strange problem. With the same Django project, site behaviour is different on development server and uwsgi server. Uwsgi and devsrv point to the same settings.py file. The issue here is that one particular app (commented out in settings file) is present in uwsgi server, but absent in development server. This app should be turned off on both servers. Files are the same, because it is the same tree. I have no idea where to seek for bug. It seems like uwsgi do not notice any changes in settings file, and stores previous version somewhere. I do restart uwsgi every time I make changes. I also tried rebooting machine. -
List of zipcodes within distance to user zipcode (Django Project)
Problem/desired Feature: If the user enters his zipcode together with an arbitrary radius/distance i want to return a list of zipcodes who are within the circle or partialy "cut" by the circle around the user location. Boundaries: I dont mind a couple of miles of uncertanties and or using third party apis Technology: Django with PostgreSQL I thought this might be a problem solved a lot so is there a API which i can implement in my Django app to accomplish this? I figured GeoDjango but it looks pretty heavyweight and requires a restructuring of my entire project. Right now i have a GeoPostalcode model as follows: class GeoPostalcode(models.Model): geoP_PLZ = models.CharField(max_length=50, default='') geoP_City = models.CharField(max_length=500, default='') geoP_Bundesland = models.CharField(max_length=400, blank = True, null = True) geoP_Land = models.CharField(max_length=300, blank = True, null = True) I have the data for my country and i think i would be able to get lat/lon as well. But i would prefer a solution using thrid party api(Google?) where i send a zipcode and radius and get a list of zipcodes back to do what ever i want with them. Anyone out there who solved something like this already and know good solutions/apis? Here … -
Django gunicorn nginx (111: Connection refused) while connecting to upstream
A Django application is running on the AWS instance, configured via gunicorn and nginx, it is running well for more than a year, but suddenly, I got 502 bad gateway error, then I saw the below mentioned message in the nginx error log, 2017/05/17 16:18:35 [error] 1040#0: *7460 connect() to unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock failed (111: Connection refused) while connecting to upstream, client: xx.xxxx.xx.xxx, server: xx.xx.xx.xxx, request: "GET / HTTP/1.1", upstream: "http://unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock:/", host: "xx.xx.xx.xxx", referrer: "http://xx.xx.xx.xxx" my nginx configuration: server { client_max_body_size 200M; listen 80; listen [::]:80 ipv6only=on; server_name xx.xx.xx.xxx; listen 443 ssl; ssl_certificate /etc/nginx/ssl/myserver.crt; ssl_certificate_key /etc/nginx/ssl/myserver.key; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/webapps/myproject/myproject; } location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock; proxy_set_header X-Forwarded-Protocol $scheme; } if ($scheme = http){ return 301 https://xx.xx.xx.xxx$request_uri; } if ($http_host = pas-cash.com){ return 303 https://xx.xx.xx.xxx$request_uri; } } my gunicorn.conf description "Gunicorn application server handling myproject" start on runlevel [6789] stop on runlevel [!6789] respawn setuid ubuntu setgid www-data chdir /home/ubuntu/webapps/myproject/myproject exec /home/ubuntu/webapps/myproject/venv/bin/gunicorn --workers 3 --bind unix:/home/ubuntu/webapps/myproject/myproject/myproject.sock myproject.wsgi:application After that I restarted the nginx by following command sudo service nginx restart After restarting, the application is running well, I can't find what will be the specific reason behind this error, I … -
I am not able to use indexing on Django model field which contains large amount of text. I am using MySQL. What should I do?
First I was using models.TextField, but it doesn't support indexing. Switching to models.CharField didn't help as text size was greater than 50000 characters in some rows. Indexing is allowed for maximum 3072 bytes data in MySQL. Should I switch to another RDBMS or use NoSQL like MongoDB? I also tried to use haystack with whoosh for indexing and searching, but searching was very slow. -
Django Count overlap of related objects and queryset/list
Say I have a model: class Car(models.Model): name = models.CharField() parts = models.ManyToManyField(Part) Now in my queryset of Car objects (Car.objects.all()) I want to annotate the count of overlap of parts in my list of ids or my queryset of Parts. Say I have a list parts = (1, 2) I have a car that has part 1, I want to annotate count 1 I have a car that has part 1 and 2, I want to annotate count 2 Is this possible? -
sending multiple values from django dropdown
I have a django form with a dropdown menu <form action="/dir/" method="POST">{% csrf_token %} <table> <tr><td> <select name="listxblocks"> {% for scname, desc in scenarios %} <!--<option value="{% url "workbench_show_scenario" scname %}">{{desc}}/{{scname}}</option>--> <option value="{{scname}}">{{desc}}/{{scname}}</option> {% endfor %} </select> </td> <td></td></tr> </table> <input type="submit" value="Save"/> </form> I'm currently passing one value scname when submitting the form, I need to pass two values scname and desc and access them later How can I send these two values -
Django rq-scheduler, Issue in function execution, not executing the scheduled function
I have an Django project, that has some functionality to run as cron job several times i.e(every half an hour I need this functionality to be executed). Till now the job is scheduling but not executing the function. Here I am attaching the code below: from __future__ import unicode_literals from django.apps import AppConfig from projectApp.views import function_to_exec from django_redis import get_redis_connection rc = get_redis_connection('default') from rq_scheduler import Scheduler scheduler = Scheduler(connection=rc) def ready(): for job in scheduler.get_jobs(): job.delete() scheduler.schedule(datetime.utcnow(), function_to_exec, interval=60, queue_name='high') # scheduler.cron("15 * * * *", func=get_dfp_report, queue_name='high') ready(); The above code is in my application's apps.py and the views.py code is like this : @job('high') def function_to_exec(): # some logic here And in my django-scheduler the status is The status is always in queued state. Can anyone share the some reference for this to achieve. Thanks in advance. -
Django upload file test returns 301
I am trying to test an API post call which allow file uploading but I cannot get it to work, I am always receiving a 301 with open('video.mp4') as f: data = {'file': f} response = self.client.post('/api/upload_file', data, format='multipart') The returned respone is a 301 HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="/api/v1/assets/upload_file/" I make sure the self.client is authenticated and the rest of the tests run correctly self.client = APIClient() self.client.force_authenticate(user=self.user) -
Django: request.user in form
How may I get the user details to use within a from? I know in the view I can just do: currentUser=request.user But if I use it in the form as so I get the following error "'request' is not defined". class SelectTwoTeams(BootstrapForm): currentUser=request.user date_joined = currentUser.date_joined.replace(tzinfo=pytz.utc) timeless30 = datetime.datetime.now() - datetime.timedelta(seconds=3610) timeless30 = timeless30.replace(tzinfo=pytz.utc) if date_joined > timeless30: currentCharities = forms.ModelChoiceField(queryset=Charity.objects.filter(enabled=1), empty_label=None, widget=forms.Select(attrs={"class":"select-format"})) team1 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None, widget=forms.Select(attrs={"class":"select-format"})) team2 = forms.ModelChoiceField(queryset=StraightredTeam.objects.none(), empty_label=None, widget=forms.Select(attrs={"class":"select-format"})) Many thanks for any help in advance. Below shows the init of this form just incase it may help. I know how to get access to the user data using kwargs for this part: def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) self.currentSelectedTeam1 = kwargs.pop('currentSelectedTeam1', None) self.currentSelectedTeam2 = kwargs.pop('currentSelectedTeam2', None) self.currentfixturematchday = kwargs.pop('currentfixturematchday', None) self.currentCampaignNo = kwargs.pop('currentCampaignNo', None) super(SelectTwoTeams, self).__init__(*args, **kwargs) cantSelectTeams = UserSelection.objects.select_related().filter(~Q(fixtureid__fixturematchday=self.currentfixturematchday),campaignno=self.currentCampaignNo, ) if not cantSelectTeams: queryset = StraightredTeam.objects.filter(currentteam = 1).order_by('teamname') else: queryset = StraightredTeam.objects.filter(currentteam = 1).exclude(teamid__in=cantSelectTeams.values_list('teamselectionid', flat=True)).order_by('teamname') teamsAlreadyPlaying = StraightredFixture.objects.filter(soccerseason=1025, fixturematchday=self.currentfixturematchday, fixturedate__lte = timezone.now()) postponedGames = StraightredFixture.objects.filter(soccerseason=1025, fixturematchday=self.currentfixturematchday,fixturestatus = "P") queryset = queryset.exclude(teamid__in=teamsAlreadyPlaying.values_list('home_team_id', flat=True)).order_by('teamname') queryset = queryset.exclude(teamid__in=teamsAlreadyPlaying.values_list('away_team_id', flat=True)).order_by('teamname') queryset = queryset.exclude(teamid__in=postponedGames.values_list('home_team_id', flat=True)).order_by('teamname') queryset = queryset.exclude(teamid__in=postponedGames.values_list('away_team_id', flat=True)).order_by('teamname') self.fields['team1'].queryset = queryset self.fields['team2'].queryset = queryset self.fields['team1'].initial = self.currentSelectedTeam1 self.fields['team2'].initial = self.currentSelectedTeam2 self.fields['team1'].label = False self.fields['team2'].label = … -
Django class based views gueryset model isn't defined
I am producing a web app in Django that stores and sorts courses. The issue I am having is that the query set is not recognizing the model. I have managed to pull all in a class based view and mess around with the data, however, when I try and do a query set it simply says that the model "Course" is not defined. I have imported the following model: class Course(models.Model): provider = models.ForeignKey(Provider) title = models.CharField('Course Title', max_length=200, ) first_line = models.CharField('Address Line: 1', max_length=200, ) second_line = models.CharField('Address Line: 2', max_length=200, ) third_line = models.CharField('Address Line: 3', max_length=200, ) city = models.CharField('City', max_length=200, ) post_code = models.CharField('Post Code', max_length=200, ) course_description = models.TextField('Description') date = models.DateField('Date') start_time = models.TimeField('Starting time') finish_time = models.TimeField('Finishing time') duration = models.IntegerField('Number of hours') CPD = models.IntegerField('CPD points') link = models.CharField('Link', max_length=200) category = models.ForeignKey(Categories) gen_cat = models.ForeignKey(Gen_Categories) location = models.ForeignKey(Gen_Location) cost = models.FloatField('Cost') And I have the following class-based view. The functions that are there like date_screen() were written in another file and imported, they work in my function based views. The issue is that it keeps saying that "Course" is not defined. If you can find anything else wrong with … -
Django urls space gets added after main url
I get this error message Using the URLconf defined in esarcrm.urls, Django tried these URL patterns, in this order: 1. ^person/ duplicate_check/(?P<entity>)/(?P<full_name>)/?$ 2. ^admin/ 3. ^api/v1/ 4. ^api/v1/authenticate/$ [name='api_authenticate'] 5. ^static\/(?P<path>.*)$ 6. ^media\/(?P<path>.*)$ The current path, person/duplicate_check/candidate/tom, didn't match any of these. Please not the space here 1. ^person/[SPACE]duplicate_check my project/urls.py urlpatterns = [ url(r'^person/', include('person.urls')), url(r'^admin/', admin.site.urls), url(r'^api/v1/', include(router.urls)), url(r'^api/v1/authenticate/$', crm_views.ApiAuthenticateView.as_view(), name='api_authenticate'), ] my app.urls urlpatterns = [ url(r'duplicate_check/(?P<entity>)/(?P<full_name>)/?$', views.check_if_exist), ] my app.views @api_view(['GET']) def check_if_exist(request, entity, first_name): if entity == 'candidate': candidates = person_models.Candidate.objects.filter(first_name=first_name) serializer = person_serializers.CandidateMiniSerializer(candidates, many=True) return Response(serializer.data) What exactly am I missing? -
read_sql_query attribute error? In production not development
!#Python3, django Issue: AttributeError: 'module' object has no attribute 'read_sql_query' I am getting the above issue when running the shell on my production server; however, the read_sql_query command appears to be working fine on the development end. Below is the code I am using for the dev and production ends, along with my imports and sql file location. Import statements: from django.db import models from .sql_manager import Rules import pandas as pd import sqlite3 import re import matplotlib.pyplot as plt import matplotlib.ticker as ticker import numpy as np import seaborn as sns Production code: #sqlite file location sqlite_file = '/home/django/castdb.sqlite' conn = sqlite3.connect(sqlite_file) c = conn.cursor() def violin(tag): from random import randint fchanger1 = str(randint(1, 49)) fchanger2 = str(randint(50,99)) fchanger3 = str(randint(100,999)) file = 'violinplots\\violin-' + tag + fchanger1 + fchanger2 + fchanger3 +'.png' filename = '/home/django/django_project/django_project/media/' + file violin = claim_vs_warn_comparison(tag) check = pd.read_sql_query("SELECT sum(incident) FROM ancast WHERE incident_date !='x' AND incident_date !='a' AND incident_date !='i' AND " + tag + " =1", conn) if (check['sum(incident)'] >= 3).bool(): sns.violinplot(violin).set_title('Violin Plot Showing Days Between Incident and Call to Action/Claim').get_figure().savefig(filename) sns.plt.clf() return file else: return None Code in dev: sqlite_file = 'C:\\users\\user\\PycharmProjects\\cast\\castdb.sqlite' conn = sqlite3.connect(sqlite_file) c = conn.cursor() def violin(tag): from … -
ManyToMany is always None
In Django admin panel I have added data to table Test and Testers. I also have selected in each Test one or more Testers. Why method get_tests() always print owner as None? class Test(models.Model): name = models.CharField(max_length=1000, unique=True) owner = models.ManyToManyField('Tester') @classmethod def get_tests(cls, offset=None, test_name_regexp=None): offset = int(offset) if offset else 10 args = { 'name__iregex': test_name_regexp } args = {key: value for key, value in args.items() if value} tests = cls.objects.filter(**args) for test in tests: print(test.name) print(test.owner) return tests -
django typeahead autocomplete
I have a simple Model class Thing(models.Model): name = models.CharField(max_length=40) language = models.CharField(max_length=2, default='de') date_from = models.DateField(default=timezone.now) name should be prepopulated in the form while typing with existing names from existing rows. I had a look at django-select2 or django-autocomplete-light. But both packages are mostly used for ForeignKeys. In fact I do so too in my project Does anybody know a simple way how to solve this task without hacking to much in JavaScript (which sucks). Regards Michael -
Error: TypeError: Cannot read property 'length' of undefined in angular
I have a working Django project and trying to use Angular2 with it. I am new to Angular2. I am getting the following error when I tried to make the routes load from a different file. Also, earlier I have observed that routerLink is getting changed to routerlink in browser. Is this an expected change? Error: TypeError: Cannot read property 'length' of undefined at Object.eval (http://user:8000/ng/src/app/app.route.js:9:16) at eval (http://user:8000/ng/src/app/app.route.js:37:4) at eval (http://user:8000/ng/src/app/app.route.js:38:3) at eval (anonymous) Evaluating http://user:8000/ng/src/app/app.route.js Evaluating http://user:8000/ng/src/main.js Error loading http://user:8000/ng/src/main.js (anonymous) @ (index):23 ZoneDelegate.invoke @ zone.js:232 Zone.run @ zone.js:114 (anonymous) @ zone.js:502 ZoneDelegate.invokeTask @ zone.js:265 Zone.runTask @ zone.js:154 drainMicroTaskQueue @ zone.js:401 ZoneTask.invoke @ zone.js:339 I have googled a lot and found out that this is problem with some versions in angular. So here is my package.json file: { "name": "angular2-quickstart", "version": "1.0.0", "description": "QuickStart package.json from the documentation, supplemented with testing support", "scripts": { "start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" ", "lite": "lite-server", "postinstall": "typings install", "tsc": "tsc", "tsc:w": "tsc -w", "typings": "typings" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@angular/common": "2.0.0-rc.5", "@angular/compiler": "2.0.0-rc.5", "@angular/core": "2.0.0-rc.5", "@angular/forms": "0.3.0", "@angular/http": "2.0.0-rc.5", "@angular/platform-browser": "2.0.0-rc.5", "@angular/platform-browser-dynamic": "2.0.0-rc.5", "@angular/router": "3.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.2", "@angular/upgrade": "2.0.0-rc.5", "systemjs": "0.19.27", … -
Django notifications not a valid choice
I´m having problems with Django notifications. When trying to save a notice setting in Django admin I´m getting following error: Unfortunately I´m not familiar with Django Backend forms. For me this looks like the send value for medium is different than the expected medium type defined in models.py. The medium is defined here. medium = models.CharField(_("medium"), max_length=1, choices=NOTICE_MEDIA) https://github.com/GeoNode/geonode-notification/blob/master/notification/models.py#L90 What steps are needed to get this working? -
send a signal which will unfollow comment thread Django
I have an comment section in my application, and I'm using this django-contrib-comment library. When someone post a comment it will automatically send a signal and mail will be send, so you will be notify when someone leave a comment. Now the idea is to have a list of Users in my model, like this comment_thread=models.ManyToManyField(User), so I can check for that list and if that user is on the list he will be able to unfollow this comment thread, so list will be check before sending mail, but this needs to be done only if he checkbox the button in the template. My question is how can I connect a button to this signal, can someone explain me please? This is my current signal: @receiver(post_save, sender=EmailAddress) def handle_email_address_save(sender, instance, created, update_fields, **kwargs): confirm = account_settings.ACCOUNT_EMAIL_CONFIRMATION_EMAIL must_confirm = instance.must_confirm if hasattr(instance, 'must_confirm') else False warning("handle_email_address_save called for email " + str(instance.email) + ", created = " + str(created) + ", confirm = " + str(confirm) + ", must_confirm = " + str(must_confirm)) if confirm and not instance.verified and must_confirm: instance.send_confirmation() warning("handle_email_address_save sent confirmation") # TODO: move to signals.py in quotes module @receiver(comment_was_posted) def handle_comment_posted(sender, comment, request, **kwargs): if comment.content_type.model == … -
Passing a python list and display correctly
I am trying to pass a list from a csv and fill a select menu in html using django. The format of my csv is like that ["otis","Otis"],["bel","Bel"].. The problem is when I put all the elements in the select the result is a bit weird and don't know how to display correctly, because I want to put in the value = otis and in the option Otis. This is my template: {% for empresa in lista %} <option value="{{empresa}}">{{empresa[empresa]}} </option> #The result is in the html select ['otis','Otis'] ['bel','Bel'] {% endfor %} And this is my function: def csv_empresas(request): lista = [] with open('media/empresas.csv') as csvfile: lector = csv.reader(csvfile, delimiter=',',quotechar='|') for row in lector: lista.append(row) return render(request,'preparar_pdf.html',{"lista": lista}) If u need more information ask me. Thanks a lot. -
Django won't save ManyToMany field on ModelForm
I've got a model similar to the following (this is a condensed version of a long form): class UserProfile(models.Model): display_name = models.CharField() nationality = models.ForeignKey(Nationality) religion = models.ForeignKey(Religion) partner_nationality = models.ManyToManyField( Nationality, related_name='partner_nationality', blank=True) partner_religion = models.ManyToManyField( Religion, related_name='partner_religion', blank=True) And the following model form: class UserProfilePartnerPreferencesForm(ModelForm): partner_nationality = ModelChoiceField( queryset=Nationality.objects.order_by('name'), widget=CheckboxSelectMultiple, empty_label=None, required=False, to_field_name='id') class Meta: model = UserProfile fields = [ 'partner_religion', 'partner_nationality', ] widgets = { 'partner_religion': CheckboxSelectMultiple(), } So what I'm doing in the model form is: Not displaying some fields (the display_name) Changing the widget on a field Creating a custom queryset and changing the widget on a field. This form displays OK but the field where I've passed a custom queryset won't save. If I don't give any values for it, django complains with 'NoneType' object is not iterable while trying to save the field (partner_nationality in this example). If I give it a valid value, it says that the value isn't valid. So it seems like fields where I supply a custom queryset aren't being applied correctly when the form is saved. If I comment out the customisation (i.e. partner_nationality in the ModelForm), it saves correctly with the default settings. How can I … -
Run python function using custom button in Django admin
I added custom button into my app_index.html file: <form action="{% url 'admin:index' %}"> <input type="submit" value="{% trans 'Another Button' %}" name="_anotherbutton" /> </form> I have simple function: def printer(): print('Some text') How can I run this function using my custom button? Now it maps to admin:index but I would like it to run printer function and go to another view (or show alert message using jquery - I will think about it). Printer function is just an example - in real it will do some database search/modify database and go to result view. -
Python dependency issues with Django on Docker
Im new to Docker and im having troubles porting my already existing and working Django project to Docker and im pretty much stuck right now since the issue is with the dependencies in my requirements.txt that are frozen and actually are working on my other environmets (Live on VPS with Ubuntu and Dev on a VM with Arch). The issue itself is while migrating the DB with djangocms_text_ckeditor/html5lib and was reported under eg. https://github.com/divio/djangocms-text-ckeditor/issues/336. How is the Docker environment different so that this error can occur on the same Base OS with the same Python- and dependency versions? what i tried so far: latest dependency versions (unfreeze) different package versions as mentioned on the issue reports. different python versions 3.4 - 3.6 (standart and alpine)(live runs on 3.5 standart) different base image (ubuntu 16.04 - 16.06) deleting package and package dependencies (leads to migration inconsistency) The dependency versions of my requirements file: djangocms-text-ckeditor==3.0.1 html5lib==0.9999999 Any ideas how to fix this issue? -
Django 1.11.1 No SessionID generated on The Project
I am trying to build a app using django. I created the app using django-admin startproject. On viewing the page in the browser no session cookie is set. On checking the response in chrome dev-tools i found that the response has no set cookie for session. I tried adding 'SESSION_SAVE_EVERY_REQUEST = True' in settings.py but the same problem. settings.py file code INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Response Header form testserver HTTP/1.0 200 OK Date: Thu, 18 May 2017 07:23:00 GMT Server: WSGIServer/0.1 Python/2.7.12 X-Frame-Options: SAMEORIGIN Content-Type: text/html Content-Length: 1716 -
Pass a python list to a django template
Hi im new in django and im trying to passa a list that i created in a python function but its not showing nothing and dont understand why? Im trying to send a simple list with only numbers to make it more clear to see. If i can solve that i will try to do in a different way but essentially this is the core problem This is my views.py def csv_empresas(request): lista_nums = ["1","2","3","4"] print (lista) return render_to_response('preparar_pdf.html',{'lista': lista_nums}) This is my html: <body> <header> <div class="container"> <h1>Crear pdf</h1> </div> </header> <div class="container-fluid"> <form action="" class=""> <div class="row col-md-9 col-lg-12 bigsep"> <a class="btn btn-primary" href="{% url 'csv_empresas' %}">Crea empresas</a> </div> <div class="row col-md-9 col-lg-12 "> <h3>Selecciona las empresas que necesites</h3> </div> <div class="row col-md-9 col-lg-12 bigsep"> <select class="selectpicker" data-live-search="true" multiple data-actions-box="true" data-style="btn"> </select> <button class="btn btn-primary btn-md" type="button" onclick="paso2()">Siguiente</button> </div> </form> <div class="container"> <ul> {% for empresa in lista %} <li>{{empresa}}</li> {% endfor %} </ul> </div> </div> And the urls.py from django.conf.urls import url from django.contrib import admin from creadorpdf import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.index,name='index'), url(r'^subir_archivos', views.subir_archivos,name='subir_archivos'), url(r'^preparar_pdf',views.preparar_pdf,name='preparar_pdf'), url(r'^csv_empresas',views.preparar_pdf,name='csv_empresas') ]