Ruchan Guler
Ruchan Guler

Reputation: 23

Data is In database but it is still saving the form

 if request.method == "POST":
            form = HayvanEkle(request.POST)
            if form.is_valid():
                if request.POST.get("alan") in Hayvan.objects.all():
                    return redirect("/")
                else:
                    form.save()
                    return redirect("/") 

"alan" is in the database but it is still saving the form. What should I do?


models.py:

 class Hayvan(models.Model):
        alan = models.CharField(max_length=50,null=True)
        satışsırası = models.CharField(max_length=50,null=True)
        hayvannumarası = models.CharField(max_length=50,null=True)
        kesimsırası = models.CharField(max_length=50,null=True)

Upvotes: 1

Views: 1705

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

You check if there already exists a record with the value for alan with:

if request.method == 'POST':
    form = HayvanEkle(request.POST)
    if form.is_valid():
        if Hayvan.objects.filter(alan=request.POST.get('alan')).exists():
            return redirect('/')
        else:
            form.save()
            return redirect('/')

You might want to set the alan field on unique=True such that the database will enforce this:

class Hayvan(models.Model):
    alan = models.CharField(max_length=50, unique=True, null=True)
    # …

Note that if an item for the given alan already exists, you will not update that record with the form. You can do this by constructing a form with HayvanEkle(request.POST, instance=instance_to_update).

Upvotes: 3

Related Questions