django integrityerror将_id附加到我的属性名称的末尾

时间:2012-04-26 02:35:31

标签: django forms foreign-keys integrity

我已经阅读了一些关于整合错误的例子,这些错误是通过将_id附加到属性的末尾引起的,但是大多数都认为user_id不是我的错误 - 我正在处理设置外国人的初始值另一个模型的关键(食谱有fk到食谱)

所以这是我的追踪

IntegrityError at /cookbook/createrecipe/

(1048, "Column 'original_cookbook_id' cannot be null")

Request Method:     POST
Request URL:    http://127.0.0.1:8000/cookbook/createrecipe/
Django Version:     1.3.1
Exception Type:     IntegrityError
Exception Value:    

(1048, "Column 'original_cookbook_id' cannot be null")

Exception Location:     /Library/Python/2.6/site-packages/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg/MySQLdb/connections.py in defaulterrorhandler, line 36
Python Executable:  /usr/bin/python
Python Version:     2.6.1
def createrecipe(request):

        form = RecipeForm(request.POST)

        if request.method == 'POST':

            if form.is_valid():

                form = RecipeForm(initial = {'original_cookbook' : request.user.cookbooks.all()[0]})

                recipe = form.save()//error

...

            t = loader.get_template('cookbook/create_form.html')

            c = RequestContext(request, {

                'form': form,

            })

            data = {

            'form': t.render(c),

你可能会看到我有一个名为original_cookbook的foreign_key,我想将其设置为用户食谱的首字母。

任何想法可能导致这种情况我可以根据需要发送更多代码

感谢

snackerfish

1 个答案:

答案 0 :(得分:0)

.....

form = RecipeForm(request.POST)
if request.method == 'POST':
  if form.is_valid():
    recipe = form.save(commit=False)
    recipe.original_cookbook = request.user.cookbooks.all()[0]
    recipe.save()