Django- how to save form input to an object model in the database?
<p>I have a Django project which is being used to manage a number of projects, and all of the information relating to a project.</p>

<p>On one of the webpages, titled 'Concept', there is a form, which takes an input value of cost excluding vat in one text box, displays the cost including vat in another text box, and has a <code>datepicker</code> field to allow the user to select the date that a deposit has been paid, if it has at all.</p>

<p>I'm having a bit of trouble getting the form to save the value entered by the user for the date at the moment- if the user fills out the three fields in the form (cost exc vat- entered by user, cost inc vat- automatically generated based on const exc vat, &amp; date), and then refreshes the page, the two cost fields retain their values, but the 'date' field reverts to being blank.</p>

<p>When I inspect the page element for the 'date' field, I can see that it is in the following HTML structure:</p>

<pre><code>&lt;body&gt;
    ...
    &lt;div class="wrapper"&gt;
        &lt;div class="content"&gt;
            &lt;form method="POST" .... data-view-url=".../concept_save_ajax/"&gt;
                &lt;div class="col-12-box"&gt;
                    &lt;div&gt;
                        &lt;table class="right fixed m-t-md"&gt;
                            &lt;tbody&gt;
                                &lt;tr&gt;
                                    ...
                                    &lt;td class="p-r-md"&gt;Deposit exc VAT&lt;/td&gt;
                                    &lt;td class="p-r-md"&gt;
                                        &lt;input class="currency" id="id_amount_exc_vat" name="amount_exc_vat" type="number" value="280"&gt;
                                    &lt;td class="p-r-md&gt;
                                        &lt;input class="datepicker hasDatepicker" data-original-value id="id_date_received" name="date_received" type="text"&gt; == $0
                                    &lt;/td&gt;
                                &lt;/tr&gt;
                            &lt;/tbody&gt;
                        &lt;/table&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/form&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/body&gt;
</code></pre>

<p><strong>Edit</strong></p>

<p>Although that is the structure of the HTML for the page when I 'inspect it in the browser, the actual code from my HTML file in my project is:</p>

<pre><code>{% block content %}
    &lt;form method="POST" enctype="multipart/form-data" data-vat-status="{{project.vat_status}}" data-view-url="{% url 'projects:concept_save_ajax_2' project.id %}" class="autosave_form formset full-width" action="{% url 'projects:upload_budget_pdfs' project.id %}"&gt;
        ...
    &lt;/form&gt;
    &lt;form method="POST" enctype="multipart/form-data" data-vat-status="{{project.vat_status}}" data-view-url="{% url 'projects:concept_save_ajax' project.id %}" class="autosave_form full-width"&gt;
        {% csrf_token %}

        &lt;div class="col-12 box"&gt;
            &lt;div&gt;
                &lt;table class="right fixed m-t-md"&gt;
                    &lt;tr&gt;
                        {% for hidden in deposit_form.hidden_fields %}
                            {{hidden}}
                        {% endfor %}
                        {% for field in deposit_form.visible_fields %}
                            &lt;td class="p-r-md"&gt;{{field.label}}&lt;/td&gt;&lt;td class="p-r-md"&gt;{{field}}&lt;/td&gt;
                        {% endfor %}
                        &lt;td&gt;&lt;a class="email_trigger button" data-view-url="{% url 'comms:open_email_template' project.id %}?template=7"&gt;Raise invoice&lt;/a&gt;&lt;/td&gt;
                    &lt;/tr&gt;
                &lt;/table&gt;
            &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class="col-6 box"&gt;
            ...
        &lt;/div&gt;
        &lt;div class="col-6 box"&gt;
            ...
        &lt;/div&gt;
    &lt;/form&gt;

{% endblock content %}
</code></pre>

<p><strong>End Edit</strong></p>

<p>Given that the form method is specified as <code>POST</code>, I am expecting the information entered into the form to be saved using the <code>concept_save_ajax</code> view as indicated inside the opening <code>&lt;form&gt;</code> tag.</p>

<p>This view is defined in <code>views.py</code> with:</p>

<pre><code>def concept_save_ajax(request, project_id):
""" Save concept forms """
if not request.is_ajax():
    raise Http404('Ajax only')

if request.method == 'POST':
    project = Project.objects.prefetch_related('budget_versions', 'budget_overview').get(pk=project_id)

    form_instances = [
        # [DepositForm, project.deposit],
        [DepositInfoForm, project.deposit],
        [BudgetNotesForm, project.budget_overview],
        [EndDetailsForm, project.end],
    ]

    # Save the forms 
    for form_instance in form_instances:
        form = form_instance[0](request.POST, instance=form_instance[0]) #1]) should be '0' for first element?
        if form.is_valid() and form.has_changed():
            print form_instance[0], "is valid.", form_instance[0]
            updated_details = form.save()
        elif form.has_changed():
            print form_instance[0], "is not valid", form.errors
            return JsonResponse({'error': form.errors})



    # url = '/projects/{0}/?tab={1}'.format(project_id, tabs[3])
    return JsonResponse({'success': 'Saved'})
else:
    raise Http404('Request is not a post')
</code></pre>

<p>I can see that this view is calling <code>form.save()</code> if and when the criteria <code>form.is_valid()</code> and <code>form.has_changed()</code> is met, but for some reason this doesn't appear to actually save when I enter a new value for the 'date' field.</p>

<p>I have tried to test this in the console- but the field that should be holding the 'date' value appears to be empty... In the console, I ran:</p>

<pre><code> from projects import models

 from projects.models import Project

 allPrjcts = Project.objects.all()

 br = allPrjcts.filter(project_name="1 Brocks Road")

 from costing import models

 from costing.models import Deposit

 allDpsts = Deposit.objects.all()

 brocksRoad = br[0]          # I know that this is the only project returned by the filter

