I have created a model form in DJANGO but on inserting value to populate the model I am getting error Coupons with this Valid coupons already exists.
in my html file.
I have two models :
class Coupons(models.Model):
valid_coupons = models.CharField(max_length=5,unique=True)
def __str__(self):
return self.valid_coupons
class ChapterParticipated(models.Model):
code = models.ForeignKey(Coupons,unique=True,on_delete=models.PROTECT)
ChapterName = models.CharField(max_length=264)
TeamName = models.CharField(max_length=264)
def __str__(self):
return self.code
And my view.py contains :
from django.shortcuts import render
from first_app.forms import NewUserForm
# Create your views here.
def index(request):
form = NewUserForm()
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('ERROR FORM INVALID')
return render(request,'firstapp/firstapp.html',{'form':form})
And my forms.py contains :
from django import forms
from first_app.models import Coupons
class NewUserForm(forms.ModelForm):
class Meta():
model = Coupons
fields = '__all__'
What happening is when I enter the value in input field and click on submit button it shows me
Coupons with this Valid coupons already exists.
And it add the input to table but it still shows that error.