Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form "Enter a valid date."

I'm having problem writing a simple form. This is my model for that form.

class UserStock(models.Model):
    amount = models.FloatField(default=0)
    date = models.DateTimeField('buy date')
    stockPrice = models.FloatField(default=0)
    user = models.ForeignKey(User)
    stock = models.ForeignKey(Stock)

This is my forms.py file

from django import forms
from datetime import date

class AddStockForm(forms.Form):
    stock = forms.CharField(max_length=10)
    amount = forms.FloatField(initial=0)
    #, initial=date.today, input_formats=settings.DATE_INPUT_FORMATS
    date = forms.DateField('buy date', initial=date.today)
    stockPrice = forms.FloatField(initial=0)

This is my first version for submitting form data.

@login_required(login_url='/login/')
def new_stock(request):
    if request.method == 'POST':
        form = AddStockForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data

            #dateForm = datetime.datetime.strptime(cd['date'],"%Y-%m-%d")
            userStock = UserStock(amount = cd['amount'], date=cd['date'], stockPrice = cd['StockPrice'])
            userStock.user = request.user
            stockForm = Stock.objects.filter(symbol=cd['stock'])
            userStock.stock = stockForm
            userStock.save()
    else:
        form = AddStockForm()

    template = loader.get_template("userStocks/new.html")
    context = RequestContext(request, {
        'form':form.as_p(),
    })
    return HttpResponse(template.render(context))

This is what my error looks like. enter image description here Error while submitting: Enter a valid date. I guess that it's Django's auto-check format. I googled a lot but didn't help. I have tried input_formats variations, but no luck. Thanks in advance for help.

like image 622
Lucas03 Avatar asked Dec 16 '22 11:12

Lucas03


1 Answers

I think this line will do.

date = forms.DateField(label='buy date', input_formats=['%Y-%m-%d'], initial=date.today)

I think the form was accepting 'buy date' as your input format, that's why when you try to set it manually it sends the duplicated error.

Hope this works

PS: Maybe after specifying that "buy date" is your label, you may be able to remove the input_formats attribute.

like image 191
Paulo Bu Avatar answered Jan 05 '23 16:01

Paulo Bu