I am trying to check and see if there is a duplicate entry in the database before adding an entry. Here are my current models —
class Education(models.Model):
school = models.CharField(max_length=100)
class_year = models.IntegerField(max_length=4, blank=True, null=True, choices=YEAR)
degree = models.CharField(max_length=100, blank=True, null=True)
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
employments = models.ManyToManyField(Employment)
On the form, a user must enter a school. Class year and degree are optional. To check for duplicate entries, right now I have —
if form.is_valid() and request.POST['school']:
school = form.cleaned_data['school']
try:
school_object = Education.objects.get(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
except (Education.DoesNotExist):
school_object = Education(school=form.cleaned_data['school'],
class_year=form.cleaned_data['class_year'],
degree = form.cleaned_data['degree'])
school_object.save()
profile.educations.add(school_object)
profile.save()
I am getting an ValueError if the class_date is not filled out. How to fix this and also when checking for duplicates? Thank you.
First, unless you’ve got a great reason you really shouldn’t be accessing post variables without sending them through a form.
Then when you’re processing the view: