Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-CKEditor : how to translate style element's name?
I am working on a django project that uses django-ckeditor. It uses the following default styleset (defined in styles.js) : CKEDITOR.stylesSet.add( 'default', [{ /* Block Styles */ name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Object Styles */ { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, ] ); I have to change the "Special Container" name to something else ("Framed text"), so to do it without modifying directly the code of django-ckeditor, I define a new styleset in the django-ckeditor's config in the settings.py file of the project : 'stylesSet': [ { 'name': 'Framed text', 'element': 'div', 'styles': { 'padding': '5px 10px', 'background': '#eee', 'border': '1px solid #ccc' } }, ], Up to there it works well. However the site on which I have to deploy this is translated in multiple languages and I would like to translate the "Framed Text" name to different languages. I was thinking about writing a plugin that redefines the default stylesSet depending on the language, but I'm pretty sure there is a better solution that I am missing. I searched the web a lot and could not … -
Django merge two QuerySets
I want to merge these two QuerySets. HotkeyAndPrefix do not have entries for every Collection in all_collections. This means len(all_collections) >= len(all_collections_hotkeys_and_prefixes). How can i merge these two QuerySets? If there is no entrie found for a Collection in HotkeyAndPrefix I want hotkey = None, prefix=None. Can I achieve this in one query? models.py: class Collection(models.Model): creator = models.ForeignKey(User, blank=True, null=True) ... class HotkeyAndPrefix(models.Model): user = models.ForeignKey(User, null=True) assigned_collection = models.ForeignKey(Collection, null=True) hotkey = models.CharField(max_length=1, blank=True, null=True) prefix = models.CharField(max_length=20, blank=True, null=True) class Meta: unique_together = ('user', 'assigned_collection') view.py admin = User.objects.filter(username='admin')[0] all_collections = Collection.objects.filter(creator=admin) current_user = request.user all_collections_hotkeys_and_prefixes = HotkeyAndPrefix.objects.filter(assigned_collection__in=all_collections, user=current_user) -
Django Suspicious Operation Request Session deleted
I try to get my django page running on my server and stumble upon the following error message in my browser: SuspiciousOperation at /lfp/filter/ The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example. The traceback you can find here: Environment: Request Method: GET Request URL: http://localhost/pass/lfp/filter/ Django Version: 1.11.2 Python Version: 3.6.1 Installed Applications: ['django_tables2', 'pass_list.apps.PassListConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] Traceback: File "/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 65. return self.cursor.execute(sql, params) File "/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute 328. return Database.Cursor.execute(self, query, params) The above exception (attempt to write a readonly database) was the direct cause of the following exception: File "/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py" in save 87. obj.save(force_insert=must_create, force_update=not must_create, using=using) File "/lib/python3.6/site-packages/django/db/models/base.py" in save 806. force_update=force_update, update_fields=update_fields) File "/lib/python3.6/site-packages/django/db/models/base.py" in save_base 836. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/lib/python3.6/site-packages/django/db/models/base.py" in _save_table 903. forced_update) File "/lib/python3.6/site-packages/django/db/models/base.py" in _do_update 953. return filtered._update(values) > 0 File "/lib/python3.6/site-packages/django/db/models/query.py" in _update 664. return query.get_compiler(self.db).execute_sql(CURSOR) File "/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql 1191. cursor = super(SQLUpdateCompiler, self).execute_sql(result_type) File "/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql 886. raise original_exception File "/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql 876. cursor.execute(sql, params) File "/lib/python3.6/site-packages/django/db/backends/utils.py" in execute 80. return super(CursorDebugWrapper, self).execute(sql, … -
retrieve data from value in database using Javascript Django
Hi i am a newbie in Django. I am using datatables (https://datatables.net/) to populate my data. Could anyone please give some advice on what i should change in my code ? I have data in database but i have no idea why the data wasn't being shown in the table. views.py from django.core import serializers def ltimesheet(request): json_serializer = serializers.get_serializer("json")() query_results = json_serializer.serialize( Timesheet.objects.all(), ensure_ascii=False ) data={'query_results':query_results} return render(request, 'hrfinance/list_timesheet.html', data) this is how my script looks like var dataSet = '{{ query_results|escapejs }}'; /*create the table*/ $(document).ready(function() { var table = $('#example').DataTable( { data: dataSet, columns: [ { title: "Student ID" }, { title: "Student Name" }, { title: "Start Date" }, { title: "End Date" } ] } ); -
transaction.atomic() inside celery task
The code below is rising InternalError('SAVEPOINT can only be used in transaction blocks\n',) sometimes. I know that inside transaction.atomic we cannot call celery task, but cannot find whether it's ok to use atomic request inside celery task (I need atomicity in celery task). @celery.task(default_retry_delay=2 * 60, max_retries=2) # retry in 2 minutes def test(): try: with transaction.atomic(): # do smth except Exception, exc: raise test.retry(exc=exc) -
How to deploy multi-tenant django application using elastic beanstalk on AWS
I am using django-tenant which enables django powered websites to have multiple tenants via PostgreSQL(default for django-tenants) schemas. Backend Database on AWS- RDS - PostgreSQl. After application deployed on elastic beanstalk I am trying to access application using tenant1.ebs.com url or tenant2.ebs.com and for this I am facing problem. Elastic beanstalk is neither responding while accessing tenant url and nor it is showing any error on browser. Please help. -
Django 'User' object is not iterable
i don't know why i'm getting this error..[ 'User' object is not iterable ] here i want to print (logged in user) followers in home page. apart from error is my models.py is right ? for followers and following mechanism. models.py from django.db import models from django.contrib.auth.models import User class Tweet(models.Model): user = models.ForeignKey('auth.User') class Follow(models.Model): following = models.ForeignKey('auth.User', related_name='following') followers = models.ForeignKey('auth.User', related_name='followers') class post(models.Model): text = models.CharField(max_length=160) views.py from django.shortcuts import render from .models import Tweet,Follow,post # Create your views here. def profile(request): current_user = request.user twi = Follow.objects.get(pk=current_user.id) display = twi.followers return render(request,'home.html' , {'detail':display,'user':current_user,}) home.html <!DOCTYPE html> <html> <head> <title>{{ user }}</title> </head> <body> {% for o in detail %} <h1>o.followers</h1> {% endfor %} </body> </html> -
Django: Muliple pi chart using nvd3 and d3
I have designed tool using the django which will read the user activity from the database and it will display them as the pi chart. Below is my view.py: from django.http import HttpResponse,HttpResponseRedirect from django.shortcuts import render import random import datetime import time from get_user_status import get_user_status def index(request): activity_dic = {} xdata = [] ydata = [] user_statuses = get_user_status(get_user_name(request)) for user_status in user_statuses: if user_status[3] in activity_dic: activity_dic[user_status[3]] = activity_dic[user_status[3]] + 1 else: activity_dic[user_status[3]] = 1 for key in activity_dic: xdata.append(key) ydata.append(activity_dic[key]) extra_serie = {"tooltip": {"y_start": "", "y_end": " cal"}} chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie} charttype = "pieChart" data = { 'charttype': charttype, 'chartdata': chartdata, } return render(request,'view_report.html', data) def get_user_name(request): if request.user.is_authenticated() is False: return HttpResponseRedirect("/login_page/") else: user_name = request.user.username return str(user_name) Below is my template: {%load static %} <meta charset="utf-8"> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="https://d3js.org/d3.v3.min.js"></script> <script type="text/javascript" src='{% static 'nvd3/nv.d3.min.js' %}'></script> <link rel="stylesheet" type="text/css" src='{% static 'nvd3/nv.d3.min.css' %}'/> {% load nvd3_tags %} <head> {% load_chart charttype chartdata "piechart_container" %} </head> <body> <h1>Activity vs days</h1> {% include_container "piechart_container" 800 800 %} </body> I am getting one pi chart as expected.Now I want to add multiple pi chart.How to do that?I have searched a lot but … -
Changing django default pk with AutoField to BigAutoField
My model has a default pk with AutoField (integer) but later on i discovered that i need to use BigAutoField instead! And also i have data in then with other models referencing the student model:: how do i change the pk field to BigAutoField and also reflects on other referencing models class Student(models.Model): matric_no = models.CharField(max_length=20, unique=True) # first set it to U(random) password = models.CharField(max_length=128) session = models.ForeignKey(Session, null=True) programme = models.ForeignKey(Programme, null=True) school = models.ForeignKey(School, null=True) course_comb = models.ForeignKey(CourseComb, null=True) serial = models.IntegerField(null=True) current_level = models.CharField(max_length=3, choices=LEVEL_CHOICES, default='100', null=True) last_login = models.DateField(null=True) is_active = models.CharField(max_length=1, default=1, choices=((1, 1), (0, 0))) created_at = models.DateTimeField(default=timezone.now) updated_at = models.DateTimeField(auto_now=True) -
How do I get the username and number of pokes of given to a specific user id from database
After a user logs in to my django application. The User can poke another User in the database. How can I get the User firstname of the poker and number of pokes they gave to a specific User in the database? Below is my code. This is how I get the number of times a User has been poked in html template. Please help. {{ i.pokegotten.all | length}} class User(models.Model): firstname = models.CharField(max_length=45) lastname = models.CharField(max_length=45) email = models.EmailField(max_length=45) password = models.CharField(max_length=255) bday = models.DateField(auto_now=True) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) objects = UserManager() class Poke(models.Model): poker = models.ForeignKey(User,related_name= "pokegiver") poked = models.ForeignKey(User, related_name= "pokegotten") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) objects = PokeManager() -
How to modify Django query_set before serving it in a ListView
I have a Django project with a database of Song Objects that users can search through. My models.py looks like this: class Songs(models.Model): title = models.CharField(max_length=100) artist = models.CharField(max_length=100) link = models.CharField(max_length=255, unique=True) album = models.CharField(max_length=100) duration = models.CharField(max_length=40) # Duration in num_secs and my views.py looks like this: class ResultsView(ListView): template_name = os.path.join(APPNAME, "results.html") model = Songs context_object_name = 'results' paginate_by = 60 ordering = ['title'] def get_context_data(self, **kwargs): context = super(ResultsView, self).get_context_data(**kwargs) context['query'] = self.request.GET.get('query') return context def get_queryset(self, **kwargs): query = self.request.GET.get('query') query_set = Songs.objects.all() results = query_set.filter(title__icontains=query) return list(results) And my results.html template looks like this: {% if results %} <div class="container-fluid"> <div class="row"> {% for result in results %} <div class="col-md-2 result-col"> <a data-toggle="tooltip" title="{{ result.title }}" target="_blank" href="/song/{{ result.id }}"> <div class="result-text">{{ result.title }} </div> <div class="result-dur">{{ result.duration }}</div> </a> </div> {% endfor %} </div> </div> {% else %} <h2>No Results</h2> {% endif %} Due to the way the data is initially stored in my DB, the duration of each song is stored as the number of seconds, ie a song that is 2 minutes long is stored with a duration of 120. However, I want to display it on the template in the … -
Django template & Javascript: How to get value(for radio buttons) or text value of each cells of a dynamic table?
My Table goes like this number of rows are dynamic. his is how the problem goes. For convenience and timesaving of users who are analysing the rows and submitting the data and also so that the data gets submitted only in specific format. Format: "C:GSMXXXX&T:GSMXXXX;C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX; C:GSMXXXX&T:GSMXXXX;" So it's basically multiple(n) pairs of C: & T: id's of GSM's. Step 1. User checks in either the control or test radio button. if: he checks control form textbox gets filled up with "C:" else if : he checks test box form textbox gets filled up with "T:" Step 2: User clicks on the GSMXXXX id in the same row. if: GSMXXXX is after C: then the output for form textbox is = "GSMXXXX " elseif: GSMXXXX is after T: then the output for form textbox is = "GSMXXXX " Step 3: At the end of the row either user chooses with or Submit to output "&" or ";". And all these values in form textbox should be appendable. Up to any length user want to go. The number of rows in the table are dynamic. My HTML code <table class="sample_table" id="table"> <tr> <th>Select_sample_type</th> <th>!Sample_geo_accession</th> <th>!Sample_title</th> <th>!Sample_platform_id</th> <th>!Pair it With/Submit</th> </tr> {% … -
how can I change default python version in pythonanywhere?
I am trying to deploy my Django application on pythonanywhere through manual-configuration. I selected Python 3.6.When I opened the console and type "python --version" It is showing python 2.7 instead of 3.6. How can I change this? Please help me. -
Python Django Mysql:ImportError: cannot import name Thing2Literal
When I am working with django, it came out that 'ImportError: cannot import name Thing2Literal'. I tried to make migrations from python to mysql but this problem came out. I have searched for many times, someone says it is the version of PyMysql that matters,but I have checked the version which may work well with my environment. My settings.py include the following code: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join(BASE_DIR, 'mysqlblogdb'), 'USER': 'root', 'PASSWORD' : 'sher', 'HOST' : 'localhost', 'PORT' : '3306', } } 'blog' is my app,and the error came as: sherdeMacBook-Pro:website sher$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/Library/Python/2.7/site-packages/django/__init__.py", line 27, in setupapps.populate(settings.INSTALLED_APPS) File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populateapp_config.import_models(all_models) File "/Library/Python/2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Library/Python/2.7/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Python/2.7/site-packages/django/contrib/auth/base_user.py", line 52, in <module> class AbstractBaseUser(models.Model): File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 119, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 316, in add_to_class value.contribute_to_class(cls, name) … -
why do we not use {{ }} while removing hardcoded urls in django?
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> here we use {{ }} tag as question.id is a variable but, <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> when we remove the hardcoded url from our template why we do not use {{ }} around the question.id? -
Dajngo BeautifulSoup Error
So basically im trying to use BeautifulSoup within a vertualenv in a django view. however when ever i run the server i get this Error. form bs4 import BeautifulSoup import bs4 as bs ImportError: No module named 'bs4' Btw this is not the full error, as it is very long so i just got the end result. importing the module outside of django works (project) PS C:\Users\jchen\desktop\project> pip install BeautifulSoup4 Requirement already satisfied: BeautifulSoup4 in c:\users\jchen\desktop\project\lib\site-packages -
The difference between django slice filter usages
I have a myList list with e.g. 5 elements, but I want to slice it in template by using command: {% for item in myList|slice:"3" %} or this command: {% for item in myList|slice:":3" %} What's the difference between slice:"x" and slice:":x"? (I don't have currently access to machine with django installed but I'm curious) -
how to |safe the whole template content in django
I am using django rest-auth and it has a view that sends out password-reset email. I want to override that template. I put my own template under /templates/registration/password-reset-email.html and it is also being taken by django. only problem is, password-reset-email.html now completely new template and I dont extend any template. When I receive the email, email has all the html tags in it: <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head> <!-- NAME: 1 COLUMN --> <!--[if gte mso 15]> .... I cannot override any view. any ideas how to |safe this? -
Gunicorn excess arguments
Setting up gunicorn service and I'm getting an excess arguments error root@samuel-pc:/usr/local/bin# systemd status gunicorn.service Excess arguments. root@samuel-pc:/usr/local/bin# systemd start gunicorn Excess arguments. the service details are below GNU nano 2.5.3 File: /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=/root/revamp ExecStart=/usr/local/bin/gunicorn --access-logfile - --workers 3 --bind unix:/r$ [Install] WantedBy=multi-user.target -
Django save() method does not insert data to my Mysql database
I have tried to entered data to Mysql database using Django. The user enters the required data through addSubscriber.html page to save in the database but the data entered is not saved in the database. Whenever I check the Mysql table (in this case 'Subscribers' table), the table is empty. Should I install mysql-connecter or not? Here are my files: views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.views import generic from .models import Subscribers from .forms import addSubsForm @login_required def dashboard(request): user = request.user context = {'user': user} template = 'dashboard.html' return render(request, template, context) @login_required def addSubscriber(request): template = 'addSubscriber.html' if request.method == 'POST': form = addSubsForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] area = form.cleaned_data['area'] phoneNumber = form.cleaned_data['phoneNumber'] installationCost = form.cleaned_data['installationCost'] billNumber = form.cleaned_data['billNumber'] print name Subs = Subscribers.objects.create(name=name, area=area, phoneNumber=phoneNumber, installationCost=installationCost, billNumber=billNumber) Subs.save() return redirect('report') else: form = addSubsForm() return render(request, template, {'form': form}) @login_required def report(request): context = locals() template = 'report.html' return render(request, template, context) models.py from __future__ import unicode_literals from django.db import models class Subscribers(models.Model): name = models.CharField(max_length=120) area = models.CharField(max_length=30) phoneNumber = models.CharField(max_length=10) installationCost = models.CharField(max_length=10) billNumber = models.CharField(max_length=100, unique=True) addSubscriber.html {%extends 'base.html'%} {% load staticfiles %} {% load crispy_forms_tags … -
LDAP search to list contact names in DJango
I am building a Django app, I am required to pull contact names from a LDAP server. I have the following piece of information in my settings.py: AUTH_LDAP_SERVER = '' AUTH_LDAP_BASE_USER = "" AUTH_LDAP_BASE_PASS = "" AUTH_LDAP_BASE = "" Now in my views.py, I would like to perform a search operation to retrieve contact names from LDAP server using the data entered by the user in an input field. I would like to know how I can perform the search operation in my views.py to filter data and send a list to the user to provide matching list. -
Getting a import error when trying to import BeautifulSoup (bs4)
i have installed BeautifulSoup in a virtualenv, however when i try to import it i get this error. from bs4 import BeautifulSoup ImportError: No module named 'bs4' (project) PS C:\Users\username\desktop\project> pip3 install beautifulsoup4 Requirement already satisfied: beautifulsoup4 in c:\users\username\desktop\project\lib\site-packages -
How to make add replies to comments in Django?
I'm making my own blog with Django and I already made a Comments system.. I want to add the replies for each comment (like a normal comment's box) and I don't know what to do this is my current models.py comments: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() created_date = models.DateField(auto_now_add=True) parent = models.ForeignKey('self', null=True, related_name='replies') def __str__(self): return self.text and this is the .html where I use the comments {% for comment in post.comments.all %} <ul> {{ comment.text }} {% for reply in comment.replies.all %} <li> {{ reply.text }} </li> {% endfor %} <ul> {% endfor %} and apparently It is working but when I try to make a comment in the admin site of Django it forces me to put a "Parent" to each comment (and this is not obligatory beacuse not every comment is a reply) I also don't know how to add the reply "button" in the HTML file. Please help tell me what changes can I do to make a simple comment box with replies . Thanks a lot -
It shoud return an object of type HttpResponse instead of EmailMessage
My requesting url is GET /documents/send/1/ HTTP/1.1 @staff_member_required @csrf_exempt def ajax_send(request, request_id=None): req= Request.objects.get(pk=request_id) request_folders = req.folder.all_files.all() context = [] for doc in request_folders: if doc.meta.state == u'rejected': context.append(doc) ctx = {'request': req} response = EmailFromTemplate('document-refusal', extra_context=ctx)\ .send_to(req.customer.user) return response and the traceback is Arold Tremblay > System User email_out "Arold Tremblay" <testjohn@email.com> Document refusal Internal Server Error: /documents/send/1/ Traceback (most recent call last): File "/home/jeremie/Projects/credit-24-django/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "/home/jeremie/Projects/credit-24-django/venv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'EmailMessage' object has no attribute 'get' 127.0.0.1 - - [29/Jun/2017 21:34:19] "GET /documents/send/1/ HTTP/1.1" 500 - Traceback (most recent call last): File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__ return self.application(environ, start_response) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 170, in __call__ response = self.get_response(request) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 140, in get_response response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 234, in handle_uncaught_exception return handle_uncaught_exception(request, resolver, exc_info) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/core/handlers/exception.py", line 128, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django_extensions/management/technical_response.py", line 6, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/core/handlers/base.py", line 131, in get_response response = middleware_method(request, response) File "/home/jeremie/Projects/credit-24-django/venv/lib/python2.7/site-packages/django/middleware/clickjacking.py", line 32, in process_response if response.get('X-Frame-Options') is not None: AttributeError: 'EmailMessage' object has no attribute 'get' I know that my view return an object … -
Django S3 with CloudFront pointing to subdirectory
I'm using django-storages to upload assets to an S3 bucket and then using CloudFront to serve those images. The challenge I have is that the media and static directories sit one level deep in a sub directory in my S3 bucket and with CloudFront pointing to the subdirectory. So the S3 url is https://my-bucket.s3.amazonaws.com/subdir/media And my CloudFront dir is https://blahblah.cloudfront.net/media (no subdir) My custom_storage file looks like this: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = '/subdir/' + settings.STATICFILES_LOCATION def __init__(self, *args, **kwargs): """Initialise.""" kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super().__init__(*args, **kwargs) class MediaStorage(S3Boto3Storage): location = '/subdir/' + settings.MEDIAFILES_LOCATION def __init__(self, *args, **kwargs): kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super().__init__(*args, **kwargs) And the relevant bit of my config file looks like this: AWS_STORAGE_BUCKET_NAME = 'bucket-name' AWS_S3_CUSTOM_DOMAIN = '{}.s3.amazonaws.com'.format(AWS_STORAGE_BUCKET_NAME) AWS_CLOUDFRONT_DOMAIN = "blhblah.cloudfront.net" STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storage.StaticStorage' STATIC_URL = "https://{}/{}/".format(AWS_CLOUDFRONT_DOMAIN, 'static') MEDIAFILES_LOCATION = 'media' MEDIA_URL = "https://{}/{}/".format(AWS_CLOUDFRONT_DOMAIN, 'media') DEFAULT_FILE_STORAGE = 'custom_storage.MediaStorage' It uploads to the right place but serves the assets from the wrong dir (https://blahblah.cloudfront.net/subdir/media). What am I missing here?