Indexpage/homepage with subpages

Hello django users,

I am trying to build a digital portfolio but I get stucked every time I want to dived the indexpage(homepage) into subpages and its getting to frustrated me :sweat_smile:.

I have followed the official django tutorial, https://docs.djangoproject.com/en/3.0/intro/tutorial01/. And tried to build in to my demandings. What I am trying to build currently is:

  • A homepage (here I want to describe a short introduction).
  • On this homepage, there should be an button with a link to my digital-portfolio page.

Currently I worked out the two pages in my urls.py. But now I want to link them to eachother. Hopefully someone can help me in this case :).

My codes:

urls.py

"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from digital_portfolio import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='index'),
    path('digital-portfolio', views.digital_portfolio, name='digital_portfolio')
]

settings.py

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.0.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'digital_portfolio',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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 = 'mysite.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',
            ],
        },
    },
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("HOMEPAGE")

def digital_portfolio(request):
    return HttpResponse("This is my digital portfolio page")

models.py

from django.db import models

# Create your models here.

apps.py

from django.apps import AppConfig


class DigitalPortfolioConfig(AppConfig):
    name = 'digital_portfolio'

Thanks in advance.

If you keep working your way through the tutorial, you will learn about how to build reference URLs into your page templates.

Ken

In this tutorial, I get stucked with the step when they add the urls.py in the app “polls”. This results in two files of urls.py which is hard to understand for me. As well, their homepage is polls/ while I want just the default url as indexpage. This would mean you should always add /polls in the web browser right?

You can add a root url entry to redirect any bare entries to /polls. You wouldn’t necessary need to add that manually yourself.
But all of the other URLs within polls is going to have that as part of any generated URLs.

In this case, in the tutorial, polls is just an “app” within your site. At this point, you’re building a site containing two apps - polls and admin. This URL structure allows you to add additional functionality by adding additional apps, and keeping the URL structures separate, avoiding any conflict.

This is a “Good Thing”.

Okay.

So now I want to create a model. But when I try to run:
python manage.py makemigrations digital_portfolio

I get the following error:
ModuleNotFoundError: No module named ‘digitalportfolio’

Is this because I named my app: “digital_portfolio”?
And should I change is to: “digitalPortfolio”?

My code inside the setting.py is:

INSTALLED_APPS = [
    'digitalportfolio.apps.DigitalPortfolioConfig',
    'digital_portfolio',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

Code in the apps.py is:

from django.apps import AppConfig


class DigitalPortfolioConfig(AppConfig):
    name = 'digital_portfolio'

A module name is the name of the directory. It’s whatever the directory name is. If the directory is digitalportfolio, the app is digitalportfolio. If the directory is digital_portfolio, the app is digital_portfolio. If the directory is digitalPortfolio, the app is digitalPortfolio.
Your naming convention is your choice - make it whatever you want it to be, however, I do suggest you are consistent with whatever pattern you choose.

(I think in the Django world at large, you’ll find a lot more apps named digital_portfolio than digitalportfolio, and probably never see one named digitalPortfolio or DigitalPortfolio - the last two don’t match common Django coding conventions.)

Also, you have:

'digitalportfolio.apps.DigitalPortfolioConfig',
'digital_portfolio',
  • Having both is redundant. You can either specify an app by the directory name (digital_portfolio) or by reference to an app configuration class (digital_portfolio.apps.DigitalPortfolioConfig), you don’t need both.
  • SInce the two references don’t match, my guess is that one of these is wrong, and based upon the message you relayed, it’s the reference to digitalportfolio.apps.DigitalPortfolioConfig

Ken

I see the issue. I have changed the code into this:

INSTALLED_APPS = [
    'digital_portfolio.apps.DigitalPortfolioConfig',
    #'digital_portfolio',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

I have added the ‘digital_portfolio’, into a comment to test. Afterwards the command in the cmd prompt works! :).

Sometimes I feel very dumb to ask those questions. I really appreciate your help in this. I document all this comments into a report to fall back onto if necessary.

Try not to feel dumb (easier said than done at times, I know). But try to keep in mind:

  • You’re climbing a pretty steep learning curve.
  • Everyone has had to learn these concepts, and have run into similar issues.
  • We’re here to help you along
  • We want to see you succeed.

Ken

I do my best to improve. Hopefully it’s all worth after a couple weeks from now.

For my understanding, I have tried to describe how a web request is processed in Django inside my own project. Is it correct when I say it as follows:

Request is: http://127.0.0.1:8000/digital-portfolio/

  1. A request comes in to /digital-portfolio/
  2. Django search in the settings.py to the ROOT_URLCONF which is ROOT_URLCONF = 'mysite.urls’
  3. Django looks at all of the URLpatterns in the URLconf for the first one that matches /digital-portfolio/
  4. Django looks for an app digital_portfolio and in this this app the urls

And from here I get stucked… What is django doing here?

Maybe I should make a seperate topic for this. Please let me know.

The overview for what’s happening here can be found in the How Django processes a request section of the URL dispatcher page.

Just keep in mind that the URL “digital-portfolio/” has no intrinsic relationship to any app, regardless of the name.
Django performs the search through the urlpatterns to find one that matches. If the match is for a view, it calls the view. If the match is for an included URL, it then repeats this search with what follows “digital-portfolio/” with the included urlpatterns.

Yes I have read the documentation on the Django site, but I can’t place the information. It is referring to so many modules and references which I doesn’t understand with the knowlegde I have at the moment.

How does the information comes to the views.py? Because the views.py is actual sending the information back to the request right?

Maybe, it’s sinks a little bit in my head now. I got the following folder structure:
FolderStructure

in mysite/urls (urls.py) I have the following code:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),

    path('', include('digital_portfolio.urls')),
    path('digital-portfolio/', include('digital_portfolio.urls')),
]

