Search code examples
pythondjangoherokudjango-mptt

Unable to retrieve from Django database in deployed Heroku App


Hi guys I'm really stuck on something developing my website with Django/Heroku. (And also using mptt)

I get the error: (again2 is the name of a table)

  DoesNotExist: again2 matching query does not exist.

I get no errors when I run locally, but I get a 500 error when I deploy to Heroku. So something has gone wrong in terms of communication between Heroku and my Django database. But I have no idea what to do to fix this?

A list of things I have done (looking at other people's questions):

  • python manage.py makemigrations followed by git commit, pushing to heroku and heroku run manage.py migrate
  • i have imported ''django.contrib.sites' into my installed apps, i have my herokuapp url saved as a site object
  • i have an updated requirements.txt
  • heroku appears to have 'data' and tables in the database it created for the app (heroku postgres)

Below is what I would have in my views:

 def topic_detail(request, x):
     text1 = str(again2.objects.get(pk='Top').get_children())
    return render(request, 'things/topic_detail.html', {
        'text1': text1,
   })

In local this would work, on deployment it would give the error, if i replaced text1 to just be again2.objects.all() it would show the contents on local but nothing on deployment to heroku (with no errors) Essentially what I'm trying to do is (for now) show the children of Top which is a member of again2.

I can't really move forward until I figure this out, your help would be much appreciated, if there is anything else you need let me know please, thank you in advance


Solution

  • This has nothing to do with migrations, requirements files or virtualenvs. DoesNotExist only means one thing. The object does not exist in your database. When you are using .get in this manner you sould always wrap it in try expect or use get_object_or_404 instead

    def topic_detail(request, x):
        try: 
            text1 = str(again2.objects.get(pk='Top').get_children())
            return render(request, 'things/topic_detail.html', {
               'text1': text1,
           })
        except again2.DoesNotExist
            raise Http404
    

    or more concisely

       text = get_object_or_404(again2, pk='Top')
    

    You can confirm that your database does not have this record by using the cli

    Now for some unsolicited advice. Please get into the habit of starting class names with an upper case letter.

    Update: migrations

    Django migrations are a painless way of managing the schema. A simple way to make changes to the models and have them reflected on the database. Applying migrations do not result in data from one server being moved to another. For that you need

    ./manage.py dumpdata > dumpfile.json
    ./manage.py loaddata dumpfile.json
    

    Or you can use the posgresql COPY FROM/TO which is more efficient.