Update View 구현하기 : Create View랑 똑같음
Change Info 들어갔을 때 username 칸 비활성화 시켜주는 작업 필요
views.py의 UserCreationForm을 상속 받아서 커스터마이징
from django.contrib.auth.forms import UserCreationForm
class AccountUpdateForm(UserCreationForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].disabled = True
Python
복사
forms.py
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, DetailView, UpdateView
from accountapp.forms import AccountUpdateForm
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'
class AccountDetailView(DetailView):
model = User
context_object_name = 'target_user'
template_name = 'accountapp/detail.html'
class AccountUpdateView(UpdateView):
model = User
form_class = AccountUpdateForm
success_url = reverse_lazy('accountapp:hello_world')
template_name = 'accountapp/update.html'
Python
복사
views.py
from django.contrib.auth.views import LoginView, LogoutView
from django.urls import path
from accountapp.views import hello_world, AccountCreateView, AccountDetailView, AccountUpdateView
app_name = "accountapp"
urlpatterns = [
path('hello_world/',hello_world, name='hello_world'),
path('login/', LoginView.as_view(template_name='accountapp/login.html'), name='login'),
path('logout/',LogoutView.as_view(), name='logout'),
path('create/', AccountCreateView.as_view(), name='create'),
path('detail/<int:pk>', AccountDetailView.as_view(), name='detail'),
path('update/<int:pk>', AccountUpdateView.as_view(), name='update'),
]
Python
복사
urls.py
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block content %}
<div style="text-align: center; max-width: 500px; margin: 4rem auto">
<div class="mb-4">
<h4>Change Info</h4>
</div>
<form action="{% url 'accountapp:update' pk=user.pk %}" method="post">
{% csrf_token %}
{% bootstrap_form form %}
<input type="submit" class="btn btn-dark rounded-pill col-6 mt-3">
</form>
</div>
{% endblock %}
HTML
복사
update.html