2017-02-10 99 views
0

我得到:Django的 - 的ModelForm不保存由於缺少用戶ID

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> 

之前,我添加了「用戶」字段模型(和我跑遷移和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) 

回答

1

嘗試保存傳遞用戶的實例。

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

窗體的保存方法返回一個實例。您應該更新並保存實例,而不是嘗試再次保存表單。

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