Django:将“created by”字段添加到object

时间:2012-06-27 00:53:33

标签: django django-models django-forms

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

(models.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',)

我正在使用this question建议的最佳答案,并在几个小时之后撞到了墙上。

这是我的追溯。错误是 / 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"

2 个答案:

答案 0 :(得分: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不可为空,则保存方法中的createdBy块没有意义:它是必需的。关于它没有“如果”。

答案 1 :(得分:0)

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