Q:

Django IntegrityError (1048, "Column 'network_id' cannot be null")

Ok, so i searched high and low for this, and both the docs, and almost every page on google tells me my code should be legit.
Let me start with models.py:
class Network(models.Model):
    title = models.CharField(max_length=50)
    description = models.CharField(max_length=500)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __unicode__(self):
       return self.id

class NetworkForm(ModelForm):
    class Meta:
        model = Network

class Range(models.Model):
    network = models.ForeignKey(Network)
    range_start = models.GenericIPAddressField(unpack_ipv4=True)
    range_end = models.GenericIPAddressField(unpack_ipv4=True)
    range_title = models.CharField(max_length=50)
    range_description = models.CharField(max_length=300)

    def __unicode__(self):
        return self.range_title

class RangeForm(ModelForm):
    class Meta:
        model = Range
        exclude = ('network',)

Then my views.py:
@login_required(login_url='/login/')
def add_network(request):

    if request.method == "POST":
        net_form = NetworkForm(request.POST)
        range_formset = RangeForm(request.POST)
        if net_form.is_valid and range_formset.is_valid:
            net_form.save(commit=False)
            range_formset.network = net_form
            range_formset.save()
            net_form.save()

        return HttpResponseRedirect('/')
    else:
        net_form = NetworkForm()
        range_form = RangeForm()
        return render_to_response('networks/add.html', {
            "net_form": net_form,
            "range_form": range_form,
        }, context_instance=RequestContext(request))

And my template:
{% extends 'base.html' %}

{% block title %}Add Network{% endblock %}

{% block content %}
<div class="row-fluid">
    <div class="span7 offset2 well">
        <h3>Add network:</h3>
        <hr />
        <form class="form-horizontal" method="post" action="">
            {% csrf_token %}
            {{ net_form }}
            <h4>Add a range to the network:</h4>
            <hr />
            <div class="form-inline">
                {{ range_form }}
            </div>
            <hr />
            <button type="submit" class="btn btn-primary btn-large">Add network</button>
        </form>
    </div>
</div>

{% endblock %}
Now, there most be something obvious i'm missing here, just failing to make the last connection. If somebody could enlighten me that would be great.
PS: In case anybody wondered i validated my model by looking in MySQL Workbench, MySQL Commandline client, and manage.py dbshell and inspectdb, all id columns are present. I even dropped the whole db and recreated it with manage.py.
Its been grinding my gears for about a week now, so time to ask for help. If anybody would be so kind to help me solve this, it would be great!
Here is the traceback:
Environment:

Request Method: POST
Request URL: http://localhost:8000/network/add/

Django Version: 1.5
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django_nose',
 'networks')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in   get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  25.                 return view_func(request, *args, **kwargs)
File "/home/alexander/PycharmProjects/NOC/networks/views.py" in add_network
  29.             range_form.save()
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save
  370.                              fail_message, commit, construct=False)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in save_instance
  87.         instance.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
  546.                        force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
  650.                 result = manager._insert([self], fields=fields,    return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
  215.         return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
  1673.     return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  937.             cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py" in execute
  41.             return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
  127.                 six.reraise(utils.IntegrityError,   utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/mysql/base.py" in execute
  120.             return self.cursor.execute(query, args)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py" in execute
  174.             self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: IntegrityError at /network/add/
Exception Value: (1048, "Column 'network_id' cannot be null")

A:

You have at least four errors.
Firstly, you have to actually call is_valid: it is a method, not a property.
Secondly, form.save(commit=False) returns the model instance. It doesn't magically convert the form object into an instance. You need to assign it to a variable which you then set the extra attributes on.
Thirdly, you're doing the commit=False on the wrong object - you should be doing it on the one you subsequently want to modify.
Fourth, don't redirect unless the forms are valid.
So:
range_form = RangeForm(request.POST)
if net_form.is_valid() and range_form.is_valid():
    net_obj = net_form.save()
    range_obj = range_form.save(commit=False)
    range_obj.network = net_obj
    range_obj.save()
    return HttpResponseRedirect('/')
else:

    net_form = NetworkForm()
    range_form = RangeForm()

return render_to_response('networks/add.html', {
    "net_form": net_form,
    "range_form": range_form,
}, context_instance=RequestContext(request))

(And don't call things formsets when they're not, they're just forms. Except that of course you actually should probably be using inline formsets for the range forms, but that's a separate question.)

