I’m trying to add a staff with django everything seems to be working fine i even see the entry in the database but once i click the submit button instead message.success i get message.error i cant seem to figure out the issue.
This is what my form for add_staff template looks like
<form role="form" method="post" action="/add_staff_save">
{% csrf_token %}
<div class="card-body">
<div class="form-group">
<label>Email address</label>
<input type="email" class="form-control" name="email" placeholder="Enter email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<div class="form-group">
<label>Firstname</label>
<input type="text" class="form-control" name="first_name" placeholder="First Name">
</div>
<div class="form-group">
<label>Lastname</label>
<input type="text" class="form-control" name="last_name" placeholder="Last Name">
</div>
<div class="form-group">
<label>Username</label>
<input type="text" class="form-control" name="username" placeholder=" User Name">
</div>
<div class="form-group">
<label>Address</label>
<input type="text" class="form-control" name="address" placeholder="Address">
</div>
</div>
<div class="form-group">
{% if messages %}
{% for message in messages %}
{% if message.tags == 'success' %}
<div class="alert alert-success" style="margin-top:10px">
{{ message }}
</div>
{% endif %}
{% if message.tags == 'error' %}
<div class="alert alert-danger" style="margin-top:10px">
{{ message }}
</div>
{% endif %}
{% endfor %}
{% endif %}
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary btn-block">Add Staff</button>
</div>
</form>
This is my views.py and the function that handles adding staff
from student_management_app.models import CustomUser, Staffs
from django.contrib import messages
def add_staff_save(request):
if request.method!=”POST”:
return HttpResponse(“Method Not Allowed!”)
else:
first_name=request.POST.get(“first_name”)
last_name=request.POST.get(“last_name”)
username=request.POST.get(“username”)
email=request.POST.get(“email”)
password=request.POST.get(“password”)
address=request.POST.get(“address”)
try:user=CustomUser.objects.create_user(username=username,password=password,email=email,l
ast_name=last_name,first_name=first_name,user_type=2)
user.staffs.address=address
user.save()
messages.success(request,"Successfully added Staff")
return HttpResponseRedirect("/add_staff")
except:
messages.error(request,"Failed to add staff")
return HttpResponseRedirect("/add_staff")
urls.py
path(‘add_staff’,HodViews.add_staff),
path(‘add_staff_save’,HodViews.add_staff_save),