Django - ModelForm因为缺少用户ID

时间:2017-02-10 12:01:43

标签: django

我明白了:

IntegrityError at /category/
NOT NULL constraint failed: transactions_category.user_id

在我看来:

    elif "create" in request.POST:
        createform = CategoryForm(data=request.POST)
        createform.save(commit=False)
        createform.user = request.user
        createform.save() <--- specifically here, the .save with commit=False goes through and I can also set the user

我使用调试器检查并且createform.user有一个用户,该用户也有一个id。

forms.py:

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        exclude = ["subcategory", "user"]

models.py:

class Category(models.Model):
    title = models.CharField(max_length = 100)
    subcategory = models.ManyToManyField("self", blank=True, symmetrical=False)
    user = models.ForeignKey(User)

用户导入是:

from django.contrib.auth.models import User

为什么不能保存?我在调用.save()之前设置了用户,就调试器而言,用户是设置的(并且有一个id)?

我已经运行了manage.py migrate和manage.py makemigrations,一切都是最新的。

编辑:

模板:

<p>Create new category form</p>
<form action="/category/" method="post">
    {% csrf_token %}
    {{ createform.as_p }}
    <input type="submit" name="create" value="Create new category">
</form>
<hr>

在我将“用户”字段添加到模型之前,新类别对象的创建和保存工作(我之后运行了migrate和makemigrations)

编辑2: 完整视图:

def category_view(request):
    createform = CategoryForm()
    searchform = CategorySearchForm()
    categories = Category.objects.all()
    categories_left = []
    categories_right = []

    if request.method == "POST":
        if "search" in request.POST:
            categories_left = Category.objects.for_title(request.POST["left-search"], user=request.user)
            categories_right = Category.objects.for_title(request.POST["right-search"], user=request.user)
        elif "create" in request.POST:
            createform = CategoryForm(request.POST)
            if createform.is_valid():
                createform.save(commit=False)
                createform.user = request.user
                createform.save()
        elif "add-subcategory" in request.POST:
            left = Category.objects.for_id(request.POST["left-category"], user=request.user)
            right = Category.objects.for_id(request.POST["right-category"], user=request.user)
            try:
                left.subcategory.add(right)
                old = left
                old.pk = None
                old.save()
            except IntegrityError:
                print("This combination already exists.") # TODO
    context = {"createform":createform, 
               "searchform":searchform,
               "categories":categories,
               "categories_left":categories_left,
               "categories_right":categories_right}
    return render(request, "transactions/category_creation.html", context)

2 个答案:

答案 0 :(得分:1)

尝试保存传递用户的实例。

createform.save(commit=False)
createform.instance.user = request.user
createform.save() 

答案 1 :(得分:1)

表单的save方法返回一个实例。您应该更新并保存实例,而不是尝试再次保存表单。

instance = createform.save(commit=False)
instance.user = request.user
instance.save()