2

I have been trying to make the date field in a form to display the current date when it renders. But I have failed to find a proper solution to this problem.

Please find below the code.

HTML File

<form class="form-horizontal" role="form" method = 'POST'>
    {% csrf_token%}
    <h2>New Manufacturer Details</h2>
    <div class="form-group row">
        <label for="createddate" class="col-sm-3 control-label">Created Date</label>
        <div class="col-sm-9">
            <input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ createddate }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufname" class="col-sm-3 control-label">Name</label>
        <div class="col-sm-9">
            <input type="text" id="manufname"  name = "manufname" placeholder="Manufacturer Name" class="form-control" autofocus required="true" value = '{{ manufname }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufaddress" class="col-sm-3 control-label">Address</label>
        <div class="col-sm-9">
            <textarea class="form-control" id="manufaddress"  name = "manufaddress" placeholder="Manufacturer Address" rows="3" required="true" value = '{{ manufaddress }}'></textarea>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufcontact" class="col-sm-3 control-label">Contact Name</label>
        <div class="col-sm-9">
            <input type="text" id="manufcontact"  name = "manufcontact" placeholder="Manufacturer POC" class="form-control" autofocus required="true" value = '{{ manufcontact }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufcontactnum" class="col-sm-3 control-label">Contact Number</label>
        <div class="col-sm-9">
            <input type="text" id="manufcontactnum"  name = "manufcontactnum" placeholder="Manufacturer Contact Number" class="form-control" autofocus required="true" value = '{{ manufcontactnum }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufemailid" class="col-sm-3 control-label">Email Id</label>
        <div class="col-sm-9">
            <input type="email" id="manufemailid"  name = "manufemailid" placeholder="Manufacturer Email Id" class="form-control" autofocus required="true" value = '{{ manufemailid }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufgst" class="col-sm-3 control-label">GST No</label>
        <div class="col-sm-9">
            <input type="text" id="manufgst"  name = "manufgst" placeholder="Manufacturer GST Number" class="form-control" autofocus required="true" value = '{{ manufgst }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manuflicenseno" class="col-sm-3 control-label">License No</label>
        <div class="col-sm-9">
            <input type="text" id="manuflicenseno"  name = "manuflicenseno" placeholder="Manufacturer License Number" class="form-control" autofocus required="true" value = '{{ manuflicenseno }}'>
        </div>
    </div>
    <div class="form-group row">
        <label for="manufbank" class="col-sm-3 control-label">Bank Details</label>
        <div class="col-sm-9">
            <textarea class="form-control" id="manufbank"  name = "manufbank" placeholder="Manufacturer Bank Details" rows="3" required="true" value = '{{ manufbank }}'></textarea>
        </div>
    </div>
    <div class="col text-center">
        <button type="submit" class="btn btn-primary" id="form-submit">Save</button>
    </div>
</form> <!-- /form -->
<script>
    $("#form-horizontal").validate();
</script>

Views.Py

def createmanufacturer(request):
if request.method == 'POST':
    form = CreateManufacturerForm(request.POST or None)
    if form.is_valid():
        form.save()
    else:
        createddate = request.POST['createddate']
        manufname = request.POST['manufname']
        manufaddress = request.POST['manufaddress']
        manufcontact = request.POST['manufcontact']
        manufcontactnum = request.POST['manufcontactnum']
        manufemailid = request.POST['manufemailid']
        manufgst = request.POST['manufgst']
        manuflicenseno = request.POST['manuflicenseno']
        manufbank = request.POST['manufbank']
        messages.success(request, ('There was an error in your form! Please try again...'))
        return render(request, 'screens/createmanufacturer.html', {
                'createddate' : createddate,
                'manufname' : manufname,
                'manufaddress' : manufaddress,
                'manufcontact' : manufcontact,
                'manufcontactnum' : manufcontactnum,
                'manufemailid' : manufemailid,
                'manufgst' : manufgst,                  
                'manuflicenseno' : manuflicenseno,
                'manufbank' : manufbank,
            })
    messages.success(request, ('Manufacturer Details have been submitted successfully'))
    return redirect("screens:testpage")
else:
    form = CreateManufacturerForm()
    return render(
        request = request,
        template_name = 'screens/createmanufacturer.html',
        context = {'form' : form}
        )

forms.py

class CreateManufacturerForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    super(CreateManufacturerForm, self).__init__(*args, **kwargs)
    self.fields['createddate'].initial = date.today

class Meta:
    model = Manufacturer
    #createddate = forms.DateField(initial=date.today)
    fields = ['createddate', 
              'manufname', 
              'manufaddress', 
              'manufcontact', 
              'manufcontactnum',
              'manufemailid',
              'manufgst',
              'manuflicenseno',
              'manufbank']

models.py

class Manufacturer(models.Model):
createddate = models.DateField()
manufname = models.CharField(max_length = 255)
manufaddress = models.TextField()
manufcontact = models.CharField(max_length = 255)
manufcontactnum = models.CharField(max_length = 25)
manufemailid = models.EmailField(max_length = 200)
manufgst = models.CharField(max_length = 255)
manuflicenseno = models.CharField(max_length = 255)
manufbank = models.TextField()
manufcode = models.CharField(max_length = 255, primary_key=True, editable=False)

def __str__(self):
    return self.manufname

Right now, nothing happens when the form renders. What I want is the date in the Created Date should be set to today's date. However the user could leave it as is or could select a date of his/her choice. But the requirement is that date field should be pre-populated with the current date.

Please find below the screenshot of the web form.

Web Form

2 Answers 2

1

To save the current use auto_now=True

class DateField(auto_now=False, auto_now_add=False, **options)¶ A date, represented in Python by a datetime.date instance. Has a few extra, optional arguments:

DateField.auto_now¶ Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override

To display current date in the form use :

form = CreateManufacturerForm(initial={'createddate': datetime.now()})
Sign up to request clarification or add additional context in comments.

6 Comments

So, In the "models.py", Should I add the following line? createddate = models.DateField(auto_now = True). And in the "forms.py" file, should the line under Class Meta be the following? createddate = forms.DateField(initial=date.today)
You need only one of them. If you just want to store it use the first one. If you want to display it. Use initials in view form instance or in firm class definition as you like
tried the following in the forms.py. createddate = forms.DateField(initial=date.today). Also tried the below too.form = CreateManufacturerForm(initial={'createddate': date.today()}). Both did not work. The input field createddate in the html page still doesn't display the current date.
form = CreateManufacturerForm(initial={'createddate': datetime.now()})
I tested. It works fine. Plz share the error you have
|
1

So, after a lot of frustrating hours, I was able to finally solve the problem, with help from my friend Houda. This is what I did.

views.py

In the GET portion of the code, I wrote the following.

initial_data = {
        'createddate' : date.today().strftime("%Y-%m-%d"),
    }
    form = CreateManufacturerForm(initial = initial_data)

template.html file

I changed the following

<input type="date" id="createddate" name = "createddate" class="form-control" autofocus required="true" value = '{{ form.createddate.value }}'>

I am not sure if this is the best solution. But at least I got it to work. I believe the issue had something to do with the date format that HTML has for the

input type = 'date'

it only allows 'YYYY-mm-dd'

Thanks everyone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.