12. Django Python – User Form

django python bahasa indonesia

Buat view untuk tambah user.

from django.contrib.auth.forms import UserCreationForm

def tambah_user(request):
   if request.POST:
       form = UserCreationForm(request.POST)
       if form.is_valid():
           form.save()
           messages.success(request, "Berhasil menambahkan user!")
           return redirect('tambah_user')
       else:
           messages.error(request, "Terjadi kesalahan!")
           return redirect('tambah_user')
    else:
       form = UserCreationForm()
       context = {
           'form': form,
       }
       return render(request, 'tambah-user.html', context)

Edit html.

{% extends 'base.html' %}

{% block content %}
...
     {% for message in messages %}
         {% if message.tag == 'success' %}
             <div class="alert alert-success">{{ message }}</div>
         {% else %}
             <div class="alert alert-danger">{{ message }}</div>
         {% endif %}
     {% endfor %}
...
         <form action="{% url 'tambah_user' %}" method="post">
             {% csrf_token %}
             {{ form.as_p }}
             <button class="btn btn-primary">Tambah</button>
             <a href="{% url 'siswa' %}" class="btn btn-light">Kembali</a>
         </form>
...
{% endblock content %}

Tambahkan URL.

urlpatterns = [
    ...
    path('user/tambah/', tambah_user, name='tambah_user'),
]


Lanjutkan Membaca Materi Lengkap


Leave a Reply

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

10 − 10 =

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