본문 바로가기
개발일지/Django

Django - ModelForms

by 다니엘의 개발 이야기 2022. 10. 1.
320x100

# 첫번째 파일

mysite > cars > models.py

from django.db import models

# Create your models here.
class Review(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    stars = models.IntegerField()

# 두번째 파일

mysite > cars > admin.py

from django.contrib import admin
from .models import Review

# Register your models here.
admin.site.register(Review)

# 세번째 파일

mysite > cars > views.py

from django.shortcuts import render, redirect
from django.urls import reverse
from .forms import ReviewForm

# Create your views here.
def rental_review(request):

    # POST REQUEST --> form contents --> thank_you
    if request.method == 'POST':
        form = ReviewForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect(reverse('cars:thank_you'))

    # ELSE, RENDER Form
    else:
        form = ReviewForm()

    return render(request, 'cars/rental_review.html', context = {'form':form})

def thank_you(request):
    return render(request, 'cars/thank_you.html')

# 네번째 파일

mysite > cars > forms.py

from django import forms
from .models import Review
from django.forms import ModelForm

'''
class ReviewForm(forms.Form):
    first_name = forms.CharField(label = 'First Name', max_length=100)
    last_name = forms.CharField(label = 'Last Name', max_length=100)
    email = forms.EmailField(label = 'Email')
    review = forms.CharField(label = 'Please write your review here', 
                            widget=forms.Textarea(attrs={
                                                    'class': 'myform',
                                                    'rows':'2',
                                                    'cols':'2'}))
'''

class ReviewForm(ModelForm):
    class Meta:
        model = Review
        fields = ['first_name', 'last_name', 'stars']
300x250