user13829491
user13829491

Reputation:

The Ticket could not be created because the data didn't validate

My model Class:

class Ticket(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ticket_number = models.IntegerField('Ticket Number', null=True)
    date = models.DateTimeField('Date', default=datetime.now())
    name = models.CharField('Customer Name', max_length=50)
    company = models.CharField('Company / Community', max_length=50, null=True)
    address = models.CharField('Address', max_length=50, null=True)
    total_card = models.DecimalField('Total Card Payment', max_digits=6, decimal_places=2, null=True)
    total_cash = models.DecimalField('Total Cash Payment', max_digits=6, decimal_places=2, null=True)
    tip_card = models.DecimalField('Tip in card', max_digits=6, decimal_places=2, null=True)
    tip_cash = models.DecimalField('Tip in cash', max_digits=6, decimal_places=2, null=True)
    gas_fee = models.DecimalField('Gas Fee', max_digits=6, decimal_places=2, null=True)
    prc_fee = models.DecimalField('Percent fee', max_digits=6, decimal_places=2, null=True)

The form works when coded like that:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit">
</form>

But I can't validate when using the forms in this way:

<form method="post">
    {% csrf_token %}
    {{ form.ticket_number.errors }}
    {{ form.ticket_number.label_tag }}
    {{ form.ticket_number }}
    <br>
    {{ form.name.errors }}
    {{ form.name.label_tag }}
    {{ form.name }}
    <br>
    {{ form.company.errors }}
    {{ form.company.label_tag }}
    {{ form.company }}
    <br>
    {{ form.address.errors }}
    {{ form.address.label_tag }}
    {{ form.address }}
    <br>
    {{ form.total_card.errors }}
    {{ form.total_card.label_tag }}
    {{ form.total_card }}
    <br>
    {{ form.total_cash.errors }}
    {{ form.total_cash.label_tag }}
    {{ form.total_cash }}
    <br>
    {{ form.tip_card.errors }}
    {{ form.tip_card.label_tag }}
    {{ form.tip_card }}
    <br>
    {{ form.tip_cash.errors }}
    {{ form.tip_cash.label_tag }}
    {{ form.tip_cash }}
    <br>
    {{ form.gas_fee.errors }}
    {{ form.gas_fee.label_tag }}
    {{ form.gas_fee }}
    <br>
    {{ form.prc_fee.errors }}
    {{ form.prc_fee.label_tag }}
    {{ form.prc_fee }}
    <br>
    <input type="submit" value="Submit">
</form>

It generates the following error:

ValueError at / The Ticket could not be created because the data didn't validate. Request Method: POST Request URL: http‍://127.0.0.1:8000/ Django Version: 3.0.8 Exception Type: ValueError Exception Value: The Ticket could not be created because the data didn't validate. Exception Location: C:\PyProjects\DeliveryDriverMoney\venv\lib\site-packages\django\forms\models.py in save, line 451 Python Executable: C:\PyProjects\DeliveryDriverMoney\venv\Scripts\python.exe Python Version: 3.8.3 Python Path:
['C:\PyProjects\DeliveryDriverMoney', 'C:\Program Files (x86)\Python38-32\python38.zip', 'C:\Program Files (x86)\Python38-32\DLLs', 'C:\Program Files (x86)\Python38-32\lib', 'C:\Program Files (x86)\Python38-32', 'C:\PyProjects\DeliveryDriverMoney\venv', 'C:\PyProjects\DeliveryDriverMoney\venv\lib\site-packages'] Server time: Mon, 13 Jul 2020 20:53:02 +0000

That's my view:

def ticket_form_view(request):
    form = TicketModelForm()
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        ticket_post = TicketModelForm(request.POST)
        # check whether it's valid:
        if ticket_post.is_valid():
            # process the data in form.cleaned_data as required
            ticket_post.user_id = request.user.id
            ticket_post.data = datetime.now()
            ticket_post.save()
            # redirect to a new URL:
            return HttpResponseRedirect('home/')
        else:
            return HttpResponseRedirect('WRONG/')
    # if a GET (or any other method) we'll create a blank form
    else:
        return render(request, 'add_ticket.html', {'form': form})
    return render(request, 'add_ticket.html', {'form': form})

Upvotes: 0

Views: 197

Answers (1)

Muhammad Zeshan Arif
Muhammad Zeshan Arif

Reputation: 475

I found a typing mistake in your code on following line i.e you wrote ticket_post.data instead of ticket_post.date

Secondly your form wants user field and date to be filled. It means input from client, not from the code. So to resolve this issue you need to follow two steps.

Firstly exclude these fields from your TicketModelForm's meta class, So that is_valid() didn't validate user and date field as it will be filled by code not from user through form.

Your TicketModelForm will look something like this

class TicketModelForm(forms.ModelForm):

    class Meta:
        model = Ticket
        exclude = ['user', 'date']

Secondly you need to update your view

def ticket_form_view(request):
    form = TicketModelForm()
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        ticket_post = TicketModelForm(request.POST)
        # check whether it's valid:
        if ticket_post.is_valid():
            # process the data in form.cleaned_data as required
            ticket = ticket_post.save(commit=False)
            ticket.user = request.user
            ticket.date = datetime.now()
            ticket.save()
            # redirect to a new URL:
            return HttpResponseRedirect('home/')
        else:
            return HttpResponseRedirect('WRONG/')
    # if a GET (or any other method) we'll create a blank form
    else:
        return render(request, 'add_ticket.html', {'form': form})
    return render(request, 'add_ticket.html', {'form': form})

Upvotes: 0

Related Questions