在form.save()之前设置一个非null但未显示的django表单字段

时间:2011-05-06 05:53:30

标签: django django-forms

我在我的应用上使用django表单。我有一个这样的模型Client

class Client(models.Model):
    client_name = models.CharField(max_length=50)
    email = models.EmailField(max_length=75)
    password = models.CharField(max_length=128)
    is_active = models.BooleanField()
    last_login = models.DateTimeField(null=True)
    class Meta:
        db_table = u'client'

然后我有一些其他模型'资产, AssetType`,然后还指定一个允许客户定义自己资产的表单 - 资产类型由管理员创建。

class AssetType(models.Model):
    name = models.CharField(max_length=50)
    class Meta:
        db_table = u'assettype'

    def __unicode__(self):
        return self.name

class Asset(models.Model):
    name = models.CharField(max_length=50)
    type = models.ForeignKey(AssetType)
    number = models.CharField(max_length=20)
    client = models.ForeignKey(Client)
    class Meta:
        db_table = u'asset'

    def __unicode__(self):
        return self.name


class AssetForm(ModelForm):
    class Meta:
        model = Asset

现在,我的问题是,当客户端登录后,想要创建一个新的Asset,我AssetForm中的asset.html就像这样呈现在<FORM id="newasset_form" method="POST" action="/assets/"> {% csrf_token %} <TABLE cellpadding="3" border="0" cellspacing="5"> <tr><th colspan="2">define a new asset</th></tr> {{ form }} <td align="center" colspan="2"><input type="submit" name="btn" id="btn" value="create asset" /></td> </TABLE> </FORM> 中:

client

在显示给客户端的结果表单上,此设置会将新Asset的{​​{1}}字段显示为select,其中包含所有现有客户的下拉列表,我想要的内容避免。我希望该客户端字段自动链接到其会话创建表单的客户端 - 当前登录的客户端,并且不允许他们将client设置为任何其他客户端。那怎么办呢?

在发布AssetForm之后,我尝试过这样做,将此客户端分配给表单的客户端字段,然后保存,但它不起作用!

if request.method == 'POST':
        asset_form = AssetForm(request.POST)
        if asset_form.is_valid():
            asset_form.client = client
            asset_form.save()

我想将表单定义为:

class AssetForm(ModelForm):
    class Meta:
        model = Asset
        exclude = ('client')

这样客户在创建新资产时根本无法篡改client字段。

1 个答案:

答案 0 :(得分:2)

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

使用save方法(docs)的commit参数:

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

或创建一个设置客户端的Asset实例,并将其用于创建表单的实例参数:

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))