[Answered ]-Set a non-null, but non-displayed django form field before form.save()

2👍

class AssetForm(ModelForm):
    class Meta:
        model = Asset
        exclude = ('client',) # don't forget that comma

Use the commit argument of the save method (docs):

if asset_form.is_valid():
    instance = asset_form.save(commit=False)
    instance.client = client
    instance.save()

or create an instance of Asset where client is set and use that for the instance argument of creating your form:

def someview(request):
    client = Client.objects.get(pk=<some_pk>)
    asset = Asset(client=client)
    if request.method == 'POST':
        form = AssetForm(request.POST, instance=asset)
        if form.is_valid():
            form.save()
            return HttpResponse('success')
    else:
        form = AssetForm(instance=asset)

    context = {'form':form}
    return render_to_response('some_template.html', context,
            context_instance=RequestContext(request))
👤dting

Leave a comment