Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to set SCOPE of Shopify in django-allauth
I tried to configure the scopes that I want in SOCIALACCOUNT_PROVIDER under shopify -> SCOPE in my settings.py, but it doesn't work. it always gives the default that was set in it which are read_orders and read_products. SOCIALACCOUNT_PROVIDER = { 'shopify':{ 'SCOPE':[ 'read_analytics', 'read_products', 'read_script_tags' 'write_script_tags' ], 'IS_EMBEDDED': True, } } I just tried doing the SCOPE of Shopify in SOCIALACCOUNT_PROVIDER, cause that's how I see other providers do it, so I assume that was also the way to define the scopes that I wanted in shopify. the other way was adding it to the link via queryparams when I'm gonna do oauth to shopify using the django-allauth. /shopify/login/?shop=<sample-shopify-shop-name>&scope=<shopify-scope> but I think this isn't the best practice? The document in django-allauth about Shopify doesn't anything about setting the scopes that you want. -
Error when run the django project
Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I want to run this project https://github.com/adarsh2397/Online-Judge -
Django query taking too much time
I'm using django and django rest framework to make a query from all users in data that have a permission sent as a url parameter but this query is taking too long. I'm user pycharm debugger how can I try to check why is it taking to long, this is the function: @list_route(url_path='permission/(?P<permission>.+)') def read_permission(self, request, *args, **kwargs): serializer = self.get_serializer_class() qs = get_user_model().objects.filter_by_permission(self.kwargs.get('permission')) qs = qs.order_by(Lower('username')) return Response(serializer(qs, many=True).data) -
MultipleObjectsReturned - get() returned more than one ContentType -- it returned 2
everything was working fine then suddenly i got this error MultipleObjectsReturned at /rohit/post/new-post/ get() returned more than one ContentType -- it returned 2! i do not know why it returned 2 objects. it just suppose to return one and i can't figure it out. help me guys. Here's my code: models.py: class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) objects = CommentManager() class Meta: ordering = ['timestamp'] def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) def get_absolute_url(self): return reverse("comments:thread", kwargs={"id": self.id}) def get_delete_url(self): return reverse("comments:delete", kwargs={"id": self.id}) def children(self): #replies return Comment.objects.filter(parent=self) @property def is_parent(self): if self.parent is not None: return False return True Views.py: instance = get_object_or_404(Post, slug = slug) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } print(initial_data) form = CommentForm(request.POST or None, initial= initial_data) if form.is_valid() and request.user.is_authenticated(): c_type = form.cleaned_data.get("content_type") print('c_type : ',c_type) content_type = ContentType.objects.get(model=c_type) print(content_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(id=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= … -
Update model field and any other fields in django
Is it possible to update a field and when saving it, it should save other fields with new changes. For example, I have the below model, class Backup(models.Model): user=models.ForeignKey(User) title=models.CharField(max_length=200) is_approve=models.BooleanField(default=False) is_bad=models.BooleanField(default=False) country=models.CharField(max_length=100) Now, my main aim is to just make is_approve field True. My secondary aim is to update other fields alongside the is_approve field, incase the user makes changes before clicking on the approve button in template. @staff_member_required def activate_moderation(request, backup_id=None): if id: vpostmod=get_object_or_404(Backup, id=backup_id) vpostmod.is_approve =1 vpostmod.save() How can I plug in instances of all fields alongside with the save(), in order to make the changes after setting is_approve to True. -
How to handle concurrency with django queryset get method?
I'm using django (1.5 with mysql) select_for_update method for fetching data from one model and serve this data to user upon request, but when two user request at simultaneously it returns same data for both of the user, see the sample code below class AccessCode(models.Model): code = models.CharField(max_length=10) state = models.CharField(max_length=10, default='OPEN') def fetch_available_code(self): with transaction.commit_on_success(): qs = self.select_for_update().filter( state='OPEN').order_by('id') if qs: return qs[0] else: return None Please guide how to handle this scenario in better way -
How do I solve the error: error: (-27) The matrix has NULL data pointer in function cvGetMat in my opencv function?
To give some background on the problem I am trying to deploy my django project to a microsoft azure server. My django project is mainly dealing with executing opencv functions. I made sure to test that all my opencv functions worked on my local host which they do but the main problem I'm having is getting them to work on an azure server. Everytime I try to call any opencv function I get the error:The matrix has NULL data pointer in function cvGetMat in my opencv function. I have tried googling the problem and have narrowed it down to my frame variable inside my function that is causing the problem. The stack trace has pointed out that the function keeps failing at this line: cv2.imshow('frame',gray). The full function is just a basic opencv function to play a video. The code is below: def PlayVideo(request): filename="app/media/traffic.mp4" cap = cv2.VideoCapture(filename) while(cap.isOpened()): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() return render_to_response('app/Configuration.html') When I first encountered this problem I thought it may have been that it could not find the video file but I've modified the code with different paths that would not … -
Django store aggregated data in the database?
I have a use case where I have some complex functions (involving aggregations) that take a few seconds to run, and are affecting the UX of the app (even when the rows are just about 25-30k and the relevant fields are indexed). I am thinking of storing the aggregations in the database itself (and run them nightly) since real-time-liness of the data is not very important here. Is that a common practice with Django? (I couldnt find much discussion on that on SO though) -
Error sum in sql request
I have model: class Sales(ModelWithCreator, models.Model): date = models.DateField(default=datetime.date.today) merchandise = models.ForeignKey(Merchandise) partner = models.ForeignKey(Partner) count = models.PositiveIntegerField() debt = models.PositiveIntegerField(default=0) price = models.PositiveIntegerField() cost = models.PositiveIntegerField() I have to get sum of all objects that model. I tried that: Sales.objects.all().extra(select={ 'total': 'Sum(price * count - cost)' }) But, I got error: column "sales_sales.id" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: SELECT (Sum(price * count - cost)) AS "total", "sales_sales"... -
Downloading a file from S3 using Boto3 in django
I want to download a file from my django application, for which i have written following code, but the file that is getting downloaded is just 4 bytes but actual is 456 kb in size. please correct me if am doing anything wrong ! #My django view that is written for downloads @login_required def large_file_download(request, slug): current_user = request.user print slug try: doc = Document.objects.get(slug=slug, file_delete=False) except ObjectDoesNotExist : return render(request, 'phoenix_app/file_404.html', status=404) if doc.owner == current_user: file_hash = doc.chash_address file_type = doc.file_type s3_client = boto3.client( 's3', aws_access_key_id= aws_settings.STORAGE_BACKEND['location']['AWS_AKey'], aws_secret_access_key= aws_settings.STORAGE_BACKEND['location']['AWS_SKey'], region_name= aws_settings.STORAGE_BACKEND['location']['AWS_RName'], ) file_data=s3_client.download_file(aws_settings.STORAGE_BACKEND['location']['AWS_BName'], file_hash, doc.file_name ) response = HttpResponse(file_data, content_type=file_type) response['Content-Disposition'] = 'attatchment; filename={}'.format(doc.file_name) return response else: return render(request, 'phoenix_app/invalid.html', status=403) #urls : from . import views from django.conf.urls import include, patterns, url urlpatterns = [ url(r'^dashboard/large_file_download/(?P<slug>[\w-]+[\w-]+)$', views.large_file_download, name='large_file_download'), ] -
Django AbstractUser doesn't show model
I'm a django beginner and i want to add a booleanfield to AbstractUser, but it's not showing the booleanfield in the admin. models.py class CustomUser(AbstractUser): selected = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['selected',] def __str__(self): return self.username admin.py admin.site.register(CustomUser, UserAdmin) settings.py AUTH_USER_MODEL = 'football_app.CustomUser' -
Why should we NOT use the default django project layout?
-THE STORY- So, I am currently working on my next application to take over the world. By the way its the first one I'm doing using django. I have gotten far into making the app and I was just about to start adding logos, buttons and etc. I now find myself encountering the STATIC_FILES part of django. Since my app will destroy everything and march its ad revenue all over the world I wanted to have great scale ability and and hopefully use a CDN in production. So, I make my way over to djangos documentation and notice a entire world of complicated stuff smacks me in the face and knocks my project back to django-admin startproject [name].(It really did not all my models are OK and such I just need to set up static files and fix my templates, urls and etc). Thats right, I made a 10 app web application with templates, views, urls and all done(ish) in the default layout provided by django. THE "PROBLEM" The reason I find myself re-making the project is because it seems I "need" to have a lot of fancy things in my project model to make an app that takes over … -
Environment variables in virtualenv through activate script with gunicorn & supervisor
My project is based on Django, Nginx, Gunicorn and Supervisor in a Virtual env. I export environmental variables at the end of the ./bin/activate script. Whenever I source the activate file, it exports environmental variables. It's pretty cool... My issue comes when I start the Supervisor script. It seems that the ./bin/activate isn't sourced as Django can't get vars such as SECRET_KEY. I heard people using a post-activate script which isn't present in my virtualenv bin dir. Am I missing something important? Why Supervisor doesn't source the ./bin/activate script? Here is my supervisor conf: command=/opt/.virtualenvs/plcweb/bin/gunicorn plcweb.config.wsgi -c /opt/plcweb/gunicorn.conf.py directory=/opt/plcweb/project user=bastien autostart=true autorestart=true redirect_stderr=True stdout_logfile=/opt/plcweb/gunicorn.log stderr_logfile=/opt/plcweb/gunicorn.log -
NoReverseMatch at /blog/2017/04/27/test_asset-purchase_2/
My first project of Django and following the book "Django by Example", i had made a html page to list all the posts i had created, and this page worked well, but if i click into anyone of the the post error occured! I had check my code with the book and found nothing different. I am so confused, please give me some help! Error Message: NoReverseMatch at /blog/2017/04/27/test_asset-purchase_2/ Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<post_id>\\d+)/share/$'] Request Method: GET Request URL: http://127.0.0.1:8000/blog/2017/04/27/test_asset-purchase_2/ Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: Reverse for 'post_share' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<post_id>\\d+)/share/$'] Exception Location: E:\workspace\pycharm\djangobyexample\mysite\env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: E:\workspace\pycharm\djangobyexample\mysite\env\Scripts\python.exe Python Version: 3.5.2 Python Path: ['E:\\workspace\\pycharm\\djangobyexample\\mysite', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\Scripts\\python35.zip', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\DLLs', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\lib', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\Scripts', 'c:\\users\\richard\\appdata\\local\\programs\\python\\python35\\Lib', 'c:\\users\\richard\\appdata\\local\\programs\\python\\python35\\DLLs', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env', 'E:\\workspace\\pycharm\\djangobyexample\\mysite\\env\\lib\\site-packages'] Models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_query(self): return super(PublishedManager, self).get_query().filter(status='published') class Post(models.Model): STATUS_CHOICES = { ('draft', 'Draft'), ('published', 'Published'), } title = models.CharField(max_length=250, primary_key=True) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_post') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: # Telling django to … -
dajngo rest framework - filtering against date query parameter
In my view I'm receiving date parameter and I'm filtering against it so I could show my contact for today, and it goes something like this: filter_date = self.request.query_params.get('filter_date', None) for queryset in contact_lead: if filter_date is not None: queryset = queryset.filter(next_action_date__gte=filter_date) return queryset Like I said with this I can see my contacts for today, but there are some contact that are made in the past, now because datepicker have past dates restriction I can not see them and I want all my past contact to appear today, or any other day in the future, so the point is I don't want contact which are created in the past to be left behind, so can someone help me and explain how can I get that result. -
Django cache loses keys
I have a Django installation that uses the FileSystem caches. The caching system is used by an array of different views. Putting in place various logs to log when a key is not found in the cache and hence regenerated, I've found out that often the keys are lost. I don't have any "cache delete" in place and all the keys are stored to last 24 hours, but in the logs they all appear to be regenerated once in a while. Is there any hidden parameter like "don't store more than n keys" or "more than n megabytes of data" or something? I'm a bit lost because it just seems that the keys are lost and I don't know when and why. Also, I originally chose as cache location "/tmp/django-cache", so I thought that maybe the tmp directory was being cleaned by Linux, but changing the location to a "safer" one in my home directory doesn't change the anomaly. Also, the full cache directory is around 25Mb, so I don't think there is something cleaning it up because it's too big. Any idea? -
After fresh install of django 1.11 and mysql-connector-python migrations fail to run. How can I resolve
I installed on ubuntu 16.04 django 1.11 usinf pip3 and then installed the oracle mysql-connector-python. Why is this error occurring? How can I resolve it? According to the tutorial migrations will run even if there are no models defined. Installed by using pip3 pip3 install --egg http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.1.6.zip My database configuration DATABASES = { 'default': { 'NAME': 'user_data', 'ENGINE': 'mysql.connector.django', 'USER': 'mysql_user', 'PASSWORD': 'priv4te', 'OPTIONS': { 'autocommit': True, }, } } The command that I ran python3 /home/django/workspace/mysite/manage.py migrate The Error Traceback (most recent call last): File "/home/django/workspace/mysite/manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/django/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/home/django/.local/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/home/django/.local/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/django/.local/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/home/django/.local/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/django/.local/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/django/.local/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): … -
I am getting MultiValueDictKeyError while editing the existing data and saving it in django admin?
I can be able to add the first data entry but after that editing the existing data or adding the new data causes MultiValueDictKeyError at /admin/api/digitalpost/9b763eae-cb8b-4473-af5d-5d4d91323ae1/change/ "u'contentlist_set-0-basemodel_ptr'". Models.py class BaseModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) version = models.FloatField(default=1.0) created_at = models.DateTimeField(auto_now_add=True) def image_tag(self): self.url = 'http://127.0.0.1:8000/' + self.picture.name return u'<img src="%s" />' % self.picture.url image_tag.short_description = 'Thumbnail' image_tag.allow_tags = True class Client(BaseModel): parent = models.ForeignKey('self',on_delete=models.SET_NULL, blank=True, null=True, related_name='brands') name = models.CharField(max_length=120, unique=True) picture = models.ImageField(upload_to="static/images/digital") list_display = ('name','parent',) description = models.CharField(max_length=250) def __unicode__(self): if self.parent: return "{} {}".format(self.parent.name, self.name) else: return self.name def parent_brand(self): return str(self) parent_brand.short_description = 'NAME' class Meta: ordering = ['parent__name','name'] class Category(BaseModel): title = models.CharField(max_length=64, unique=64) description = models.CharField(max_length=256, null=True, blank=True) def __unicode__(self): return self.title class Meta: ordering = ['-created_at'] verbose_name_plural = "categories" class DigitalPost(BaseModel): title = models.CharField(max_length=100) brand = models.ForeignKey(Client, on_delete=models.SET_NULL, blank=True, null=True, ) launch_date = models.DateField(blank=True, null=True) order = models.IntegerField() def __unicode__(self): return self.title class Meta: ordering = ['order'] class ContentList(BaseModel): title = models.CharField(max_length=100) description = models.CharField(max_length=256, null=True, blank=True) picture = models.ImageField(upload_to="static/images/digital", blank=True) post = models.ForeignKey(DigitalPost, on_delete=models.SET_NULL, null=True, blank=True) # post_category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) def __unicode__(self): return self.title class Meta: ordering = ['title'] admin.py class ContentListInline(admin.TabularInline): model = models.ContentList form = ContentListForm fk_name … -
Update sqlite database based on changes in production
I am deploying a Django App using Elastic Beanstalk on AWS. The app has a function whereby user can register their details. The problem is when I make small changes to my app and deploy this new version I loose the registered users since their information isn't in my local database (only the database on aws). Is there any way to download the modifications to the database during production so that I can keep these changes when I redeploy. I'm not using AWS RDS, I simply bundle the .SQLite file with my source code and deploy to Elastic Beanstalk. Thanks in Advance. -
Why the form has extraneous text?
Can someone say how to fix next little bag? I edit/update object data(in my case purpose data) by AJAX and then save it. I use Modal form to edit object. AJAX update works fine but I see the text inside comment form as in the picture below after successfull editing. Why? Why $("#purpose-comment-form")[0].reset(); didnt work? project_detail.html: <div class="card"> <div class="card-header"> <div class="d-flex align-items-center justify-content-between purpose-top"> {% include 'project/purpose_top.html' %} </div> </div> <div class="card-block"> <div class="collapse purpose-block" id="collapse-purpose"> {% include 'project/purpose_list.html' %} </div> </div> </div> purpose_list.html: <div class="list-group" id="purpose-list"> {% for purpose in purposes %} <div class="list-group-item flex-column align-items-start custom-list-group-item"> <div class="d-flex w-100 justify-content-start"> <p>{{ purpose.text }}</p> </div> <div class="comment-list-block"> <div class="list-group custom-list-group"> <div class="list-group-item bg-faded"> {% include 'project/purpose_comment_form.html' %} </div> <div class="purpose-comments"> {% include 'project/purpose_comment_list.html' %} </div> </div> </div> </div> {% endfor %} </div> purpose_comment_form.html: <form method="post" class="purpose-comment-form" id="purpose-comment-form"> <!--SOME HTML--> </form> js: $(function () { var loadForm = function () { var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal").modal("show"); }, success: function (data) { $("#modal .modal-content").html(data.html_purpose_form); } }); }; var saveForm = function () { var form = $(this); $("#purpose-comment-form")[0].reset(); //??? $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: … -
File /etc/nginx/sites-available/mysite_nginx.conf is empty after symlink
I'm following this tutorial http://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html on configuring nginx for django projects. I have problems after making a symlink. The file mysite_nginx.conf is created in directory /etc/nginx/sites-enebled but there's nothing in it. What am I supposed to put there? -
Dj-stripe 0.8.0 'djstripe_sync_customers' not working
I know this is a vague question. But I am running Django 1.9.8, python 3.5 and djstripe 0.8.0 and the sync customers command doesn't work. When we run the $python manage.py djstripe_sync_customers command and return to the admin page the customers subscription status doesn't change. Meaning we have a customer who's card has expired and their subscription still shows active. another customer who has already made 2 monthly payments still shows as trial. However, if that user views their payment history via: www.website.com/payments/history/ the Stripe info is synced correctly and all is good. Has anyone run into this before? Thanks in advance for the assistance. -
Django request GET return None on string
I have this url : /page_b/a015541/?pagei=a011&account_id=95651&application_id=5563&startdate=20170101&enddate=20170101 When parsing with : page_id= request.GET.get('pagename') account_id= request.GET.get('account_id') application_id= request.GET.get('application_id') uurid= request.GET.get('uurid') I have for string values : page_id = None Numerical have correct values How to fix this ? -
Django+Haystack+Whoosh, no models being indexed, no results returned in search
I have a haystack search implementation using the whoosh backend in django 1.10. I've followed the "Getting Started" documentation page and have implemented everything I can see there, however, when I run ./manage.py update_index It will show me Indexing 0 posts And when I run a test search I will get no results. I'm creating a forum web app and all the posts are populated with Lorem Ipsum... content. When I search "Lorem" it will not show me any results. settings.py: """ Django settings for portfolio project. Generated by 'django-admin startproject' using Django 1.11. 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 # 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/1.11/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 = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdown_deux', 'haystack', 'forum', ] 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', ] ROOT_URLCONF = … -
DJANGO/Heroku not saving into database POSTGRES
I am creating an API and my app isn't saving user information to the POSTGRES database. Can someone look over my code and tell me what is wrong? SECRET_KEY = os.environ['SECRET_KEY'] ALLOWED_HOSTS = ['salty-sands-40947.herokuapp.com','.herokuapp.com'] DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'aroomieapp', 'oauth2_provider', 'social_django', 'social.apps.django_app.default', 'rest_framework_social_oauth2', "push_notifications" ] 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', ] ROOT_URLCONF = 'aroomie.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.media', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'aroomie.wsgi.application' # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOGIN_REDIRECT_URL = '/' # Setting the image path in server MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' # This package help us to replace our database with Postgresql import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) AUTHENTICATION_BACKENDS = ( # Others auth providers (e.g. Google, OpenId, etc) # …