我是Django的新手,并且正在关注有关创建用户注册页面的教程。但是,当我运行服务器时,表单字段不会出现,只有“注册”按钮在那里。
我浏览了许多教程,并试图更改UserForm
类,以为那是问题所在,但我遇到了同样的问题。
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ["username", "email", "password"]
views.py
...
class UserFormView(View):
form_class = UserForm
template_name = 'static/register.html'
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {"form":form})
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
#creates an object frm the form but doesnt save it into the database
user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()
#returns object if credenials are correct
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('main:homepage')
return render(request, self.template_name, {"form":form})
urls.py
from django.urls import path
from . import views
from django.conf.urls import url, include
app_name = "main"
urlpatterns = [
path("", views.homepage, name="homepage"),
path("register/", views.UserFormView.as_view(), name='register'),
]
register.html
{% extends 'static/header.html' %}
{% block content %}
<br>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button style="background-color:#F4EB16; color:blue" class="btn btn-outline-info" type="submit">Sign Up</button>
</form>
If you already have an account <a href="/login" target="blank"><strong>login</strong></a> instead.
{% endblock %}
header.html
<html>
<head>
{% load static %}
</head>
<body>
<nav>
<div style="background-color:green;">
<a href="#" class="brand-logo">Title</a>
</div>
</nav>
{% block content %}
{% endblock %}
</body>
</html>
settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'main.apps.MainConfig',
]
...
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
我开始认为这个问题与其中一个html代码有关,但看起来与教程中的代码相同。