1

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.

Mansi Shukla
  • 377
  • 3
  • 23

2 Answers2

1

Because your field valid_coupons in the model Coupons has the attribute unique=True, Django is raising an exception that an object of the model Coupons with the value of valid_coupons already exists.

I don't know if it's intentional or not to have the valid_coupons field to be unique, but if you removed or changed unique to False instead it should work.

If it is intentional to have it set to True, then well... don't save a value that already exists?

Edit: As I pointed out in my comment below, an empty value is also a unique value, meaning that just because you leave the value of valid_coupons empty doesn't mean you can bypass the unique attribute.

If you want to store random values for each instance of valid_coupons you can override the save method in the model of Coupons, like this:

import uuid

class Coupons(models.Model):
    ...

    def save(self, *args, **kwargs):
        # Only do this part if the PK is not set yet
        if self.pk is None:
            # Generate a random string for valid_coupons
            self.valid_coupons = uuid.uuid4().hex[:5].upper()
            # TODO: Make sure this code is unique somehow
        # Call the super
        super().save(*args, **kwargs) 

I included the random code generation from this answer, but you should look to implement your own solution. Also, the code above doesn't check for duplicates, but instead relies on that it won't be any conflicts by randomising the codes. This is a naive approach and you should look up to check for duplicates before calling the super method.

Johan
  • 3,577
  • 1
  • 14
  • 28
0

For me, it works in this way I have a class in models.py (Types_List) and another class in forms.py (Types_form). Also one HTML file in "base/add.html" address. My code within views.py is:

def add(response):
   form = Types_form(response.POST or None)
   if form.is_valid():
       n = form.cleaned_data['type_name'] 
       if Types_List.objects.filter(type_name=n).exists():
           form.message = 'Erorr: Duplicated!".'
       else:
           t = Types_List(type_name=n)
           t.save()

   return render(response, "base/add.html", {"form":form})

For more clarification, "response.POST or None" prevents function always send a post, even when you only opened the page. "cleaned_data" unencrypts "form" dictionaries and you can call them by key.

"filter(type_name=n).exists()" validates the presence of "type_name" within the "Types_List". If there is any similar content, one string will save into "form.message" and you can call it simply within the HTML file, as bellow:

<div>
  {{ form.message }}
  <form method="post" action="{% url 'add' %}">
      {{form}}
      {% csrf_token %}
      <button type="submit" name="Add">Add</button>
  </form>
</div>
Shrm
  • 426
  • 4
  • 8