how to properly configure error handling in template - django

I have a basic form that I'm rendering in template using standard "{{ form.name_of_field.errors }} tags. When I try to submit an empty form, I expect to see the form re-rendered with "•field is required" next to the empty form fields. What I get instead is a Value Error. "The view wedbpjr.wedb.views.display_prdInboxEntry didn't return an HttpResponse object." Where am I going wrong?
<form action="." method="POST">{% csrf_token %}
{{ form.non_field_errors }}
<table id="inbox_table">
<tr>
<td colspan="6">
<div class="fieldWrapper">
{{ form.assigned_by.errors }}
<label for="id_assigned_by">Assigned by:</label>
{{ form.assigned_by }}
</div>
</td>
</tr>
<tr>
<td>
<div class="fieldWrapper">
{{ form.job_number.errors }}
<label for="id_job_number">job no:</label><br />
{{ form.job_number }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.cell_number.errors }}
<label for="id_cell_number">cell:</label><br />
{{ form.cell_number }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.job_name.errors }}
<label for="id_job_name">job name:</label><br />
{{ form.job_name }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.request.errors }}
<label for="id_request">request:</label><br />
{{ form.request }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.note.errors }}
<label for="id_note">note:</label><br />
{{ form.note }}
</div>
</td>
<td>
<div class="container">
<!-- <div class='well'> -->
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
{{ form.date_due.errors }}
<label for="id_date_due">date_due:</label>
{{ form.date_due}}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!-- </div> -->
<script type="text/javascript">
$(function () {
$('#datetimepicker1').datetimepicker();
});
</script>
</div>
</td>
</tr>
<tr>
<td>
<div class="fieldWrapper">
{{ form.box.errors }}
<label for="id_box">inbox:</label><br />
{{ form.box }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.assigned_to.errors }}
<label for="assigned_to">assigned_to:</label><br />
{{ form.assigned_to }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.basecamp_link.errors }}
<label for="id_basecamp_link">basecamp:</label><br />
{{ form.basecamp_link }}
</div>
</td>
<td>
<div class="accepted_by">
{{ form.accepted_by.errors }}
<label for="id_accepted_by">accepted_by:</label><br />
{{ form.accepted_by }}
</div>
</td>
<td>
<div class="fieldWrapper">
{{ form.status.errors }}
<label for="id_status">status:</label><br />
{{ form.status }}
</div>
</td>
<td>
<div class="container">
<!-- <div class='well'> -->
<div class="form-group">
<div class='input-group date' id='datetimepicker2'>
{{ form.completed_on.errors }}
<label for="id_completed_on">completed:</label>
{{ form.completed_on}}
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<!-- </div> -->
<script type="text/javascript">
$(function () {
$('#datetimepicker2').datetimepicker();
});
</script>
</div>
</td>
</tr>
<tr>
<td>
<p><input id="inbox_submit_btn" type="submit" value="add" /></p>
</td>
<td>
<p><input id="inbox_delete_btn" name="delete" type="submit" value="delete" /></p>
</td>
</tr>
</table>
</form>
Running Django 1.5.1 - Python 2.7
views.py
def display_prdInboxEntry(request, id):
if request.method == 'POST':
form = PrdInboxForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/production-display/'+ id +'/')
else:
form = PrdInboxForm()
user = request.user
u = UserProfile.objects.get(pk=id)
creativerecords = InboxEntry.objects.filter(box="Creative")
studiorecords = InboxEntry.objects.filter(box="Studio")
records = InboxEntry.objects.filter(assigned_to=u)
return render_to_response('home_inbox.html', {'form': form, 'records': records, 'studiorecords': studiorecords, 'creativerecords': creativerecords, 'user': user}, context_instance=RequestContext(request))

The errors is coming from your view, Make sure you have a condition for your form.is_valid equaling False. This usually involves reshowing the form with the incorrect data
from django.shortcuts import render
from django.http import HttpResponseRedirect
def contact(request):
if request.method == 'POST': # If the form has been submitted...
# ContactForm was defined in the the previous section
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
The django documentation, clearly explains this