brDpst = allDpsts.get(project_id = 6311L)      # I know that this is the ID for the 'brocksRoad' project
</code></pre>

<p>But then, when I run <code>brDpst.date_received</code> in the console, nothing is shown, indicating that the value I entered into the 'date' field on the webpage doesn't appear to have been saved...</p>

<p>Any ideas why this is? How can I get the value of the 'date' field to save automatically, so that it is displayed when I reload the page, the same as the 'cost' fields on that form?</p>

<p>If I run <code>brDpst.amount_exc_vat</code> in the console, it displays the value: </p>

<blockquote>
  <p>Decimal('280.00')</p>
</blockquote>

<p>which is the amount I input into the text box, so clearly the form is saving... just for some reason the value of the 'date' field is not being retained...</p>

<p><strong>Edit</strong></p>

<p>This is how the <code>DepositInfoForm</code> is currently defined:</p>

<pre><code>class DepositInfoForm(ValidatedForm):
    ...
    date_received = MoonDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'})))
</code></pre>

<p>I tried changing it to:</p>

<pre><code>class DepositInfoForm(ValidatedForm):
    ...
    date_received = MoonDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker', 'type':'date'})))
</code></pre>

<p>as suggested by @neverwalkaloner, but if I do this, there are now two calendars displayed in the drop down when I select the <code>date_received</code> field on the form... I want to use the calendar that's already there to choose the date, not the one that was added by the <code>'type':'date'</code> parameter that I passed to the <code>date_received</code> variable...</p>

<p><strong>Edit</strong></p>

<p>I've added some debug to my <code>DepositInfoForm(...)</code> class, and it seems that its <code>save()</code> method is being called when changes are made to the form field that's taking the numerical value, but <code>save()</code> is not being called when changes are made to the form field that's holding the date... I don't understand why this is...?</p>

<p>The <code>DepositInfoForm(...)</code> class is defined with:</p>

<pre><code>class DepositInfoForm(ValidatedForm):
    amount_exc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency',}),label="Deposit exc VAT")
    amount_inc_vat = forms.IntegerField(required=False, widget=forms.NumberInput(attrs={'class': 'currency', 'readonly':'readonly',}),label="Inc VAT")
    date_received = MoonDateField(required=False, label="Date deposit received", widget=forms.DateInput(format='%d/%m/%Y', attrs=({'class':'datepicker'})))

    class Meta:
        model = Deposit
        fields = ('amount_exc_vat', 'amount_inc_vat', 'date_received')#,'received')

    def __init__(self, *args, **kwargs):
        print "__init__ method being called in DepositInfoForm"
        instance = kwargs.get('instance', {})
        project = instance.project

        try: amount_exc_vat = int(round(instance.amount_exc_vat))
        except TypeError: amount_exc_vat = None
        try: amount_inc_vat = int(round(project.deposit.amount_inc_vat))
        except TypeError: amount_inc_vat = None

        try: date_received = instance.date_received
        except TypeError: date_received = None

        initial = kwargs.get('initial', {})
        initial={
                    'received': project.deposit_received,
                    'amount_exc_vat': amount_exc_vat,
                    'amount_inc_vat': amount_inc_vat,
                    'date_received': date_received,
                }
        kwargs['initial'] = initial

        super(DepositInfoForm, self).__init__(*args, **kwargs)
        self.fields['date_received'].widget.attrs.update({'data-original-value': self.initial['date_received'] or ''})

    def save(self, commit=True):
        print "Save method being called in DepositInfoForm"
        deposit = self.instance
        data = self.cleaned_data

        print "save method being called in DepositInfoForm (projects/forms.py line 1142)"
        if 'date_received' in self.changed_data:
            if not data['date_received'] == '':
                deposit.project.deposit_received = True;
                self.deposit_r = True
                deposit.project.upgrade_detailed_status(Project.ds75)
        else:
            deposit.project.deposit_received = False;       
        deposit.project.save()

        if ('amount_exc_vat' in self.changed_data or 'date_received' in self.changed_data in self.changed_data) and data['amount_exc_vat'] and data['date_received']:
            send_message(message_template=2, project=self.instance.project)
            self.deposit_r = True       

        if hasattr(self, 'deposit_r'):
            # Make the payment
            deposit_payment = Payment(project=deposit.project, is_booking_deposit=True, amount_exc_vat=data['amount_exc_vat'], date_paid=data['date_received'])

        return super(DepositInfoForm, self).save(commit=commit)
</code></pre>

<p><strong>Edit</strong></p>

<p>when I try to change the date in the form on the webpage at the moment, although the new date is displayed initially, if I refresh the page, its value changes back to what it was before I changed it. When I change the value of the 'date' field in the form, the console is displaying the following output:</p>

<pre><code> Exception in thread Thread-42:
Traceback (most recent call last):
  File ".../threading.py", line 810, in __bootstrap_inner
self.run()
  File ".../models.py", line 138, in run
msg.send(self.fail_silently)
  File ".../message.py", line 292, in send
return self.get_connection(fail_silently).send_messages([self])
  File ".../smtp.py", line 100, in send_messages
new_conn_created = self.open()
  File ".../smtp.py", line 67, in open
self.connection.login(self.username, self.password)
  File ".../smtplib.py", line 615, in login
raise SMTPAuthenticationError(code, resp)
SMTPAuthenticationError: (535, '5.7.3 Authentication unsuccessful')
</code></pre>

<p>but I haven't actually changed any of the files it's complaining about in the <code>Traceback</code>... What would be causing this exception?</p>