Django.fun

Django can't get page with a form to load in browser 404

I've got my LAMP setup with Ubuntu and MariaDB. The Django code managed to create some tables for me in the database but I just get 404 when I try to load my form in my browser via URLS http://127.0.0.1/create_unit or http://127.0.0.1/vcm/create_unit

Maybe my urls.py is wrong. Maybe it's my settings.py. I've trying all sorts of things so my code has probably got a bit mangled.

From TEMPLATES in settings.py I've hardcoded the path to my .html I've experimented with this a lot.

'DIRS': [ '/opt/vcm_project/vcm/templates/vcm' ],

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('create_unit', views.create_unit, name='create_unit'),
]

models.py

from django.db import models

# Create your models here.
class Unit(models.Model):
    unit_code = models.CharField(max_length=15)
    unit_name = models.CharField(max_length=255)
    unit_sector = models.CharField(max_length=255)
    unit_application = models.TextField(max_length=65535)
    unit_url = models.URLField(max_length=255)
    superseded_equivalent = models.CharField(max_length=15)

    def __str__(self):
        return self.unit_name

class Element(models.Model):
    element_number = models.CharField(max_length=100)
    element_name = models.CharField(max_length=255)

    def __str__(self):
        return self.element_name

forms.py

from django import forms
from .models import Unit

class UnitForm(forms.ModelForm):
    class Meta:
        model = Unit
        fields = ('unit_code', 'unit_name', 'unit_sector', 'unit_application', 'unit_url', 'superseded_equivalent')
        widgets = {
            'unit_code': forms.CharField(label='Unit code', max_length=15)
            'unit_name': forms.CharField(label='Unit name', max_length=255)
            'unit_sector': forms.CharField(label='Unit sector', max_length=255)
            'unit_application': forms.CharField(label='Unit application', max_length=65535)
            'unit_url': forms.URLField(label='Unit URL', max_length=255)
            'superseded_equivalent': forms.CharField(label='Superseded equivalent', max_length=15)
        }

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render

from .models import Unit
from django.views.generic.edit import CreateView, UpdateView

def index(request):
    return HttpResponse("Hello, world. You're at the vcm index.")


def create_unit(request):
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = UnitForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            form.save()
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = UnitForm()

    return render(request, 'vcm/create_unit.html', {'form': form})

My HTML is here /opt/vcm_project/vcm/templates/vcm/create_unit.html

create_unit.html

<form action="{% url 'create_unit' %}" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit"/>
</form>

admin.py

from django.contrib import admin

# Register your models here.
from .models import Unit

admin.site.register(Unit)


from .models import Element

admin.site.register(Element)

Tutorials

Современный Python: начинаем проект с pyenv и poetry

Настройка проекта Python — виртуальные среды и управление пакетами

Использование requests в Python — тайм-ауты, повторы, хуки

Понимание декораторов в Python

ProcessPoolExecutor в Python: полное руководство

map() против submit() с ProcessPoolExecutor в Python

Понимание атрибутов, словарей и слотов в Python

Полное руководство по slice в Python

Выпуск Django 4.0

Безопасное развертывание приложения Django с помощью Gunicorn, Nginx и HTTPS

Автоматический повтор невыполненных задач Celery

Django REST Framework и Elasticsearch

Докеризация Django с помощью Postgres, Gunicorn и Nginx

Асинхронные задачи с Django и Celery

Релизы безопасности Django: 3.2.4, 3.1.12 и 2.2.24

Выпуски исправлений ошибок Django: 3.2.3, 3.1.11 и 2.2.23

Эффективное использование сериализаторов Django REST Framework

Выпуски безопасности Django: 3.2.2, 3.1.10 и 2.2.22

Выпущенные релизы безопасности Django: 3.2.1, 3.1.9 и 2.2.21

Обработка периодических задач в Django с помощью Celery и Docker

View all tutorials →