Related

Django CreateView form in modal not show

I have a simple CRUD for a table named Clasificacion. The problem is I would like use a Modal for insert record, but actually I don't use the Django form, instead I declared a normal form with all the fields one by one, but I would like use the From, but is not posible for me show the form content, instead the modal shows empty with the ok button.This table has a model declared as:
class Clasificaciones(models.Model):
clasificacion=models.CharField(max_length=30)
detalles=models.CharField(max_length=1000)
This is How I declared the ListView and the CreateView
class ClasificacionesListView(ListView):
model = Clasificaciones
template_name = 'clasificacion/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de clasificaciones"
return context
class ClasificacionesCreateView(SuccessMessageMixin, CreateView):
model = Clasificaciones
form_class = ClasificacionesForm
template_name = 'clasificacion/index.html'
success_url = reverse_lazy('clasificaciones')
success_message = "Insertado correctamente!!!!"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
and this is the index.html with the modal. The modal is in other directory but not works if I put in the same index.html file
{% extends "starter.html" %}
{% block content %}
<div class="content-wrapper">
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<div class="pull-right">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#modalAddClasificacion">Nueva clasificación</button>
</div>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<section class="content">
<div class="content-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Clasificaciones</h3>
</div>
<div class="card-body">
<table id="tablaClasificaciones" class="table table-bordered table-striped">
<thead>
<tr>
<th>Clasificación</th>
<th>Detalles</th>
<th></th>
</tr>
</thead>
<tbody>
{% for clasificacion in object_list %}
<tr>
<td>{{ clasificacion.clasificacion }}</td>
<td>{{ clasificacion.detalles }}</td>
<td>
<div>
<!-- Detalles -->
Editar
<a class="btn btn-link" data-toggle="modal" data-target="#deleteClasificacionModal{{clasificacion.id}}"><span class="fas fa-trash text-danger"></a>
{% include 'clasificacion/modals/delete_modal.html' %}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th>Clasificación</th>
<th>Detalles</th>
<th></th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
{% include 'clasificacion/modals/add_modal.html' %}
{% endblock %}
and the modal code, commented the inputs, this way works, but I would like use form
<div class="modal fade" id="modalAddClasificacion">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Adicionar clasificación</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<form id="addclasificacion" method="POST">
{% csrf_token %}
<div class="row">
{% for field in form.visible_fields %}
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>{{ field.label }}</strong>
{{ field }}
</div>
</div>
{%endfor%}
<!-- <div class="col-12">
<div class="form-group">
<strong>Clasificación:</strong>
<input type="text" name="clasificacion" class="form-control" placeholder="Clasificación">
</div>
</div>
<div class="col-12">
<div class="form-group">
<strong>Detalles:</strong>
<textarea class="form-control" style="height:150px" name="detalles" placeholder="Detalles"></textarea>
</div>
</div> -->
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Insertar</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
It not works because I must add to context variable the form, in this case the Form to Categoria model. Also I must add to Create form, because I don't use a create template.
So this is the answer:
class ClasificacionesListView(ListView):
model = Clasificaciones
template_name = 'clasificacion/index.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Lista de clasificaciones"
context['form'] = ClasificacionesForm()#here the detail.
return context

how can ı submit more than one row in django view with table form

