我正在尝试在网站首页上创建一个usercreationform。在阅读并观看了有关用户创建的教程之后,我注意到每个人都为“注册”创建了单独的HTML页面,但是,我希望我的注册页面直接位于我的主页上-这可能吗?我发现很难通过拥有自己独立应用程序的“帐户”以及拥有自己独立应用程序的首页来理解,我称之为“游戏”。两个应用程序必须分开吗?我可以将帐户应用程序设为主要的“主页”应用程序吗?
有人可以推荐有关此的任何教程吗?我想我也应该提到我对django很陌生。谢谢。
我的首页应用(标题游戏) urls.py:
from django.contrib import admin
from django.urls import path
from.import views
urlpatterns = [
path('', views.game_start),
]
views.py:
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from .models import Game
def game_start(request):
games = Game.objects.all().order_by('date') # grabs all records in game in db table, order by date
return render (request, 'game/game_start.html', {'games':games})
def signup_view(request):
form = UserCreationForm()
return render(request, 'game/game_start.html', {'form': form})
accounts / urls.py:
from django.conf.urls import url
from .import views
app_name = 'accounts'
urlpatterns = [
path('', game_views.game_start, name="home"),
]
accounts / views.py:
from django.http import HttpResponse
from django.shortcuts import render
def about(request):
# return HttpResponse('Price is right game one')
return render(request, 'about.html')
答案 0 :(得分:1)
我希望注册页面直接位于我的主页上-这有可能吗?
是的,您可以在帐户应用中定义自定义signup
函数,然后将其导入到首页应用中,如下所示:
accounts / views.py:
def signup(request):
data = {'form':None, 'user_created': False}
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
# do soemthing with the registered user
data['user_created'] = True
else:
form = UserCreationForm()
data['form'] = form
return data
homepage / views.py:
from accounts.views import signup
def game_start(request):
games = Game.objects.all().order_by('date')
data = {'msg': ''}
response = signup(request)
if response['user_created']:
# you can redirect user here to somewhere else when they have been registered.
data['msg'] = 'Thanks for being the part of our beautiful community!'
return render(request, 'game/game_start.html', {
'games':games,
'form': response['form'],
'msg': data['msg']
})
game_start.html:
<p>{{msg}}</p>
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Sign Up</button>
</form>
两个应用程序必须分开吗?
好吧,您可以将它们都放在一个应用程序中,但由于以下原因,我们不建议这样做:
如果您难以理解django中的应用程序,那么只需看一下我的回答here
答案 1 :(得分:0)
您可以在“ game_start.html”模板中添加表单:
{% if not user.is_authenticated %}
<form role="form"
action="{% url 'player_login' %}"
method="post">
{% csrf_token %}
<p>Please login.</p>
{{ form.as_p }}
<button type="submit">Sign in</button>
</form>
{% endif %}
这假设您有一个命名的URL模式player_login
。