reverse : 함수형 뷰에서 사용
reverse_lazy : 클래스 기반 뷰에서 사용
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
from django.urls import reverse, reverse_lazy
from django.views.generic import CreateView
from accountapp.models import HelloWorld
def hello_world(request):
if request.method == "POST":
temp = request.POST.get('hello_world_input')
new_hello_world = HelloWorld()
new_hello_world.text = temp
new_hello_world.save()
hello_world_list = HelloWorld.objects.all()
return HttpResponseRedirect(reverse('accountapp:hello_world'))
else:
hello_world_list = HelloWorld.objects.all()
return render(request, 'accountapp/hello_world.html', context={'hello_world_list': hello_world_list})
class AccountCreateView(CreateView):
model = User
form_class = UserCreationForm
success_url = reverse_lazy('accountapp:hello_world')
template_name = 'accountapp/create.html'
Python
복사
views.py
함수형 뷰에서는 urls.py에 함수이름을 써서 그냥 넣어주면 되는데
클래스에서는 뒤에 as.view() 붙여서 써야함
from django.urls import path
from accountapp.views import hello_world, AccountCreateView
app_name = "accountapp"
urlpatterns = [
path('hello_world/',hello_world, name='hello_world'),
path('create/', AccountCreateView.as_view(), name='create'),
]
Python
복사
{% extends 'base.html' %}
{% block content %}
<div style="text-align: center">
<form action="{% url 'accountapp:create' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="'submit" class="btn btn-primary">
</form>
</div>
{% endblock %}
HTML
복사
create.html