Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku django program deployed,but returned a 400 error
The thing is,I wrote a very simple django blog.And I put it on Github.Then I tried to deploy it on Heroku.When I finished it,I only saw 400 Bad Request.I'm confused.The log is here: 2018-03-13T11:56:51.929117+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=guoguoblog.herokuapp.com request_id=85b467df-9cd5-4bae-8cd8-e33a9c89d1a9 fwd="112.9.115.29" dyno=web.1 connect=1ms service=20ms status=400 bytes=154 protocol=https 2018-03-13T11:56:51.928540+00:00 app[web.1]: [13/Mar/2018 19:56:51] "GET /favicon.ico HTTP/1.1" 400 26 And repeat again when I flush my page. What can I do? Oh,this is my github project.https://github.com/qwedc001/DjangoBlog Can anybody help me? Eric -
building big xml file with python 2
im trying to get the best performance to build a big XML file in python 2/django. the XML file produced have ~500mb and the 1st approach used was with lxml. took over 3H30. then i tested with xml.sax and took over the same time, 3h30. im trying to find the fastest way and with less memory consumption. i searched over several days and the best ways i found were these two, but then i found that lxml have xml.sax implementation aswell. any ideas to help? thanks! -
What is the best way to manage permissions for user and multiple admin for object instances for a web application
I am looking for best way for my web application. It has many admin and users. the workflow is like there is super admin who create account for company admin (this can be many or one). the company admin can have many end user's who access departments of that company. the company admin set or remove permission for end user like user1 can access dept but not dept2. So what would be the best structure/design to build this system. (I am going to use django for this) -
Bootstrap modal dialog dismiss not working but submit button
I have a problem which I seam to find no answer to. I have modal which contains a form for submitting data to the server. The submitting part is working just fine. All data gets send and the server takes the correct steps. However, the buttons to close/dismiss the modal do not work. The form gets pulled by ajax request from the server and is embedded in the current page <!-- Dialog for user input of forms--> <div id="form-modal" class="modal fade" role="dialog"> </div> Ajax pulled form <div class="modal-dialog" role="document"> <!-- Content of dialog --> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Datensatz erstellen</h4> <button type="button" class="close" data-dismiss="modal">&times </button> </div> <div class="modal-body"> <form action="{% url 'knowledgeedit' %}" method="POST" id=""> {% csrf_token %} {% for field in form %} <div id="{{ field.auto_id }}_container"> {{ field.help_text }} <div> {{ field.label_tag }} {{ field }} </div> {% endfor %} </div> </form> <div class="modal-footer"> <button class="btn btn-success" type="submit" name="{{ requestedForm }}">Speichern</button> <button class="btn btn-default" type="button" data-dismiss="modal">Abbrechen</button> </div> </div> </div> </div> css: body { font-family: 'Open Sans', serif; padding-top: 54px; color: #868e96; } .btn-primary{ background-color: #bd5d38 !important; border-color: #868e96 !important; } /* Sections */ @media (min-width:992px) { body { padding-top: 0; padding-left: 17rem; } }h1, h2,h3,h4, h5, h6 … -
Filtered records in django template
I am building a races app, where in a webpage I want to display records from the db, grouped based on the year a race took place and on the type of the race, so as to calculate some stats. Which is the best way to pass these groups of records in the template and build the methods for the calculation of the stats? a) Passing a dictionary through views? b) Applying a custom filter? c) Applying a simple tag? d) Building a custom Manager? e) Building the stats methods in models.py, and if so, how can I apply the group filters? f) any other way? Please, provide a working example if possible. -
How to iterate ElasticSearch data in Python/Django?
I have ElasticSearch iterated data like this: (Pdb) data[0] {'_index': 'publishserdata-index', '_type': 'publishser_data_index', '_id': '35', '_score': 1.0, '_source': {'publisher': 'Admin', 'department': 'IT', 'subdepartment': 'Full Stack Developer', 'inventory_ID': 'IT003', 'title': 'Why Should I Use Celery?', }} I want get publisher,department,title data. I tried data[0]._source try to user dict data[0].__dict__ but it's showing error. -
saving form - many to many relationship
I am trying to save form based data in many to many relationship. My models is as follow: class Student(models.Model): stuName = models.CharField(max_length=100) stuCity = models.CharField(max_length=100) stuPhone = models.IntegerField(max_length=10) stuNationality = models.CharField(max_length=50) stuCreatedt = models.DateTimeField(default=timezone.now) def __str__(self): return '%s %s %s' % (self.stuName,self.stuCity,self.stuNationality) class Dept(models.Model): deptId = models.AutoField(primary_key=True) deptName = models.CharField(max_length=100) def __str__(self): return '%s %s' % (self.deptId, self.deptName) class Course(models.Model): courseId = models.AutoField(primary_key=True) courseName = models.CharField(max_length=100) enrolledStu = models.IntegerField(max_length=3) students = models.ManyToManyField(Student) dept = models.ForeignKey(Dept, on_delete=models.CASCADE) def __str__(self): return '%s %s %s %s' % (self.courseName,self.enrolledStu,self.students,self.dept) which i am trying to save. my view is def addStudent(request): if request.method == "POST": form = CourseForm(request.POST) if form.is_valid(): print(form.cleaned_data) course = form.save(commit=False) course.courseName = request.courseName course.save() form.save_m2m() return redirect('lstDetail') i tried without form.save_m2m() method but still its giving error. AttributeError at /stuApp/new/ 'WSGIRequest' object has no attribute 'courseName' Request Method: POST Request URL: http://127.0.0.1:8000/stuApp/new/ Django Version: 1.11.10 Exception Type: AttributeError Exception Value: WSGIRequest' object has no attribute 'courseName Exception Location: C:\Users\PycharmProjects\learning\stuApp\views.py in addStudent, line 22 Python Executable: C:\Users\PycharmProjects\learning\venv\Scripts\python.exe Python Version: 3.6.4 this is from html page. on console there isn't any error its just prints the query. basically i am unable to save data with many to many fields and relationship. my … -
Django save previous object from models
In a Django admin site, I have this class. I want to save a previous version of a object (Servers) which is a manytomany field to find changes on the object. With normal CharField this work, but for manytomany fields I got this error: "<SourceDestinationGroup: asdas>" needs to have a value for field "id" before this many-to-many relationship can be used. here is my objectclass class SourceDestinationGroup(models.Model): STATE_CHOICES = ( ('C', 'in Change'), ('F', 'Finished') ) ServerGroupName = models.CharField(max_length=256) Description = models.CharField(max_length=256,blank=True) Servers = models.ManyToManyField(Server) Status = models.CharField(max_length=1, choices=STATE_CHOICES, default='C') def __init__(self, *args, **kw): super(SourceDestinationGroup, self).__init__(*args, **kw) self._old_Servers = self.Servers def save(self, **kw): if self.Servers != self._old_Servers: self.Status = 'C' self._old_Servers = self.Servers super(SourceDestinationGroup, self).save(**kw) def __str__(self): return self.ServerGroupName -
Django forms validation is not showing up in the template
My problem is, when I validate forms for errors, some text with warning would show up, But id does not. I was searching for 2 days for some good answers and i tried also everything, so I thing that is some really silly mistake. Can anyone help me with this problem? I was trying to implement validation in my register subpage so.... First image is my model.py for registration Second image is my inputForms.py with simple validation Third image is my view.py And fourth is my template.html for registration Someone please help me with this mistake. Thank you very much. -
how to dispatch a specific method with csrf_exempt in django class based view
Hello i am trying to set csrf_exempt on class based view in django i've tried this one now my class is look like this: class UserView(View): # Check csrf here def get(self, request, pk): #code here # I want to exempt csrf checking only on this method def post(self, request): #code here Meanwhile if I use @method_decorator(csrf_exempt, name='dispatch') it will applied to every methods in the class. What's the best approach to exempt only for specific method in a class based view in Django? -
Django celery for download large file
I am developing a django app and my app need to user to upload the urls in excel files. On server side i am reading the excel file by each cells, extracting the news article of the urls and generating the summary of article. This process can take up to 5-10 minutes for the long list of urls. I am using celery for managing the long running task but somehow server is giving me error 500 - Internal server error after 2 min without completing the task __init__.py from .celery import app as celery_app __all__ = ['celery_app'] Setting.py BROKER_URL = 'django://' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' celery_app.py from __future__ import absolute_import import os import django from celery import Celery from django.conf import settings from kombu import serialization serialization.registry._decoders.pop("application/x-python-serialize") os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'news.settings') django.setup() app = Celery('news') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) summary.py from celery import shared_task @shared_task def WritesummaryfromArticleToExcel(input_file,noofline,lang): try: data=False wb = xlrd.open_workbook(file_contents=input_file.read()) wb_sheet=wb.sheet_by_index(0) df=pd.DataFrame(columns=['Full Article','Summary']) for rownum in range(0, wb_sheet.nrows): # for colnum in range(0,1): try: rw=wb_sheet.cell_value(rownum,0) if type(rw)==float or type(rw)==int: rw= str(rw) # if len(rw)>15000: data=True articletext=rw # nooflines=request.data["numberofline"] lantext="" lantexttemp= articletext.split('\n')[0:2] for l in lantexttemp: lantext=lantext +"\n" +l lan=detect(lantext) view.py def translatedoc(request): data="" convrowstr="" if request.method=='POST': … -
djang template loop for with ajax script multiply
I've been following with "Django by example' practice book doing like unlike system. I encountered some problem with Ajax script when I a nested then into an loop for ( "for post in posts iterating view"). When I put into my template’s loop, this ajax I get looping likes in all iterated post. Do You have any tips how can I tackle with this ? enter code here <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.each(document).ready(function(){ $('a.like').click(function(e){ e.preventDefault(); $.post('{% url "like" %}', { id: $(this).data('id'), action: $(this).data('action') }, function(data){ if (data['status'] == 'ok') { var previous_action = $('a.like').data('action'); // toggle data-action $('a.like').data('action', previous_action == 'like' ? 'unlike' : 'like'); // toggle link text $('a.like').text(previous_action == 'like' ? 'Unlike' : 'Like'); // update total likes var previous_likes = parseInt($('span.count .total'). text()); $('span.count .total').text(previous_action == 'like' ? previous_likes + 1 : previous_likes - 1); } } ); }); }); </script> enter code here {% for post in posts %} <small>Posts: {{ post.message}}</small> {% include 'posts/like.html' %} {% endfor%} -
Access the Django-Rest-Framework url do not load the styles file
I have a project with the settings.py: # -*- coding: utf-8 -*- """ Django settings for Qiyun02 project. Generated by 'django-admin startproject' using Django 1.11.5. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os import sys #import django.contrib.auth.middleware # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PARENT_DIR = os.path.abspath(os.path.join(BASE_DIR, os.pardir)) # 增加sys目录 sys.path.insert(0, BASE_DIR) sys.path.insert(0, os.path.join(PARENT_DIR,'旗云管理员后台')) sys.path.insert(0, os.path.join(PARENT_DIR,'用户前台')) sys.path.insert(0, os.path.join(PARENT_DIR,'用户管理后台')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'u8ctyimjuy7t-7r3%$&4sc2g^5fhc8dathp8z&(7pp=&eee@zn' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'rest_framework_docs', # API文档 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', ...... ] SITE_ID = 1 # email backend TODO 这个,每个商户可以自己定义邮箱 EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' #EMAIL_USE_TLS = True EMAIL_USE_SSL = True EMAIL_HOST = 'smtp.gmail.com' # QQ:smtp.qq.com 163:smtp.163.com EMAIL_PORT = 465 EMAIL_HOST_USER = 'qiyunserver@gmail.com' EMAIL_HOST_PASSWORD = 'qiyunserver123' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER # TODO 方便调试,关闭Token验证 REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES':[], #'rest_framework.permissions.IsAuthenticated' 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), #['rest_framework.authentication.TokenAuthentication'], # 'rest_framework.authentication.TokenAuthentication' #'DEFAULT_PAGINATION_CLASS': ('rest_framework.pagination.PageNumberPagination',), 不能打开这个 #'PAGE_SIZE':10, … -
payment via PayPal payout API
I am using Payout API (in Django) for PayPal mass payments . How can i make all these payments as "PERSONAL" from api . Code snippet of PayPal object that i am using : payout = Payout({ "sender_batch_header": { "sender_batch_id": batch_id, "email_subject": mail['subject'] }, "items": [ { "recipient_type": "EMAIL", "amount": { "value": amount, "currency": "USD" }, "receiver": receiver_email, "note": mail['body'] "sender_item_id": id } ] }) Reference : https://developer.paypal.com/docs/api/payments.payouts-batch/#payouts . Is there any Key value that needs to be sent with the above object or is there any different approach for PERSONAL payment from PayPal API. -
None type error in Django rest RegisterView
I am using Django RestFramework's RegisterView for the registration api in my project.I use a custom adapter as well, it is as follows. class CustomAccountAdapter(DefaultAccountAdapter): """ Override all_auth's default adapter """ def send_confirmation_mail(self, request, emailconfirmation, signup): # current_site = get_current_site(request) promo_code = emailconfirmation.email_address.user.promo_code activate_url = "%s/#/verifyEmail/%s/" % ( settings.FRONTEND_HOSTNAME, emailconfirmation.key ) if promo_code: activate_url = "%s/#/verifyEmail/%s/?promo_code=%s" % ( settings.FRONTEND_HOSTNAME, emailconfirmation.key, promo_code ) ctx = { "user": emailconfirmation.email_address.user, "activate_url": activate_url, "current_site": settings.FRONTEND_HOSTNAME } if signup: email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' self.send_mail(email_template, emailconfirmation.email_address.email, ctx) I get an error while the sending the confirmation mail to the newly registered user.The error is below File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/message.py", line 283, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 99, in send_messages sent = self._send(message) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 110, in _send from_email = sanitize_address(email_message.from_email, email_message.encoding) File "/home/ubuntu/fizprod_env/local/lib/python2.7/site-packages/django/core/mail/message.py", line 105, in sanitize_address nm, addr = addr TypeError: 'NoneType' object is not iterable Can anyone tell me what is the error and how it's happening.I use Django 1.7, python 2.7, Django REST 3.1.1 -
Is it possible to add a custom attribute to a model field?
Here's my model: def Post(models.Model): ... video = models.BooleanField(default=False, youtube=False) is it possible to add the youtube attribute so I can use it in my template like so: {% if video.youtube %} <p>text</p> {% endif %} -
Django: raw passwords via request.POST
This question concerns the standard UserCreationForm within Django, and the way that passwords are stored, extracted and used through a request object. Specifically the fact that I seem to be able to print raw passwords through print(request.POST). File contents will be provided at the end of this post. I have created a registration page. I have set up a very basic class-based view that authenticates and logs the newly created user in. The actual HTML of that page is rendered automatically in this case, through {{ form.as_p }} where form is an instance of UserCreationForm. How come, when I execute print(request.POST), I get something along the lines of this returned: <QueryDict: {'csrfmiddlewaretoken': ['keeping_this_private'], 'username': ['William'], 'password1': ['ACTUALPASSWORD'], 'password2': ['ACTUALPASSWORD'], 'button': ['']}> Is this really secure? As I have only been programming for a couple of months, I am still learning. Views.py: class RegisterView(View): def get(self, request): form = UserCreationForm() return render(request, 'authentication/registration.html', {'form': form}) def post(self, request): form = UserCreationForm(request.POST) if form.is_valid(): print(request.POST) form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: return render(request, 'authentication/registration.html', {'form': form}) Registration.html {% extends 'base.html' %} {% block body %} <body class="text-center"> <form method="post"> {% csrf_token %} … -
Django 2.0 + Postgres heroku migrations
I am trying to run a Django application with Postgres in Heroku. I have created an app for the application but the problem is that the app migrations are not being applied in Heroku. I am using the heroku starter base template and have committed the necessary migration files. When I run heroku run python manage.py migrate, the first set of migrations apply: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK blah blah blah But when I run it the second time it gives me the the output Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. If I specify the app using heroku run python manage.py migrate phone I get the error CommandError: No migrations present for: phone In my local development, I have an app called phone that I have added to the settings.py and can run local migrations. -
How to integrate Django into an existing database without using models
I have been asked to provide a web interface to access some scientific data which is being saved in a laboratory. The data are stored in folders, each containing some number of FITS files, and the application collecting the data is already written and functional. The web interface I am supposed to implement should have the following features: View all the data taken so far; Allow the user to make queries; File downloading; Only read-only operations are allowed. I know Django quite well and would like to use it. However, this kind of application is quite different from what I am used to. Usually a Django application implements models which are linked to a database, and this database is completely managed by Django itself. In this case, the database would be the plain tree of folders, which is being modified by an external application while Django is running. Can Django be adapted to this task, or should I turn to other more low-level solutions? (e.g., microframeworks like Flask) -
In what sequence Model.save() and ModelForm.save() called
I understand that both models.Model and forms.ModelForm both contain .save() method that you can override. My question is how and when are they used to save an object and in what sequence. -
Django: why Using a custom user model when starting a project is not made compulsory?
I was working on a project and after the mid way, i wanted to work on the users. That time i decided to use email as the login. I found that custom user migration should be done only in the start of the project. Using a custom user model when starting a project If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you. This model behaves identically to the default user model, but you’ll be able to customize it in the future if the need arises: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project So why such a thing should not be made as compulsory thing before one starts a project. Assuming I am in the middle of a project. How can i transfer all the database data to my new project with custom_user. -
Redirect user from login page
When the user presses on login, nothing happens. I would like to redirect them to calculator.html where i intend to make some entry fields to obtain parameters from the user to calculate a certain value at the end. Django 1.11.11 Python 3.6.4 Thanks. urls.py from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('webapp.urls')), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.decorators import login_required # Create your views here. def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): # log the user in user = form.get_user() login(request, user) return redirect('/calculator/') else: form = AuthenticationForm() return render(request, 'registration/login.html', { 'form': form }) @login_required(login_url="/login/") def calculator(request): return render(request, 'webapp/calculator.html') app urls.py from django.conf.urls import url from . import views from django.contrib.auth.views import login from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf.urls.static import static from django.conf import settings from django.views.generic.base import RedirectView urlpatterns = [ url(r'^login/$', views.login_view, name='login'), url(r'^calculator/$', views.calculator, name='calculator'), url(r'^.*$', RedirectView.as_view(pattern_name='login', permanent=False)), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) login.html {% extends 'webapp/base_layout.html' %} {% block content %} <h1>Log in</h1> <p></p> <p></p> <form class="site-form" action="/registration/login" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Login" /> </form> {% endblock … -
checking celery task queue on local running django heroku application
I am running a django app. I use redis as a broker for celery. I boot redis separately with redis-server /usr/local/etc/redis.conf Once redis has started, I run my Django code in the CLI of heroku heroku local I have tasks that I can process, the set-up works I would like to monitor the tasks from the "bash"/"Shell"/"console" to see which tasks are running. I have some scheduled tasks but no idea if they eventually get scheduled or not. probably this is some kind of one-liner but I have no clue where to start looking for it. What i have tried: reading heroku documentation on the shell and running heroku locally I have tried to run a separate python shell inside the virtualenv where I run the django app I also tried accessing tasks from a separate shell but that didn't worked out either thanks for the help! -
How to get an image from HttpRequest in Django without using HTML form?
I picked up Django just a few days ago, so I only have a very limited knowledge of how it works, and I can't figure out how to get file a POST. All tutorials, SO questions, etc. focus on images being uploaded from HTML forms, then saving those files, or using Django rest framework and so on, however I need none of those things. I use Postman to send an image to Django, so naturally HttpRequest.FILES dict is empty. The file is encoded in HttpRequest.body as a byte stream. In theory, I could parse that byte stream into an image, but that would require accounting for different image headers(png, jpg, gif...) and also cut out irrelevant parts of the stream, such as Content-Disposition: form-data; name=""; filename="image.png"\r\nContent-Type: image/png. which is quite annoying to work with. Is there simply no other way to access the file in the HttpRequest that would result in an actual image object, say PIL.Image? -
Heroku generates Server Error (500) in Django application
I have deployed a Django application on Heroku and attached PostgreSQL database to it successfully. On running the application I have observed that it behaves unexpectedly Sometimes it produces Server Error (500) Sometimes only half of the page is loaded Sometimes jQuery ajax call gets failed all these problems only appear on Heroku, when I run the same application on my system locally it runs smoothly without any problem. These errors are appearing only on 2 pages of my projects all other pages work fine. To overcome this problem, I followed these posts Post 1, Post 2, Post 3, Post 4 and tried changing the parameters in settings.py but nothing worked. settings.py import os #from .base import import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [".herokuapp.com", "127.0.0.1"] # Application definition INSTALLED_APPS = [ 'blog', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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', …