8. Django Python – Model Form

django python bahasa indonesia

1. Model Form

Buat file forms.py.

from django.forms import ModelForm
from apps.apps01.models import Siswa

class FormSiswa(ModelForm):
   class Meta:
      model = Siswa
      fields = '__all__'

Buat views untuk tambah siswa.

from apps.apps01.forms import FormSiswa

def tambah_siswa(request):
   form = FormSiswa
   context = {
              'form': form,
   }

return render(request, 'tambah-siswa.html', context)

Buat file tambah-siswa.html.

{% extends "base.html" %}

{% block content %}
    <form action="" method="POST" accept-charset="utf-8">
      {{ form.as_p }}
    <button>Tambah</button>
    </form>
{% endblock content %}

Buat url untuk tambah_siswa.

urlpatterns = [
    ...
    ...
    path('siswa-tambah/', tambah_siswa, name='tambah_siswa'),
]

2. Menentukan Form yang Ditampilkan

Edit file forms.py.

from django.forms import ModelForm
from apps.apps01.models import Siswa

class FormSiswa(ModelForm):
   class Meta:
       model = Siswa
       fields = [‘nomor’,’nama_lengkap’]

3. Exclude Form yang Ditampilkan

Edit file forms.py.

from django.forms import ModelForm
from apps.apps01.models import Siswa

class FormSiswa(ModelForm):
   class Meta:
      model = Siswa
      exclude = [‘nomor’]

4. Widgets

Edit file forms.py.

from django import forms

class FormSiswa(ModelForm):
   class Meta:
      model = Siswa
      fields = '__all__'

      widgets = {
       'nomor': forms.NumberInput({'class':'form-control'}),
       'nama_depan': forms.TextInput({'class':'form-control'}
       'nama_belakang': forms.TextInput({'class':'form-control'}),
       'tgl_lahir': forms.DateInput({'class':'form-control','type':'date'}),
       'alamat': forms.TextInput({'class':'form-control'}),
       'jurusan': forms.Select({'class':'form-control'}),
       }

Buat file tambah-siswa.html.

{% extends "base.html" %}

{% block content %}
<div class="container">
   <div class="row">
      <form action="" method="POST" accept-charset="utf-8">        {{ form.as_p }}
         <button>Tambah</button>
      </form>
   </div>
</div>
{% endblock content %}


Lanjutkan Membaca Materi Lengkap


Leave a Reply

Your email address will not be published. Required fields are marked *

13 + sixteen =

This site uses Akismet to reduce spam. Learn how your comment data is processed.