ı wanna submit more than one record but in that code only first student can be record how can ı add more than one record in django view ı am prety new in django can anyone help about that table image
thats the model.py
class GonulluOgrenciDevamsizlik(models.Model):
ogrenci_dersi = models.ForeignKey('Ogrenci', null=True, on_delete=models.SET_NULL)
gonulu = models.ForeignKey('Gonullu', null=True, on_delete=models.SET_NULL)
devamsizlik = models.BooleanField(verbose_name="Devamsızlık Bilgisi",blank=True, default=False)
sinif = models.ForeignKey('SinifListe', null=True, on_delete=models.SET_NULL)
olusturma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Oluşturma Tarihi')
guncelleme_tarihi = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-devamsizlik']
verbose_name = 'Devamsızlık'
verbose_name_plural = 'Devamsızlıklar'
def __str__(self):
return self.gonulu.ad + ' ' + self.gonulu.soyad
here is my view: in view ı had been add required foreign keys for my table and then try to save coming post data from table form.
def ogrencidevamsizlik(request, id):
details = "hesabim/ogrenci-devamsizlik.html"
siniflar = SinifListe.objects.filter(gonullu__gonullu__email=request.user.email)
ogrenci = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email)
gonulu = GonulluDersleri.objects.get(gonullu__email__iexact=request.user.email, id=id)
gonulluler = Gonullu.objects.get(email__iexact=request.user.email)
ders = GonulluDersleri.objects.filter(gonullu__email=request.user.email, id=id)
devamsizliklar = SinifDetay.objects.filter(sinif__gonullu__gonullu__email=request.user.email, sinif__gonullu__id=id)
if request.method == 'POST':
form = DevamsizlikDetayForm(request.POST, request.FILES)
if form.is_valid():
form.save()
messages.success(request, 'Devamsızlıklar başarılı bir şekilde eklendi.')
return redirect('gonullu-siniflar')
else:
messages.error(request, 'Devamsızlık bilgilerinizdeki zorunlu alanları eksiksiz doldurmalısınız.')
else:
form = DevamsizlikDetayForm()
context = {'devamsizliklar': devamsizliklar,
'gonulu': gonulu,
'ders': ders,
'form': form,
'ogrenci': ogrenci,
'siniflar': siniflar,
'gonulluler': gonulluler}
return render(request, details, context)
and here is my table: in table ı try to add devamsizlik area for each student , gonulu , ogrenci and sinif ıd are already coming with views info but devamsizlik will submited by the gonullu so ı made a for loop for all student but when ı submit only first one can be submit thats the promlem
<form class="" novalidate method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.title }}
<div class="row justify-content-center">
<div class="col-12 col-md-9 mt-3 ">
<div class="font-weight-bold align-center">Gönüllü Dersi :
{% for x in ders %}
{{ x.gonullu }} {% if x.birinci_ders != null %} {{ x.birinci_ders }} {{ x.birinci_ders_seviye }} {% endif %}
{% endfor %}
</div>
</div>
</div>
<div class="row justify-content-center">
<table class="table table-hover">
<thead>
<tr data-toggle="collapse" data-target="#accordion" class="clickable">
<th scope="col">Id</th>
<th scope="col">Öğrenci</th>
<th scope="col">Sınıf</th>
<th scope="col">Aktif</th>
<th scope="col">Devamsızlık</th>
</tr>
</thead>
<tbody>
{% for y in devamsizliklar %}
<tr>
<td id="accordion" class="collapse">{{ y.id }}</td>
<td id="accordion" class="collapse">{{ y.ogrenci }}</td>
<td id="accordion" class="collapse">{{ y.sinif }}</td>
<td id="accordion" class="collapse">{{ y.aktif }}</td>
<td id="accordion" class="collapse">
<div class="form-group row">
<div class="col-sm-10 col-md-7">
<input data-handle-width="20" data-label-width="1" data-size="mini"
{{ form|validation_class:"devamsizlik" }} id="devamsizlik" name="devamsizlik"
{% if form.devamsizlik.value %}checked{% endif %} class="form-control swich-check"
type="checkbox">
{{ form.devamsizlik|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">
<label for="gonulu" class="col-sm-2 col-md-5 col-form-label">Gönüllü*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"gonulu" }}" name="gonulu"
id="gonulu" required>
<option value="{{ gonulu.gonullu.pk }}" selected="selected">{{ gonulu.gonullu|safe }}</option>
</select>
{{ form.gonulu|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Öğrenci*</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"ogrenci_dersi" }}" name="ogrenci_dersi"
id="ogrenci_dersi" required>
<option value="{{ y.ogrenci.ogrenci.pk }}" selected="selected">{{ y.ogrenci.ogrenci|safe }}</option>
</select>
{{ form.ogrenci_dersi|f_errors }}
</div>
</div>
<div class="form-group row" style="visibility: hidden; display: none">>
<label for="ad" class="col-sm-2 col-md-5 col-form-label">Sınıf</label>
<div class="col-sm-10 col-md-7">
<select class="custom-select my-1 mr-sm-2 {{ form|validation_class:"sinif" }}" name="sinif"
id="sinif" required>
{% for x in siniflar %}
<option value="{{ x.pk }}" selected="selected">{{ x|safe }}</option>
{% endfor %}
</select>
{{ form.sinif|f_errors }}
</div>
</div>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!--submit-->
<div class="row justify-content-center">
<button type="submit" name="save" value="save"
class="btn btn-primary mb-2 float-left bg-c b-0 rounded-0">
Devamsızlık bilgilerimi güncelle
</button>
</div>
</form>
And thats is the form.py
class DevamsizlikDetayForm(forms.ModelForm):
class Meta:
model = GonulluOgrenciDevamsizlik
fields = '__all__'

