models.py (Contact)
class Contact(models.Model)
first = models.CharField(max_length=30)
middle = models.CharField('M.I.',max_length=30, blank=True)
last = models.CharField(max_length=30)
sort_order = models.PositiveIntegerField(default=99)
models.py (Link)
class Link(models.Model):
contact = models.ForeignKey(Contact)
link = models.URLField()
description = models.CharField(max_length=30)
access_date = models.DateField(blank=True,null=True)
forms.py
from django.forms import ModelForm
from contacts.models import Contact
class ContactAjaxForm(ModelForm):
class Meta:
model=Contact
views.py
def edit(request,object_id=False):
LinkFormSet = inlineformset_factory(Contact, Link, extra=1)
if object_id:
contact=Contact.objects.get(pk=object_id)
else:
contact=Contact()
if request.method == 'POST':
f=forms.ContactAjaxForm(request.POST, request.FILES, instance=contact)
fs = LinkFormSet(request.POST,instance=contact)
if fs.is_valid() and f.is_valid():
f.save()
fs.save()
return HttpResponse('success')
else:
f = forms.ContactAjaxForm(instance=contact)
fs = LinkFormSet(instance=contact)
return render_to_response(
'contacts/edit.html',
{'fs': fs, 'f': f, 'contact': contact}
)
This is not based on the example in the book, it's edited down from some code on my site. I haven't tested it so there might be some bugs but overall it should be solid. Using an empty instance of Contact isn't the suggested method but it saves a bit of logic and it works.
Edit: Added Link Model, switched to normal Foreign Key instead of Generic Foreign Key which is confusing