django表单提交类的实例

时间:2015-07-01 16:31:22

标签: python django django-forms

我有以下views.py:

def address_save(request, cid=0, id=0):
    context = {}
    address = None
    try:
        if cid >= 1:
            client = Client.objects.get(pk=cid)
    except Client.DoesNotExist:
        return redirect('clients_list')

    try:
        if id >= 1:
            address = Address.objects.get(pk=id)
    except Address.DoesNotExist:
        pass

    address_form = AddressForm(request.POST or None, instance=address, initial={'client': client.id})

    if request.POST:
        if address_form.is_valid():
            address_form.save()
            return redirect('/business/clients/%d' % cid)

    context.update({
        'address_form': address_form,
    })
    return render(request, 'address/add.html', context)

我的表格看起来像这样:

class AddressForm(forms.ModelForm):

    client = forms.CharField(widget=forms.HiddenInput)

    class Meta:
        model = Address
        fields = [
            'type',
            'address_line1',
            'address_line2',
            'address_line3',
            'city',
            'postcode',
            'county',
            'country',
            'client'
        ]

My Traceback错误如下所示:

Environment:


Request Method: POST
Request URL: http://cic.js.dev/business/address/save/client/2

Django Version: 1.8.1
Python Version: 2.7.8
Installed Applications:
('django_admin_bootstrapped',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'bootstrap3_datetime',
 'business',
 'bootstrapform',
 'debug_toolbar')
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/vhosts/cic/cic/business/views.py" in address_save
  144.         if address_form.is_valid():
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  184.         return self.is_bound and not self.errors
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/forms/forms.py" in errors
  176.             self.full_clean()
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  394.         self._post_clean()
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
  427.         self.instance = construct_instance(self, self.instance, opts.fields, construct_instance_exclude)
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/forms/models.py" in construct_instance
  62.             f.save_form_data(instance, cleaned_data[f.name])
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in save_form_data
  874.         setattr(instance, self.name, data)
File "/home/bs/envs/cic/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
  627.                     self.field.rel.to._meta.object_name,

Exception Type: ValueError at /business/address/save/client/2
Exception Value: Cannot assign "u'2'": "Address.client" must be a "Client" instance.

对我来说问题是,如何在我的客户端外键(已经可以使用)上创建一个HIDDENField并为is_valid方法创建模型?

1 个答案:

答案 0 :(得分:0)

我真的不知道你为什么要这样做。您在视图中有客户端ID;根本没有必要将它发送到模板并再次发回。

相反,只需在保存时设置客户端ID:

if address_form.is_valid():
   address = address_form.save(commit=False)
   address.client_id = cid
   address.save()