1. ModelForm
위젯 속성을 이용해서 부트스트랩 클래스인 'form-control' 추가하기
class MovieForm(forms.ModelForm):
GENRES = (
('comedy', 'comedy'),
('horror', 'horror'),
('romance', 'romance')
)
genre = forms.ChoiceField(choices=GENRES,
widget = forms.Select(
attrs = {
'class':'form-select',
}
)
)
release_date = forms.DateField(
widget = forms.DateInput(
attrs={
'type' : 'date',
'class': 'form-control',
}
)
)
score = forms.FloatField(
widget = forms.NumberInput(
attrs={
'step' : 0.5,
'max' : 5,
'min' : 0,
'class': 'form-control',
'placeholder' : 'Score',
}
),
)
audience = forms.IntegerField(
widget = forms.NumberInput(
attrs={
'class': 'form-control',
'placeholder' : 'Audience',
}
),
)
title = forms.CharField(
widget = forms.TextInput(
attrs={
'class' : 'form-control',
'placeholder' : 'Title'
}
)
)
poster_url = forms.CharField(
widget = forms.Textarea(
attrs={
'class' : 'form-control',
'placeholder' : 'Poster url'
}
)
)
description = forms.CharField(
widget = forms.Textarea(
attrs={
'class' : 'form-control',
'placeholder' : 'Description'
}
)
)
# audience, poster_url
class Meta:
model = Movie
fields = '__all__'
-> 부트스트랩이 적용된 화면을 볼 수 있다.
2. 영화 수정 페이지
요구사항 1 : HTML input 요소에는 기존의 데이터 출력
# views.py
def update(request, pk):
movie = Movie.objects.get(pk=pk)
if request.method == 'POST':
# 기존의 데이터를 인스턴스 값으로 넘겨줌
form = MovieForm(request.POST, instance=movie)
if form.is_valid():
form.save()
return redirect('movies:detail', movie.pk)
else:
form = MovieForm(instance=movie)
context = {
'form' : form,
'movie' : movie,
}
return render(request, 'movies/update.html', context)
요구사항 2 : cancel 버튼은 사용자의 모든 입력을 초기 값으로 재설정
<input class="btn btn-primary" type="reset" value="Cancel">
-> 각 항목의 값을 초기화 해주는 type='reset' 적용
3. 회원가입, 로그인, 로그아웃
>> accounts app
# models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
# AbstractUser를 상속받는 커스텀 User 클래스 작성
# 기존의 User 클래스도 AbstractUser를 상속받기 때문에 커스텀 User도 완전히 같은 모습
class User(AbstractUser):
pass
# forms.py
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
class CustomUserCreationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = UserCreationForm.Meta.fields + ('email',)
class CustomUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model = get_user_model()
fields = ('email', 'first_name', 'last_name',)
# views.py
from django.contrib.auth import login as auth_login
from django.contrib.auth import logout as auth_logout
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
from django.shortcuts import redirect, render
from django.views.decorators.http import require_http_methods, require_POST
from .forms import CustomUserChangeForm, CustomUserCreationForm
# Create your views here.
@require_http_methods(['GET', 'POST'])
def login(request):
if request.user.is_authenticated:
return redirect('movies:index')
if request.method == 'POST':
form = AuthenticationForm(request, request.POST)
# form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
# 로그인
auth_login(request, form.get_user())
return redirect(request.GET.get('next') or 'movies:index')
else:
form = AuthenticationForm()
context = {
'form': form,
}
return render(request, 'accounts/login.html', context)
@require_POST
def logout(request):
if request.user.is_authenticated:
auth_logout(request)
return redirect('movies:index')
@require_http_methods(['GET', 'POST'])
def signup(request):
if request.user.is_authenticated:
return redirect('movies:index')
if request.method == 'POST':
form = CustomUserCreationForm(request.POST)
if form.is_valid():
user = form.save()
# 회원가입 후 로그인
auth_login(request, user)
return redirect('movies:index')
else:
form = CustomUserCreationForm()
context = {
'form': form,
}
return render(request, 'accounts/signup.html', context)
가을 옷을 꺼내 입어도 조금 쌀쌀한 날씨!
'Web > Django' 카테고리의 다른 글
DRF - Single Model (0) | 2022.10.17 |
---|---|
URL (0) | 2022.10.17 |
실습 - 1:N 을 활용한 app 작성 (0) | 2022.10.06 |
쿠키와 세션 (0) | 2022.09.08 |
Django Form (0) | 2022.09.07 |
댓글