Reputation: 292
models.py
from django.db import models
from .validator import validate_age
# Create your models here.
class City(models.Model):
city_name=models.CharField(max_length=200)
def __str__(self):
return self.city_name
class Employee(models.Model):
name = models.CharField(max_length=200)
pan_number = models.CharField(max_length=200, unique=True, null=False, blank=False)
age = models.IntegerField(validators=[validate_age])
gender = models.CharField(max_length=10)
email = models.EmailField()
city = models.ForeignKey(City, on_delete=models.DO_NOTHING)
def __str__(self):
return self.name
def clean(self):
if self.name:
self.name =self.name.strip()
views.py
def employee(request):
context = {}
if request.POST:
form = EmployeeForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
pan_number = form.cleaned_data['pan_number']
email = form.cleaned_data['email']
age = form.cleaned_data['age']
city = form.cleaned_data['city']
gender = form.cleaned_data['gender']
print(city)
with connection.cursor() as cursor:
cursor.callproc('insert_employee', [name, pan_number, age, gender, email, city])
# qs_add = Employee(name=name, pan_number=pan_number, email=email, age=age, city=city, gender=gender)
# qs_add.save()
messages.add_message(request, messages.INFO, 'Employee save successfully')
context['form'] = context['form'] = EmployeeForm()
else:
context['form'] = EmployeeForm(request.POST)
else:
context['form'] = EmployeeForm()
return render(request, 'app/employee.html', context)
Upvotes: 1
Views: 1220
Reputation: 21807
In your model Employee
the field city
is a ForeignKey
for which the default form field is ModelChoiceField
[Django docs]. This form field normalizes to a model instance. Assuming that you don't use some other form field you are not getting the choice text but an instance of City
. Therefore you can simply write city.id
or city.pk
to get the id that you want, or you can simply write the follows:
city = form.cleaned_data['city'].pk
Also calling some procedure to insert values should not really be needed (unless for some reason you really want to save bandwidth), assuming you use a ModelForm
you can simply write the follows to save the employee to the database:
employee = form.save()
Upvotes: 1