I have a ModelForm that I have created a view and template with to add an instance to the database. I am now trying to extend this to be editable when the user clicks a button - but when they do that the form/template page appears and I get the "This Field is required message" but all fields are empty instead of pre-populated with the instance I passed in, but when I edit the values to something different than originally then in my database the correct instance is updated. So it is passing the primary key but none of the values are showing up. If anyone can tell what I am doing wrong I would appreciate it, oh, and I am using this post Django edit form based on add form? as a basis so please don't just send me there.
Here are my files
ModelForm
class CreditCardForm(forms.ModelForm):
class Meta:
model = CreditCard
fields = ('name_on_card','card_number','contact_number_on_card')
View
def edit(request, id=None, template_name='article_edit_template.html'):
if id:
print "Edit Mode"
card = get_object_or_404(CreditCard, pk=id)
if card.card_owner != request.user:
raise HttpResponseForbidden()
else:
print "Create Mode"
card = CreditCard(card_owner=request.user)
if request.POST:
print "request.POST"
form = CreditCardForm(request.POST, instance=card)
if form.is_valid():
print "is_valid()"
form.save()
# If the save was successful, redirect to another page
# redirect_url = reverse(article_save_success)
return HttpResponseRedirect('/cards/')
else:
print "else"
form = CreditCardForm(instance=card)
return render_to_response(
'create_credit.html',
{'form': form,},
context_instance=RequestContext(request)
)
Template
{% include "base.html" %}
<form action="" method="post">{% csrf_token %}
<fieldset>
<legend>Required</legend>
<div class="fieldWrapper">
{{ form.name_on_card.errors }}
<label for="id_topic">Name as it appears on card:</label>
{{ form.name_on_card }}
</div>
<div class="fieldWrapper">
{{ form.card_number.errors }}
<label for="id_topic">Last 6 digits of card number:</label>
{{ form.card_number }}
</div>
</fieldset>
<fieldset>
<legend>Optional</legend>
<!-- This is for Credit Card's Only -->
<div class="fieldWrapper">
{{ form.contact_number_on_card.errors }}
<label for="id_topic">Institution contact number: 1-</label>
{{ form.contact_number_on_card }}
</div>
</fieldset>
<p><input type="submit" value="Save"></p>
</form>
URLS
url(r'^new/credit/$', views.edit, {}, 'crds_newCredit'),
url(r'^edit/credit/(?P<id>\d+)/$', views.edit, {}, 'crds_editCredit'),