This error occurs when same user in the database try to save a data. i notice this error while i was working with modelform. I try to save directly from the database by picking the same User, but this erro occurs in the database ‘‘Academy with this User already exists.’’ below are my logics.
forms.py
class academyForm(ModelForm):
widgets= {
'institution': forms.Select(choices=ACADEMY_CHOICES,
attrs={
"placeholder": "Institution Attended",
"class": "form-control"
})
}
widgets= {
'certificate_obtained': forms.Select(choices=CERTIFICATE_CHOICES,
attrs={
"placeholder": "Certificate Obtained",
"class": "form-control"
})
}
date_obtained = forms.DateField(
widget=forms.DateInput(
attrs={
"placeholder": "Date obtained",
"class": "form-control",
"type":"date"
}
))
widgets= {
'document': forms.FileInput(
attrs={
"placeholder": "Document",
"class": "form-control"
})
}
class Meta:
model = Academy
fields = ('institution', 'certificate_obtained', 'date_obtained', 'document')
views.py
def academy(request):
user= User.objects.get(username= request.user)
credential =Academy.objects.filter(user_id =user).order_by('user_id')
if request.method == 'POST':
form =academyForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user =request.user
institution =form.cleaned_data.get('institution')
certificate =form.cleaned_data.get('certificate_obtained')
dates =form.cleaned_data.get('date_obtained')
document =form.cleaned_data.get('document')
# try:
academy, created= Academy.objects.get_or_create(user=user, institution = institution, certificate_obtained=certificate, date_obtained =dates, document =document)
# except:
# messages.error(request, 'Cannot submit credential twice!')
# return redirect('academy')
messages.success(request, 'User data saved successful! Click next to proceed')
return redirect('academy')
form = academyForm()
return render(request, 'portal/home/credential.html', {'form':form, 'credentials':credential } )
this is the model.py
class Academy(models.Model):
user =models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True)
institution =models.CharField(choices=ACADEMY_CHOICES, max_length=100, null=True, blank = True)
certificate_obtained=models.CharField(choices=CERTIFICATE_CHOICES, max_length=100, null=True, blank = True)
date_obtained =models.DateField(null =True, blank=True)
document = models.FileField(upload_to='document')
# personalinfo =models.ForeignKey('Personalinfo', on_delete=models.CASCADE, null=True, blank = True)
# job =models.ForeignKey('Job', on_delete=models.CASCADE, null=True, blank = True)
def __str__(self):
return self.certificate_obtained