city
city

Reputation: 261

Django database inquiries. Finding duplicates in the database and stopping them from being submitted

I'm trying to go inside of my database and see if a certain submission has been submitted before and if it has stop it from being submitted again. Currently I have this bit of code testing each field of the form (obviously changes per field but i thought I'd only show one field for simplicity)

if request.method == 'POST':
    Cashtexts.objects.filter(cashTexts=request.POST['cashTexts']).exists() == False:

Then if it does not exist it goes on and save the submissions into the database. If it returns true it goes to an else statement that tells the user that what they entered has already been entered. previously this type of thing worked but I changed some variable names and now it stopped working. I've been browsing the code over a few time so I thought maybe something was fundamentally wrong with this type of filter but it makes sense in my head.

def submit_win(request):
    if request.method == 'POST':
        if Cashtexts.objects.filter(cashTexts=request.POST['cashTexts']).exists() or Cashtexts.objects.filter(superPoints=request.POST['superPoints']).exists() or Cashtexts.objects.filter(varolo= request.POST['varolo']).exists() or Cashtexts.objects.filter(swagbucks = request.POST['swagbucks']).exists() or Cashtexts.objects.filter(neobux = request.POST['neobux']).exists() or Cashtexts.objects.filter(topline=request.POST['topline']).exists() or Cashtexts.objects.filter(Paidviewpoint=request.POST['Paidviewpoint']).exists() or Cashtexts.objects.filter(cashcrate=request.POST['cashcrate']).exists() == False:
            form = CashtextsForm(request.POST)
            if form.is_valid():
                form.save()
                ref_create = Cashtexts.objects.filter(cashTexts=request.POST['cashTexts'])
                return render_to_response('submitted_page.html', {'ref_create': ref_create})
        else: #Error message reading wither you didnt insert codes or you enter the same code twice
            error = 'That code has already been submitted'
            ref_create = CashtextsForm()
            return render_to_response('submit.html', {'ref_create': ref_create,'error':error}, context_instance=RequestContext(request))
    else: #displays the page when the user asks to go to the submit page
        ref_create = CashtextsForm()
        return render_to_response('submit.html', {'ref_create': ref_create}, context_instance=RequestContext(request))

Also, I turned Cashtexts.objects.filter(cashTexts=request.POST['cashTexts']) intoa variable and passed it to my template to see what it was returning and it was returning objects that should have told the statement True. but it just seemed to ignore them and submit them anyway.

I suppose i could delete all the previous objects that match the thing they entered upon submission but that makes it less secure and could lead to users submitting over and over again thinking that they are getting it more in there. I'd rather just stop it before it happens.

Upvotes: 0

Views: 135

Answers (1)

marue
marue

Reputation: 5726

You can just set the definition of your cashTexts field to unique in the models definition:

def Cashtexts(models.Model):
    name = CharField(max_length=50, unique = True)

Just set the "unique" argument to true for each field you want to be unique and you're done. The way Django's forms API is working, the form fields will take over all the necessary error handling.


With the model fields set to unique where necessary you can have this much easier:

def view(request):

    if request.method == 'POST':
        form = CashtextsForm(request.POST)

        """ the next line is going to check uniqueness for each
            of the models fields where you have set unique = True
            If the field is not unique, it s field will have an
            attribute error, which you can then render to the template """
        if form.is_valid():
            form.save()
    else:
        form = CashtextsForm()

    context = RequestContext(request)

    # now i pass the form to the template as 'ref_create'
    context.update( {'ref_create':form} )
    return render_to_response('submit.html',context)

Then you simply render that form in your template (either with form.as_p(), form.as_table() or with some custom code like this):

{% for field in ref_create %}
    {{ field.label_tag }}
    {{ field }}
    {{ field.errors }}
{% endfor %}

Each field, set to unique in the model definition, which which would not be unique in the database any more if your form is saved, will now have an error message saying something like "A Cashtext with this name allready exists".


Customizing you error messages can be done in two ways: 1: customize the forms (i do not recommend that, until you have better understandings of how Django works) 2: instead of {{ field.errors }} write something like this:

{% if field.errors %}
     The Cashtext field {{field.name}} value should be unique.
{% endif %}

Upvotes: 1

Related Questions