Delroy Brown
Delroy Brown

Reputation: 125

TypeError when using AWS S3 Bucket with Django

I'm brand new to Django and AWS S3 and seem to have hit a wall. This is all on localhost at the moment. I'm trying to add a new product through my own admin app for a Art Gallery website i'm working on, all worked fine originally when adding a product, but since using AWS S3 i receive the following TypeError:

enter image description here

enter image description here

The error states that it's expecting "...a string or bytes-like object." and refers to the following lines of code in both my mixins.py and my staff views.py

mixins.py:

from django.shortcuts import redirect


class StaffUserMixin(object):
    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_staff:
            return redirect("home")
        return super(StaffUserMixin, self).dispatch(request, *args, **kwargs)

views.py:

class ProductCreateView(LoginRequiredMixin, StaffUserMixin, generic.CreateView):
    template_name = 'staff/product_create.html'
    form_class = ProductForm

    def get_success_url(self):
        return reverse("staff:product-list")

    def form_valid(self, form):
        form.save()
        return super(ProductCreateView, self).form_valid(form)

As I stated at the start i'm very new to both Django and AWS S3, so if this is just a schoolboy error, please forgive me but any help would be fantastic. And if any additional info is needed i'll be happy to provide. Thanks!

Upvotes: 0

Views: 221

Answers (1)

Mahmoud Daker
Mahmoud Daker

Reputation: 33

You need to write some lines in your settings.py file in order to get django-storages to work.

Those lines are:

AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME')

and you need to identify those variables in your .bash_profile file (if you are on mac) so that they are not committed to your version control system for security reasons.

You need to follow this syntax:

export AWS_ACCESS_KEY_ID="YOUR_ID" **(NO SPACES)**
export AWS_SECRET_ACCESS_KEY="YOUR_SECRET_KEY"
export AWS_STORAGE_BUCKET_NAME="YOUR_BUCKET_NAME"

and then you need to provide Heroku (on which I encountered this error) with this data by using configVars.

In your Terminal/CommandLine:

heroku config:set AWS_ACCESS_KEY_ID="YOUR_ID"
heroku config:set AWS_SECRET_ACCESS_KEY="YOUR_SECRET_KEY"
heroku config:set AWS_STORAGE_BUCKET_NAME="YOUR_BUCKET_NAME"

Make sure to use double-quotes!

Upvotes: 2

Related Questions