Django - 初始化注册特定字段而不呈现表单

我是新手,我使用的是Python 2.7.15,它不是Django REST Framework . 有我的表格:

class RegForm(UserCreationForm):
   telephone = forms.CharField(required=False)
   user_type = forms.ChoiceField(required=False)

   class Meta:
       model = User
       fields = (
           'username', 'first_name', 'last_name',
           'telephone', 'groups', 'user_type',
           'password1', 'password2', 'email'
                 )

字段:first_name,last_name,telephone,email,password1和password2由移动POST请求提供 .

还有其他我想在保存期间初始化的字段......但是出现了问题 .

很少有像群组和用户名这样的其他字段......所以我必须将它们添加到

request.POST['username'] = some_function()
request.POST['groups'] = [1, 2]

它的工作原理

但我有问题传递组,我需要推两个值(组ID = 1和2)当我尝试 request.POST['username'] = [1, 2] ,然后 form = RegForm(request.POST) 它传递但内部的值是 [[1, 2]] (双列表),而不是 [1, 2] .

我不知道如何解压 request.POST['username']request.POST['username'] 将同时进行

request.POST['username'] = 1

request.POST['username'] = 2

我试过了:

request.POST['username'] = 1, 2

request.POST['username'] = (1, 2)

request.POST['username'] = {1, 2}

request.POST['username'] = {1: 1, 2: 2}

list = [1,2] request.POST ['username'] = * list#its python 2.7.15

或者也许有另一种方法来初始化这些字段?我在内部表单类中尝试过:

def __init__(self, *args, **kwargs):
       super(Registration123Form, self).__init__(*args, **kwargs)
       self.prepare()

def prepare(self):
       for key in ('email', 'first_name', 'last_name', 'password1', 'password2'):
           self.fields[key].required = True

       self.fields['groups'].initial = self._get_groups()
       print("Groups:", self._get_groups())
       self.fields['user_type'].initial = self._get_user_type()
       self.fields['username'].initial = #something

但没有任何作用!似乎我必须渲染初始字段才能起作用; /

我正在尝试使用由Django UserCreationForm准备的快速检查请求中的所有内容并保存....

我试图避免做这样的事情:

#check passwords (my function)
#check emails (my function)
#check phone (my function)

User.object.create()

#save every value to newly created object

回答(0)