Django:为ModelForms添加默认值

时间:2017-06-20 23:41:17

标签: django

我正在研究django中的一个小项目,我正在尝试使用由用户填写的表单并将其存储在数据库中。对于表单,我使用ModelForm而不是标准Form。

用户使用表单创建的组的名称和描述提交表单。我想在将新对象放入数据库之前,将默认值添加到模型中的表单值。

这是Form.py

from django import forms
from django.forms import ModelForm
from tab.models import Group

member_count_choices = (('bronze', '1-4',),
                        ('silver', '5-7',),
                        ('gold', '8-10',),
                        ('platnium', '11+',))

class CreateGroupForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ['name', 'description']

这是views.py

from django.shortcuts import render, get_object_or_404, redirect
from django.db import transaction

from .models import Group, User
from .forms import CreateGroupForm, AddMembersFour, AddMembersSeven
from .forms import AddMembersTen, AddMembersEleven

# the following def is going to be what grabs all of the different groups that
# are in the database
# filters can be added later

def groups(request):
    # following is all of th actions that are taken after the form is submitted
    if request.method == 'POST':
        createGroup = CreateGroupForm(request.POST)
        if createGroup.is_valid():
            cd = createGroup.cleaned_data
            groupName = cd['name']
            groupDescription = cd['description']
            groupDefaultLevel = 1
            groupDefaultStatus = 1
            groupDefaultCreatedBy = User.objects.get(username='omar')
            new_group = createGroup
            new_group.name = groupName
            new_group.description = groupDescription
            new_group.levels = groupDefaultLevel
            new_group.status = groupDefaultStatus
            new_group.created_by = groupDefaultCreatedBy
            new_group.save()
            return redirect('/tab/addMembers')

这是Models.py文件

from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User

class Group(models.Model):
    name = models.CharField(max_length = 25)
    description = models.CharField(max_length = 250)
    levels = models.SmallIntegerField()
    status = models.SmallIntegerField()
    created_by = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)

如你所见。我正在尝试为组模型的级别,状态,created_by和create添加默认值。 created_by是我从管理站点创建的随机用户。

以下是本地网站的说法:

IntegrityError at /tab/createGroup/
NOT NULL constraint failed: tab_group.levels
Request Method: POST
Request URL:    http://127.0.0.1:8000/tab/createGroup/
Django Version: 1.8.6
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: tab_group.levels
Exception Location: C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 318
Python Executable:  C:\Users\OmarJandali\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.1
Python Path:    
['C:\\Users\\OmarJandali\\Desktop\\opentab\\opentab',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36',
 'C:\\Users\\OmarJandali\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
Server time:    Tue, 20 Jun 2017 23:03:09 +0000

所以我只需要知道在将表单保存到数据库之前如何向表单添加默认值。任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

因为您使用的是模型表单,所以您可以设置字段模型的默认值。它看起来像这样:

class Group(models.Model):
  name = models.CharField(max_length = 25)
  description = models.CharField(max_length = 250, blank=True)
  levels = models.SmallIntegerField(default=0)
  status = models.SmallIntegerField(default=0)
  created_by = models.ForeignKey(User, on_delete=models.CASCADE)
  created = models.DateTimeField(auto_now_add=True