Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app with docker-compose keep the data in media volume
I'm using Django cookiecutter with docker and docker-compose. On production I'm using dj-static to serve my media files. Whenever I use 'docker-compose down' command everything that is in my media volume gets deleted. I think this is the expected outcome of that command but everything that is in 'postgreSQL' is kept. How can I do that with the 'media' volume? -
How to check current request.path in Django urls.py [duplicate]
This question already has an answer here: Check if redirect url exists 1 answer I would like to check my current URL's in django urls or not. if i need to do redirect.. My URL'S are like this, url(r'^$', TemplateView.as_view(template_name='login.html'), name='login_page'), url(r'^my_perf/$', TemplateView.as_view(template_name='performance.html'), name='performance' ), etc.... I wrote middleware to check, if current request.path == reverse('specific_url') but i want to check dynamic urls in urls.py or not? eg: i will get current url from request.path which is contains in urls by checking entire urls page. how do i achieve this? -
Django model save() - AttributeError: 'NoneType' object has no attribute 'append'
In my models.py I want to extend the Django User model by adding an email_list. from django.contrib.postgres.fields import ArrayField class User(AbstractUser): email_list = ArrayField(models.EmailField(max_length=100), null=True, blank=True) [...] This email_list has to have the user email as default value. I found that the best way to do this, is by overriding the save() method: def save(self, *args, **kwargs): self.email_list.append(self.email) super(User, self).save(*args, **kwargs) However, when I add a user I get the following error: AttributeError: 'NoneType' object has no attribute 'append' And the print(type(self.email_list)), returns <type 'NoneType'> What is wrong with the ArrayField? -
django recreate dropped table
I dropped a table manually cause while changing the model I made a very bad mistake. So anyway ... how can I recreate it ? I have tried : - Delete the migrate folder of that app - delete from django_migrations where app='main' - makemigrations main - migrate main But it stops at the first table. Which is there :-( and my Table message in that case is not recreated. In initial.py I have the correct entry for my table migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('unread', models.BooleanField(default=True)), ('subject', models.CharField(max_length=120)), ('freetext', models.TextField(null=True)), ('from_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user', to=settings.AUTH_USER_MODEL)), ('to_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user', to=settings.AUTH_USER_MODEL)), ], ), Is there way to start this manually ? -
Django form field not displaying correct queryset values
The following code is from an multi-vendor ecommerce portal. We need to display different shipping methods according to the store(or vendor) on the checkout summary page. However even though I get correct queryset while print i.e Store 1 has Test Rest of World Shipping method and Store 2 has UPC and DHL, the rendered form shows incorrect values - ######################################################### class ShippingCountryChoiceField(forms.ModelChoiceField): widget = forms.RadioSelect() def label_from_instance(self, obj): price_html = format_price(obj.price.gross, obj.price.currency) label = mark_safe('%s %s' % (obj.shipping_method, price_html)) return label class ShippingMethodForm(forms.Form): def __init__(self, country_code, *args, **kwargs): stores = kwargs.pop('stores') super(ShippingMethodForm, self).__init__(*args, **kwargs) for count, store in enumerate(stores, start=1): method_field = ShippingCountryChoiceField( queryset=ShippingMethodCountry.objects.select_related( 'shipping_method').order_by('price').filter(shipping_method__store=store), label=pgettext_lazy('Shipping method form field label', 'Shipping method for %s' % store), required=True) if country_code: queryset = method_field.queryset method_field.queryset = queryset.unique_for_country_code(country_code) if self.initial.get('method') is None: method_field.initial = method_field.queryset.first() method_field.empty_label = None self.fields['method_%d' % count] = method_field print [q.queryset for q in self.fields.values()] ################################################### @load_checkout @validate_voucher @validate_cart @validate_is_shipping_required @validate_shipping_address @add_voucher_form def shipping_method_view(request, checkout): country_code = checkout.shipping_address.country.code stores = checkout.cart.lines.values_list('variant__product__store', flat=True) stores = Store.objects.filter(id__in=stores) print checkout.shipping_method shipping_method_form = ShippingMethodForm( country_code, request.POST or None, initial={'method': checkout.shipping_method}, stores=stores) if shipping_method_form.is_valid(): for count, store in enumerate(stores): checkout.shipping_method[store] = shipping_method_form.cleaned_data['method_%s' % count] return redirect('checkout:summary') print [q.queryset for q in shipping_method_form.fields.values()] return TemplateResponse(request, … -
how to add image in a django project
I want to add background image and change background color in my django project which is a recommendation system.I am having problem with the syntax.Can you please help. here's my code for base.html: {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% block bootstrap3_content %} <div class="container"> <nav class="navbar navbar-inverse"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'reviews:review_list' %}">Winerama</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'reviews:wine_list' %}">Wine list</a></li> <li><a href="{% url 'reviews:review_list' %}"> <span class="glyphicon glyphicon-home"></span> Home</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'reviews:user_review_list' user.username %}"> <span class="glyphicon glyphicon-user"></span> Hello{{ user.username }}</a></li> <li><a href="{% url 'reviews:user_recommendation_list' %}"> <span class="glyphicon glyphicon-glass"></span> Wine suggestions</a></li> <li><a href="{% url 'auth:logout' %}"> <span class="glyphicon glyphicon-log-out"></span> Logout</a></li> {% else %} <li><a href="{% url 'auth:login' %}"> <span class="glyphicon glyphicon-log-in"></span> Login</a></li> <li><a href="/accounts/register"> <span class="glyphicon glyphicon-user"></span>Register</a></li> {% endif %} </ul> </div> </nav> <h1>{% block title %}(no title){% endblock %}</h1> {% bootstrap_messages %} {% block content %}(no content){% endblock %} </div> {% endblock %} and here's the code for review_list.html: {% extends 'base.html' %} {% block title %} <h2>Latest reviews</h2> {% load static %} {% endblock %} {% block content %} {% if latest_review_list %} <div class="row"> … -
Django M2M field unit-tests not failing
I have a model Notification class Notification: reports = ManytoManyField() On my code I had this line: Notification.objects.create(reports=reports_list) The above throws a database constraint violation when run (relating to report fk), although, when executing the same code with unittests, there is no error. I even assert the result and it passes, e.g: notification = Notification.objects.create(reports=reports_list) ... notification.refresh_from_db() self.assertEqual(notification.reports.count(), 10) Is this the expected behaviour on this scenario ? -
Django with Postgresql on Heroku - Could not translate host name "db" to address: Name or service not known
I deployed on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. When I open app I get error: 2017-07-11T12:13:03.823882+00:00 app[web.1]: connection = Database.connect(**conn_params) 2017-07-11T12:13:03.823882+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect 2017-07-11T12:13:03.823883+00:00 app[web.1]: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) 2017-07-11T12:13:03.823884+00:00 app[web.1]: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Locally everything works properly. Maybe there is a problem with my database migration? Any suggestions? Procfile: web: sh -c 'cd PROJECT/backend/project && gunicorn project.wsgi --log-file -' due to my structure of files like in [this case][1]. I have quite similar situation in my project tree. Anyone can show me how my Procfile should look like? Project tree: DockerProject ├── Dockerfile ├── Procfile ├── init.sql ├── requirements.txt ├── docker-compose.yml └── PROJECT ├── frontend └── backend └── project ├── prices ├── manage.py └── project └── all project files Frontend's Dockerfile: # Create image based on the official Node 6 image from dockerhub FROM node:6 # Create a directory where our app will be placed RUN mkdir -p /usr/src/app # Change directory so that our commands run inside this new directory WORKDIR /usr/src/app # … -
Apache serving Django and Angular
I have a project with Angular frontend served by a Django Rest API. My project is in the following structure. example.com |- client (holds angular files) |- server (holds Django Rest Framework files) The angular app makes calls to drf through http: example.com/api/<params> I'm hosting on a Linode Ubunutu 17.04, using Apache and uWSGI. I can't seem to figure out the best way to serve both Angular and Django at the same time? I can easily host the Django Rest API with the WSGI config, but can't figure out how Apache knows to point to Angular for normal requests. What's wrong with the below solution or is there a better way? In /etc/apache2/sites-available/example.com <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/client/ </VirtualHost> <VirtualHost *:80> ServerName example.com/api ServerAlias www.example.com/api WSGIScriptAlias / var/www/example.com/index.wsgi DocumentRoot /var/www/example.com/server/ </VirtualHost> Any help would be greatly appreciated! -
Django - How to handle on the fly checkbox
I'm quite new to django, and i'm pretty much stuck on this problem. I'm creating a website who can handle lists of objects. Every detailview of a single object display all the list available for the customer (every list created by him or the other people working in the same company), checked if the object is in this list, unchecked if not. My problem is the following : I want that when the user press the submit button, my DB to be updated. If there is no change on the box, nothing happen on the DB If there is a change, of course, the DB is updated. But only on the items who's "state" as changed Here's my template: <form action="{% url 'forms:add-list' artpiece.id %}" method="post"> {% csrf_token %} {% for foo in list %} <input type="checkbox" name="listform" value="{{ foo.id }}" {% if artpiece.pk in foo.art_inlist %} checked {% endif %}> {{ foo }}<br> {% endfor %} <input type="submit"> </form> And my models : class ArtList(models.Model): name = models.CharField(max_length=250, blank=False) creator = models.ManyToManyField(User) art_ids = models.ManyToManyField(ArtPiece, related_name='artid') def __str__(self): return self.name def art_inlist(self): return self.art_ids.values_list('pk', flat=True) Is something like looping into every list and checking for the ID is present … -
How to respond to django.test.Client using the test database
I have a django settings.py file with one configured database, leading to two mysql databases, let's call them dbname and test_dbname. When running a command like python manage.py test ..., an object selection like MyClass.objects.all() will select the objects from test_dbname, so far so good. On the other hand, if I test the generation of an html page using client = django.test.Client() response = client.post(...) then the test code (or thread, I'm not sure) that creates the client object and the post arguments uses test_dbname whereas the thread that serves the post request and generates the response uses dbname (no test_ prepended). This is an inconvenience, because: My test code can't correctly formulate requests (i.e. post data) if such requests should depend on the server thread's database, leading to problems like How to test a Django form with a ModelChoiceField using test client and post method There are now TWO databases under test, whereas the contents of only one of them seems to be controllable from my test code, which makes the tests unpredictable. Can I make the server thread use a database that I can control from the test case thread? -
Django/Python : Sort python's dictionnaries with the equals key
I am currently tring to sort two Python dictionaries into an HTML array such as: #Headers DictA = {'value': 'valeur', 'name': 'nom' } #Data DictB = {'value': '456', 'name': 'Test' } I wanted to sort these two dictionaries in order to get the '456' in DictB equals to the key 'value' in DictA. Note: I used other dictionaries than DictA and DictB, it was just an example. But it fits my problem. In my views.py, I define my two dictionaries such as: headers = json.loads(entries[0].form_data_headers) data = json.loads(entries[1].saved_data) valuesData = data.values() then I pass them into the template.html via the context: context = {'entries': entries, 'form_entry_id': form_entry_id, 'headers': headers, 'data': data, 'valuesData': valuesData} Thus, in my template, it will print an array with the headers (DictA) and the datas (DictB). In my template I make this code: <thead> <!-- Test pr voir si les values sont pris en compte ou non --> <p>{{valuesData}}</p> <tr> {% for entry in headers %} <td> {{ entry }} </td> {% endfor %} </tr> </thead> And the datas are in another for loop: <tbody> <thead> <!-- Test pr voir si les values sont pris en compte ou non --> <p>{{valuesData}}</p> <tr> {% for entry in … -
Django "Violation of PRIMARY KEY constraint" however the primary key is BigAutoField
I have defined a table named ReadUnit. class ReadUnits(models.Model): ReadID = models.BigAutoField(primary_key=True, unique=True, null=False) ReadDate = models.DateField(null=False) The settings.py has the following setting for accessing the database: DATABASES = { 'default': { 'NAME': 'MyProjectDB', 'ENGINE': 'sqlserver_ado', 'HOST': '127.0.0.1', 'USER': 'sa', 'PASSWORD': 'pass', 'OPTIONS': { 'provider': 'SQLOLEDB' }, } } The project was working perfect for several months. Between 30~40 records was added to the table everyday. Recently, I was sometimes facing with a 'Violation of PRIMARY KEY constraint' Error. The code that inserts record to this table is very simple: ReadUnits(ReadDate=str(datetime.datetime.now().strftime("%Y-%m-%d"))).save() Nowadays it becomes awesome because every time this code runs, the error happens. So there isn't any record saved in DB for these days at all. -
get_query_set(self) is not being called in django
I am implementing search function using TemplateView in Django the class is class part_search_view(TemplateView): model = part_list context_object_name = 'part_list' template_name = 'part_list.html' def get_context_data(self, **kwargs): context = super(part_search_view, self).get_context_data(**kwargs) context['my_list'] = populate_nav_bar() return context def get_queryset(self): key = self.request.GET['search_text'] partlist = part_list.objects.filter(Q(part_id__icontains=key) | Q(part_name__icontains=key)) return partlist part_list.html {% for part in part_list %} <a href="{% url 'parts:part_detail' part.id %}" class="list-group-item">{{ part.part_id }} - {{ part.part_name }}</a> <a href="{% url 'parts:part_update_view' part.id %}" > Edit </a> {% endfor %} the url mapping is url(r'^search/',views.part_search_view.as_view(),name='part_search_view'), the form for serch button <form action="{% url 'parts:part_search_view'%}" role="form" class="navbar-form navbar-left" method="get" > {% csrf_token %} <div class="form-group "> <input class="form-control mr-sm-2" type="text" placeholder="Search" name="search_text"> <button class="form-control search_buton btn btn-success " type="submit" >Search</button> </div> </form> after the search button is pressed the address is http://127.0.0.1:8000/parts/search/?csrfmiddlewaretoken=PWjEw1hRsyH9B6YcseVuhS0urX8L7f170q9ucLF9hTPQPThulpgMSP4y5xhScCVr&search_text=mp6 but the get_query_set(self) is not called here the get_context_data(...) is called though, why? -
How to sort serialized fields with Django Rest Framework
I'm looking for suggestions on how to sort/group serialized fields by value. Here's a code example explaining what I wanto achieve. Models class Folder(models.Model): name = models.CharField() class File(models.Model): filetype = models.CharField() name = models.CharField() folder = models.ForeignKey(Folder) Serializers class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ('id', 'filetype', 'name') class FolderSerializer(serializers.ModelSerializer): files = FileSerializer(read_only=True) class Meta: model = Folder fields = ('name', 'files') This serializes to: { "name": "Test Folder", "files": [ {"id": 1, "filetype": "pdf", "name": "some pdf file"}. {"id": 2, "filetype": "pdf", "name": "some other pdf file"}, {"id": 3, "filetype": "txt", "name": "some text file"} ] } I'm looking for a way to serialize to this: { "name": "Test Folder", "files": [ "pdf": [ {"id": 1, "name": "some pdf file"}, {"id": 2, "name": "some other pdf file"} ], "txt": [ {"id": 3, "name": "some text file"} ] ] } -
SSL Certificate Privacy error with Django App
I have build a django website , and I've also did the encryption with letsencrypt , and after that , I get a privacy error , when I am trying to access my website:"NET::ERR_CERT_AUTHORITY_INVALID".That error comes only when I type "www.msadwaadsawd.org" ( I mean those www. ) . If I type https://msadwaadsawd.org , I don't have any error and everything works fine. What should I do? It would help me so much an answer! Have a nice day.Also msadwaadsawd.org it's an example , not my real site haha -
Python django - list index out of range
Last time I moved a django website to new server. I installed all packages in pip, everything is working but when I go to insert page in django admin I have issue http://dpaste.com/11AR90Q At older server everything is working fine but on new server there's a crash. The database is the same for both servers. -
My django form fields are not showing up in template
forms.py class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = {'title', 'url', 'description'} widgets = { 'url':forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg', 'jpeg'] #The two below codes do exactly the same thing but partition is faster extention = url.rpartition('.')[2].lower() #extension = url.rsplit('.',1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('The given URL does not match valid image extensions') return url def save(self, force_insert=False,force_update=False,commit=True): image = super(ImageCreateForm, self).save(commit=False) image_url = self.cleaned_data['url'] image_name = '{}.{}'.format(slugify(image.title), image_url.rpartition('.')[2].lower()) #download image from the given URL response = request.urlopen(image_url) image.image.save(image_name,ContentFile(response.read()),save=False) if commit: image.save() return image The image appears alright but the fields are not showing index.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %}Bookmark an image{% endblock %} {% block content %} <h1>Bookmark an image</h1> <img src="{{ request.GET.url }}" class="image-preview"> <form action="." method="post"> {{ forms.as_p }} {% csrf_token %} <input type="submit" value= 'Bookmark it!'> </form> {% endblock %} -
Gunicorn: why HTTP GET request contained path to gunicorn's UNIX socket
I deployed my django application using nginx and gunicorn over a month ago. Today I received email with error notification from this application. Apparently, some GET request contained absolute file path to gunicorn's UNIX socket used by nginx upstream: Invalid HTTP_HOST header: u'/path/to/gunicorn/socket/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. Report at / Invalid HTTP_HOST header: u'/path/to/gunicorn/socket/gunicorn.sock:'. The domain name provided is not valid according to RFC 1034/1035. Request Method: GET Request URL: https:///path/to/gunicorn/socket/gunicorn.sock:/ What's going on? Is my application compromised? Gunicorn version is 19.7.1, django version is 1.9. -
Django 1.11 send file form (not required)
Problem in sending a message that contains a file. At the moment when you attach a file, the letter comes to the mail with an attachment. It would seem all right if the field is required, but if the field is not mandatory and does not select the file to be sent, the letter does not come to the mail. Who will tell me how to solve this problem? Views: if request.method == 'POST': file_form = FileForm(request.POST, request.FILES) if file_form.is_valid(): f_name = file_form.cleaned_data['f_name'] f_mail = file_form.cleaned_data['f_mail'] f_message = file_form.cleaned_data['f_message'] f_news = file_form.cleaned_data['f_news'] f_file = request.FILES['f_file'] news = '' if f_news: news = 'Посетитель дал согласие на получение новостей' d = {'f_name': f_name, 'f_mail': f_mail, 'news': news, 'f_message': f_message} htmly = get_template('mail/file.html').render(d) plaintext = get_template('mail/file.txt').render(d) from_email = 'dolgoletie.plastic@yandex.ru' to_email = [from_email, ] subject = 'Страничная форма c файлом' html_content = htmly text_content = plaintext try: mail = EmailMultiAlternatives(subject, text_content, from_email, to_email) mail.attach_alternative(html_content, "text/html") mail.attach(f_file.name, f_file.read(), f_file.content_type) mail.send() except: return HttpResponse('Invalid mail send!') return HttpResponseRedirect('/') else: file_form = FileForm() ModelForm: class FileForm(forms.Form): f_name = forms.CharField(required=True, max_length=50) f_mail = forms.EmailField(required=True) f_message = forms.CharField(required=True, max_length=500) f_file = forms.FileField(widget=forms.FileInput) f_news = forms.BooleanField(required=False) Html Form: <form class="form_question" role="form" method="post" action=" " {% if file_form.is_multipart %}enctype="multipart/form-data"{% endif … -
Django redirect from one page to another
I am trying to split up my registration based user choice i.e, faculty and student. In basic registration page I intend to capture email, designation (radio button) and password. On clicking Next, respective detailed registration pages would be available based on users designation type. However, on clicking next the FacultyRegistrationForm/ StudentRegistrationForm form is not displayed. My View: def registerView(request): title = "Registration" initial_designation = {'designation': request.session.get('designation', None)} initial_email = {'designation': request.session.get('email', None)} form = FirstRegistrationForm(request.POST or None, request.FILES or None) if form.is_valid(): request.session['designation'] = form.cleaned_data['designation'] .... .... if 'Faculty' in request.session: return HttpResponseRedirect('facultyRegistration') elif 'Student' in request.session: return redirect('studentRegistration') else: form = FirstRegistrationForm() return render(request, 'account/registerForm.html', {'form': form, 'title': title}) def facultyregisterView(request): title = "Registration" form = FacultyRegistrationForm(request.POST or None, request.FILES or None) if form.is_valid(): designation = request.session['designation'] user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate Your PubNet Account' message = render_to_string('account/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') else: form = UserRegistrationForm() return render(request, 'account/registerForm.html', {'form': form, 'title': title}) My urls.py: urlpatterns = [ url(r'^register/$', registerView, name="registerView"), url(r'^register/facultyRegistration/$', facultyregisterView, name="facultyregisterView"), url(r'^register/studentRegistration/$', studentregisterView, name="studentregisterView"), ] My template: {% extends "index.html" %} {% load crispy_forms_tags %} {% block content … -
Serialize related models and override the create method
I am new to DRF and I want to do something similar to the formsets in django forms I have an Invoice And Products models related to each other throw a many to many InvoiceDetail model.. when I create an Invoice I choose some products and create a InvoiceDetail object for each .. I want to do this in DRF how can I serialize the Invoice model and it's create function then? or should i do it form the view? models.py: class Invoices(models.Model): #some fields products = models.ManyToManyField('Products', through='InvoiceDetail') class Products(models.Model): #some fields class InvoiceDetail(models.Model): invoice = models.ForeignKey(Invoices, related_name='parent_invoice') product = models.ForeignKey(Products, related_name='parent_product') product_description = models.TextField() product_price = models.DecimalField(max_digits=9, decimal_places=2) quantity_sold = models.IntegerField() serializers.py: class ProductsSerializer(serializers.ModelSerializer): class Meta: model = Products fields = ('barcode', 'product_code', 'name', 'description', 'category', 'quantity_in_stock', 'quantity_on_hold', 'expire_date', 'vendor', 'manufacturer', 'discount') class InvoiceDetailsSerializer(serializers.ModelSerializer): class Meta: model = InvoiceDetail fields = '__all__' view.py: class ProductsView(viewsets.ReadOnlyModelViewSet): queryset = Products.objects serializer_class = ProductsSerializer class InvoicesView(viewsets.ModelViewSet): queryset = Invoices.objects serializer_class = InvoicesSerializer class InvoiceDetailView(viewsets.ModelViewSet): queryset = InvoiceDetail.objects serializer_class = InvoiceDetailsSerializer -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x02BA8660>
When I try to run the server this error occurs. I have included my app to "INSTALLED APPS" and migrated model. Can anyone tell how to solve it -
ENOTFOUND: getaddrinfo ENOTFOUND rendezvous.runtime.heroku.com after heroku run python manage.py migrate
Has anyone got this error: ENOTFOUND: getaddrinfo ENOTFOUND rendezvous.runtime.heroku.com rendezvous.runtime.heroku.com:5000 while running heroku run python manage.py migrate ? Any thoughts on how this can be fixed? -
Use a javascript array to display specific HTML divs
Using django I have a HTML page with a table containing checkboxes: {% for o in obj %} <input class='germ_ids' name='{{o.id> {% endfor %} <script> var elements = document.getElementsByClassName("germ_ids"); var ids = []; for(var i=0; i<elements.length; i++) { ids.push(elements[i].name); } </script> This has given me an array of specific 'germ ids'. These relate to other django objects I have: the same .html page: {% for k, v in add_state_dict.items %} <div class='{{k.id}}_statement'> <p>{{v}}</p> </div> {% endfor %} <div class='all_germ'> <p>{{additional_statement}}</p> </div> What I want to achieve is a statement for each germ_id when their checkbox is checked. However when more than one boxes are checked, it makes a concat statement called additional_statement in the 'all_germ' class. I have hard coded it in in a JSFiddle http://jsfiddle.net/sDsCM/1037/ However I want to use the elements in the array to do this to account for different array values.