0

我需要在数据库中存储正在创建特定对象的用户,如下所示:

(模型.py)

class Address(models.Model):
createdBy = models.ForeignKey(User)
address1 = models.CharField("Address Line 1", max_length=40)
address2 = models.CharField("Address Line 2", max_length=40, blank=True)
city = models.CharField(max_length=20)
state = models.CharField(max_length=3)
zipCode = models.CharField("Postal Code", max_length=10)

我处理表单的观点在这里(views.py):

def handlePopAdd(request, addForm, field):
if request.method == "POST":
    form = addForm(request.POST)
    if form.is_valid():
        try:
            newObject = form.save(request)
        except forms.ValidationError, error:
            newObject = None
        if newObject:
            return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>'% (escape(newObject._get_pk_val()), escape(newObject)))
else:
    form = addForm()
pageContext = {'form': form, 'field': field}
return render_to_response("address_popup.html", pageContext, context_instance=RequestContext(request))

最后,这是我的表单代码:(forms.py)

class AddressForm(forms.ModelForm):

def __init__(self, *args, **kwargs):
    self.request = kwargs.pop('request', None)
    return super(AddressForm, self).__init__(*args, **kwargs)

def save(self, *args, **kwargs):

    obj = super(AddressForm, self).save(commit=False)
    if self.request:
        obj.createdBy = self.request.user
    obj.save()

class Meta:
    model = Address
    exclude = ('createdBy',)

我正在使用这个问题建议的最佳答案,并且在盯着这个洞几个小时后撞到了墙上。

这是我的回溯。错误是/app/address/add/ 处的 IntegrityError(1048,“列 'createdBy_id' 不能为空”)

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)
File "/home/matthew/lessonhelper/../lessonhelper/lessons/views.py" in address_add
  78.   return handlePopAdd(request, AddressForm, 'address')
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)
File "/home/matthew/lessonhelper/../lessonhelper/lessons/views.py" in handlePopAdd
  66.               newObject = form.save(request)
File "/home/matthew/lessonhelper/../lessonhelper/lessons/forms.py" in save
  29.       obj.save()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py" in save
  460.         self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py" in save_base
  553.                     result = manager._insert(values, return_id=update_pk, using=using)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py" in _insert
  195.         return insert_query(self.model, values, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in insert_query
  1436.     return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  791.         cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py" in execute_sql
  735.         cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py" in execute
  34.             return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/mysql/base.py" in execute
  86.             return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py" in execute
  166.             self.errorhandler(self, exc, value)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py" in defaulterrorhandler
  35.     raise errorclass, errorvalue

Exception Type: IntegrityError at /app/address/add/
Exception Value: (1048, "Column 'createdBy_id' cannot be null"
4

2 回答 2

2

您专门定义了将请求添加到表单的逻辑,但没有使用它。

您需要将表单实例request化为关键字参数(根据您的代码)。

form = addForm(request.POST, request=request)

save(request)对请求不做任何事情。

大多数人更喜欢只接受save().

def save(self, request):
    obj = super(AddressForm, self).save(commit=False)
    obj.createdBy = request.user
    obj.save()

最后,如果不能为空if,则 save 方法中的块没有意义:它是必需的。createdBy没有“如果”。

于 2012-06-27T01:26:47.193 回答
0

您排除了createdBy表单中的字段,根据您的模型定义,这是一个必填字段,因为您使用的是 ModelForm。

于 2012-06-27T01:13:15.397 回答