In digital_portfolio/urls I have the following code:

from django.urls import path

from . import views  #the . (dot) means the current "directoy"! and the directory in this case is 
                     # digital_portfolio. So the command looks at the views.py in the digital_porfolio folder

urlpatterns = [
    path('', views.index, name='index'),
    path('digital-portfolio/', views.digital_portfolio, name='digital_portfolio'),
    
]

But what is the difference between the path codes in the urlpatterns? In bot urls.py files the path in described? Should it not be easier to understand just having one urls.py file?

I’m going to continue to refer you to the Django tutorial. If you work your way all the way through the tutorial, you’ll have the chance to see how all the pieces fit together. Your questions are answered there once you see how a completed application is put together.

I have stopped following the tutorial. I doesn’t understand it anymore from part 3. I going to try searching on the internet.

What is it about the tutorial that you’re not understanding? It is, in fact, part 3 which specifically addresses the questions you asked just prior to this.

(I’ll also add, that the best way to learn this is to work through all the examples and not just try to read it. This means actually typing the examples and running them. There’s a learning process that goes on when you type something instead of just reading it.)

The coding is to hard. As well, I have named my folder already digital_portfolio instead of “polls” which makes it very confusing. Also, I have made my homepage as http://127.0.0.1:8000/ instead of http://127.0.0.1:8000/polls so mostly the codes in the tutorial aren’t corresponding to my needs…

Now the only thing I do is copy/paste from the tutorial and hoping it is working, and this doesn’t feels as learning but wasting my time.

You’re trying to jump ahead, and that’s creating the confusion. If you’re finding the Python difficult to understand, then it might be worth your effort to spend some time with a Python tutorial and work through that to become more comfortable with the language - after all, Django is just Python.

Don’t rush the process - there are a lot of people who have worked on crafting this tutorial over a number of years. It’s teaching the concepts that you will need to learn to apply to your own projects.

You are correct, it’s not exactly what you’re looking to do - but the concepts are all there. The parallels are there and so once you understand how and why the polls application is put together the way it is, you can do the same for your own project.

(That’s also why I, and others as well, recommend that you actually type the examples - it adds a layer of learning that you don’t get by copy/pasting lines of code.)

So take your time, work the examples, and - in the case of your original questions about URL mappings, see how the URLs in the polls app work to create a URL structure within your site. Once you understand that, then you’ll be able to apply that to your own project.

Ok.

I will start a new topic due to how to setup from scratch a new project…