Reputation: 3
I'm trying to take input the person table but I'm getting this error. I have connect these two models and I'm returning the string to connect it can anyone tell me solution for this below are my codes
this code is from models.py
from django.db import models
class Person(models.Model):
PersonID=models.CharField(max_length=30,null=True)
Lastname=models.CharField(max_length=30,null=True)
Middlename=models.CharField(max_length=30,null=True)
Firstname=models.CharField(max_length=30,null=True)
Initials=models.CharField(max_length=10,null=True)
Title=models.CharField(max_length=10,null=True)
Gender=models.CharField(max_length=10,null=True)
Birthdate=models.DateField(default=None,null=True)
def __str__(self):
return self.PersonID
class Function(models.Model):
FunctionCode=models.CharField(max_length=30,null=True)
FunctionName=models.CharField(max_length=30,null=True)
MinSalary=models.IntegerField(null=True)
MaxSalary=models.IntegerField(null=True)
DefaultBillingRate=models.CharField(max_length=30,null=True)
def __str__(self):
return self.FunctionCode
this code is from forms
from django.forms import ModelForm
from .models import Person
class PersonForm(ModelForm):
class Meta:
model = Person
fields = '__all__'
this code is from views
from django.shortcuts import render
from .forms import Person
from .models import *
def createPerson(request):
form = Person()
context = {'form':form}
return render(request, 'create_person.html', context )
this code is from person.html
{% extends 'main.html' %}
{% load static %}
{% block content %}
<form action="" method="POST">
{% csrf_token %}
{{form}}
<input type="submit" name="Submit">
</form>
{% endblock %}
Upvotes: 0
Views: 1063
Reputation: 472
If field could be None (null=True), then the __str__
method can return None. You should prevent this:
def __str__(self):
return self.field or ''
It returns the field's value if it is not None, otherwise it returns an empty string.
Upvotes: 1
Reputation: 51
In both models the fields returned by the str method can be null, you must establish a condition.
Example: Model -> Person
def __str__(self):
if self.PersonID is not None:
return self.PersonID
return "Custom String"
Model -> Function
def __str__(self):
if self.FunctionCode is not None:
return self.FunctionCode
return "Custom String"
Upvotes: 0
Reputation: 2380
As you can see your FunctionCode
can be null.
your __str__
method should only return string, but when FunctionCode
is null it will return None
instead of string
.
You can return a non nullable field or you can do this.
def __str__(self):
if self.FunctionCode is not None:
return self.FunctionCode
return "Unknown"
Upvotes: 1