Home > database >  Django HTTP Error 404: Not Found: Using a config.json file in my views
Django HTTP Error 404: Not Found: Using a config.json file in my views

Time:12-22

I have 3 apps and one is called 'cv' but for this app I use a config.json file but it keeps giving me a 404-error when loading the page.

My project is called "project_1" and my urls.py is defined as:

  urlpatterns = [
  path("", include("cv.urls")),
  path("admin/", admin.site.urls),
  path("projects/", include("projects.urls")),
  path("blog/", include("blog.urls")),
]

http://127.0.0.1:8000/admin

http://127.0.0.1:8000/projects and

http://127.0.0.1:8000/blog

can be reached, but when I open

http://127.0.0.1:8000

It gives me the error.

In the cv-directory, I have my urls.py defined as:

 urlpatterns = [
        path("", views.index, name="cv_index"),
    ]

And my cv/views.py as:

def index(request):
    BASEURL = request.build_absolute_uri()
    url = BASEURL   "/static/configuration/configuration.json"
    response = urllib.request.urlopen(url)
    configuration = json.loads(response.read())
    return render(request, "index.html", configuration)

Where my json configuration is located in the cv directory under static>configuration>configuration.json

When I change my index function in cv/views.py to just render the request and give back my index.html file, it goes fine. So I expect it has something to do with this piece of code:

BASEURL = request.build_absolute_uri()
url = BASEURL   "/static/configuration/configuration.json"
response = urllib.request.urlopen(url)
configuration = json.loads(response.read())

My traceback looks like this:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 3.2.6
Python Version: 3.9.9
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'projects',
 'blog',
 'cv']
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 (most recent call last):
  File "C:\Users\s.pauly\Github\portfolio\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\s.pauly\Github\portfolio\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\s.pauly\Github\portfolio\cv\views.py", line 8, in index
    response = urllib.request.urlopen(url)
  File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
    response = meth(req, response)
  File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
    response = self.parent.error(
  File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
    return self._call_chain(*args)
  File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "C:\Users\s.pauly\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)

Exception Type: HTTPError at /
Exception Value: HTTP Error 404: Not Found

CodePudding user response:

In your settings.py, what does your static files configuration look like? More specifically, have you defined the STATIC_ROOT and STATIC_URL variables?

You should be accessing static assets via the STATIC_URL.

Additionally, I would highly advise against sending a urllib.request inside a view function to access a static asset. Instead (assuming you are using a modern version of Django), access the file in your view function like so:

from django.templatetags.static import static

def index(request):
    # use the imported static function to access the file as you would in a template
    config_file = static('configuration/configuration.json')
    
    # parse the json
    config_json = json.loads(config_file)
    
    # return your template and payload
    return render(request, "index.html", configuration)

However, have you ran python manage.py collecstatic, and verified that the configuration.json is collected and placed in your static directory defined under the STATIC_ROOT variable in settings.py? I would suggest starting here.

Another potential issue could be your app namespacing. What does the directory structure of your STATIC-ROOT directory look like? I highly recommend installing the Django Extensions plugin for development; the added python manage.py show_urls command is incredibly useful for debugging errors such as these.

I don't have enough rep yet to comment on other answers, but @Marco: json.loads() will deserialize a valid json instance to a Python object (dict), so passing configuration in his render statement should be fine, assuming the json is valid. The issue right now is accessing the file itself-- OP's solution of sending a GET request to his /static/ path is returning a 404.

CodePudding user response:

Django documentation for render says:

render(request, template_name, context=None, content_type=None, status=None, using=None)

So, you should pass those configuration probably as context if it's an dictionary:

return render(request, "index.html", context=configuration)

context: A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.

  • Related