Field 'id' expected a number but got 'product_id' django [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
In my ecommerce app when I click on add to cart the product goes to the cart but when I click on the cart it gives me the error that 'Field 'id' expected a number but got 'product_id''. Basically I use context_processor to pass the cart.py information to the template.
Link to the cart from base.html is:
<div class="navbar-item">
Cart {% if cart %}({{cart|length}}){% endif %}
</div>
When I click on cart this error is generated:
Field 'id' expected a number but got 'product_id'
my project/urls.py is
path('cart/',include("cart.urls")),
my cart/urls.py is
urlpatterns = [
path('',views.cart_detail, name='cart')
]
my cart/cart.py is
from django.conf import settings
from product.models import Product
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def __iter__(self):
for p in self.cart.keys():
self.cart[(p)]['product'] = Product.objects.get(pk=p)
for item in self.cart.values():
item['total_price'] = item['product'].price * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def add(self, product_id, quantity=1, update_quantity=False):
product_id = str(product_id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 1, 'id': product_id}
if update_quantity:
self.cart[product_id]['quantity'] += int(quantity)
if self.cart[product_id]['quantity'] == 0:
self.remove(product_id)
self.save()
print(self.cart)
def remove(self, product_id):
if product_id in self.cart:
del self.cart[product_id]
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
def get_total_cost(self):
for p in self.cart.keys():
self.cart[str(p)]['product'] = Product.objects.get(pk=p)
return sum(item['quantity'] * item['product'].price for item in self.cart.values())
my context_processors.py is
def cart(request):
return {'cart': Cart(request)}
and my cart.html is:
{% extends 'core/base.html' %}
{% block title %}Cart | {% endblock %}
{% block content %}
<h1 class="title">Cart</h1>
{% if cart %}
<div class="box mb-6">
<div class="table">
<table class="table is-fullwidth is-striped">
<thead>
<th></th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th></th>
</thead>
<tbody>
{% for item in cart %}
<tr>
<td>
<figure class="image is-64x64">
<img src="{{ item.product.get_thumbnail }}">
</figure>
</td>
<td>
{{ item.product.title }}
</td>
<td>
{{ item.quantity }}
-
+
</td>
<td>${{ item.total_price }}</td>
<td>Remove</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td></td>
<td><strong>Total cost</strong></td>
<td><strong>{{ cart|length}}</strong></td>
<td colspan="2"><strong>${{ cart.get_total_cost }}</strong></td>
</tr>
</tfoot>
</table>
</div>
</div>
<h2 class="subtitle">Contact information</h2>
<form method="post" action="." id="payment-form">
{% csrf_token %}
{% if form.non_field_errors %}
<div class="notification is-danger">
{{ form.non_field_errors}}
</div>
{% endif %}
{% if form.errors %}
<div class="notification is-danger">
<ul>
{% for field in form %}
{% for error in field.errors %}
<li><strong>{{ field.label }}: </strong>{{ error }}</li>
{% endfor %}
{% endfor %}
</ul>
</div>
{% endif %}
<div class="columns">
<div class="column is-6">
<div class="field">
<label>First name</label>
<div class="control">
<input class="input" type="text" name="first_name">
</div>
</div>
<div class="field">
<label>Last name</label>
<div class="control">
<input class="input" type="text" name="last_name">
</div>
</div>
<div class="field">
<label>E-mail</label>
<div class="control">
<input class="input" type="email" name="email">
</div>
</div>
<div class="field">
<label>Phone</label>
<div class="control">
<input class="input" type="text" name="phone">
</div>
</div>
</div>
<div class="column is-6">
<div class="field">
<label>Address</label>
<div class="control">
<input class="input" type="text" name="address">
</div>
</div>
<div class="field">
<label>Zip code</label>
<div class="control">
<input class="input" type="text" name="zipcode">
</div>
</div>
<div class="field">
<label>Place</label>
<div class="control">
<input class="input" type="text" name="place">
</div>
</div>
</div>
</div>
</form>
<h2 class="subtitle">Payment information</h2>
<div id="card-element">
<!-- A Stripe Element will be inserted here -->
</div>
{% if messages %}
{% for message in messages %}
<div class="notification is-danger">{{ message }}</div>
{% endfor %}
{% endif %}
<div class="field">
<div class="control">
<button class="button is-dark mt-4 is-uppercase">Checkout</button>
</div>
</div>
</div>
{% else %}
<p>You don't have any products in your cart!</p>
{% endif %}
{% endblock %}
Aren't you casting the product_id to a string with str(product_id) ? And later you're passing it as an number but it's still an string. In cart.py and function add
The answer is I did not clear cookies. As I clear those o the code
change this:
{'quantity': 1, 'id': product_id}
with this
{'quantity': 1, 'id': int(product_id)}

How to list the id with getlist method in Django checkbox

html file
Here I list the client and Process in the input tag
And select the and submit
{% extends 'client_pannel.html' %}
{% block content %}
<script>
function postConfirm() {
if (confirm('Are you sure you want to delete this client')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
<form method="POST">
{% csrf_token %}
<div class="breadcome-area">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="breadcome-list single-page-breadcome">
<div class="row">
<div class="col-lg-10 col-md-6 col-sm-6 col-xs-12">
<div class="breadcome-heading">
<form role="search" class="sr-input-func">
<label>{{ emp.first_name }} {{ emp.last_name }}</label>
</form>
</div>
</div>
<div class="col-lg-2 col-md-6 col-sm-6 col-xs-12">
<a href="/employee_list/"> <button type="submit"
class="btn btn-info add-new">Submit</button></a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="data-table-area mg-b-15">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="sparkline13-list">
<div class="sparkline13-graph">
<div class="datatable-dashv1-list custom-datatable-overright">
<table id="table" data-toggle="table" data-pagination="true" data-search="true"
data-show-columns="true" data-show-pagination-switch="true" data-show-refresh="true"
data-key-events="true" data-show-toggle="true" data-resizable="true"
data-cookie="true" data-cookie-id-table="saveId" data-show-export="true"
data-click-to-select="true" data-toolbar="#toolbar">
<thead>
<tr>
<th>Process</th>
</tr>
</thead>
<tbody>
{% for client in form %}
<tr>
<td>
<input type="checkbox" name="cname[]" value="{{ client.id }}">
{{ client.Name }}
</td>
<td>
{% for process in client.clients %}
<input type="checkbox" name="process[]" value="{{ process.id }}">
{{ process.process }}<br />
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
{% endblock %}
views file
The below code is get the selected in checkbox. The getlist method return nothing
if request.method == "POST":
cname = request.POST.getlist('cname[]')
print("cname", cname)
process = request.POST.getlist('process[]')
print("process", process)

unable to update the fields in model Django

I am trying to edit user details of a specific user when admin logins its going to edit page but when I press the update button it's not updating not showing any error message. (correct me please if I am wrong).
This is my edit.html
{% extends 'base.html' %}
{% block title %}edit details{% endblock %}
{% block content %}
{% if emp %}
<form method="POST" class="form-inline my-2 my-lg-0" ">
{% csrf_token %}
<div class="container">
<br>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<h3>Update Details</h3>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee User:</label>
<div class="col-sm-4">
<input type="text" id="id_user" required maxlength="20" value="{{
emp.user }}"/>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee first_name:</label>
<div class="col-sm-4">
<input type="search" id="id_first_name" required maxlength="100"
value="{{ emp.first_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee last_name:</label>
<div class="col-sm-4">
<input type="text" id="id_last_name" required maxlength="100" value="{{
emp.last_name }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Email:</label>
<div class="col-sm-4">
<input type="email" id="id_email" required maxlength="254" value="{{
emp.email }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Gender:</label>
<div class="col-sm-4">
<input type="text" id="id_gender" required maxlength="15" value="{{
emp.gender }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee Age:</label>
<div class="col-sm-4">
<input type="text" id="id_age" required maxlength="100" value="{{
emp.age }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Employee salary:</label>
<div class="col-sm-4">
<input type="text" name="ename" id="id_salary" required maxlength="100"
value="{{ emp.salary }}" />
</div>
</div>
<div class="form-group row">
<label class="col-sm-1 col-form-label"></label>
<div class="col-sm-4">
<button type="submit" class="btn btn-success">Update</button>
</div>
</div>
</div>
</form>
{% endif %}
{% endblock %}
This is my profile.html page
{% if user.is_authenticated %}
{% if user.is_superuser %}
<table class="table table-striped table-bordered table-sm">
<thead class="thead-dark">
<tr>
<th>Employee User</th>
<th>Employee first_name</th>
<th>Employee last_name</th>
<th>Employee Email</th>
<th>Employee Gender</th>
<th>Employee Age</th>
<th>Employee Salary</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for employee in employees %}
<tr>
<td>{{ employee.user }}</td>
<td>{{ employee.first_name }}</td>
<td>{{ employee.last_name }}</td>
<td>{{ employee.email }}</td>
<td>{{ employee.gender }}</td>
<td>{{ employee.age }}</td>
<td>{{ employee.salary }}</td>
<td>
<a href="{% url 'edit' employee.id %}"><span class="glyphicon
glyphicon-pencil" >Edit</span></a>
Delete
</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<br>
<center><a href="{% url 'signup' %}" class="btn btn-primary">Add New
Record</a></center>
{% else %}
<p>username : {{ user }}</p>
<p>firstname : {{ user.first_name }}</p>
<p>lastname : {{ user.last_name }}</p>
<p>{{user.employee.age}}</p>
<p>
Edit details
</p>
<p>
Change password
</p>
{% endif %}
{% endif %}
This is view.py of edit method
def edit(request, emp_id):
if request.method == 'POST':
emp = employee.objects.get(pk=emp_id)
form = EmployeForm(request.POST or None, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
return HttpResponseRedirect('view_profile')
else:
emp = employee.objects.get(pk=emp_id)
return render(request, 'edit.html', {'emp': emp})
def view_profile(request):
employees = employee.objects.all()
args= {'user':request.user,'employees':employees}
return render(request,'profile.html',args)
This is my model page
class employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=50)
gender = models.CharField(max_length=1,choices=(('M','Male'),
('F','Female')),blank=True)
age = models.PositiveIntegerField(blank=True, null=True)
salary = models.CharField(blank = True,max_length=50
def __str__(self):
return self.user.username
Please, any advice on how to troubleshoot or any documentation I can read.
You're not using the form properly. Forms are not only for validation, they are also responsible for rendering the error messages. You want to change your view to pass the form to the template:
def edit(request, emp_id):
emp = employee.objects.get(pk=emp_id)
if request.method == 'POST':
form = EmployeForm(request.POST, instance=emp)
if form.is_valid():
form.save()
messages.success(request, ('Item has been edited'))
# this one is probably not going to work
# as expected - you may want to check the
# doc for the `redirect` shortcut instead
return HttpResponseRedirect('view_profile')
else:
form = EmployeForm(instance=emp)
return render(request, 'edit.html', {'emp': emp, 'form':form})
Then in your template instead of manually writing the whole form markup, use the form for rendering so you have the validation errors correctly displayed.