我扩展了我的用户模型并添加了一些额外的字段。我希望能够通过Web界面(而不是管理员页面)添加新用户,因此需要某种形式。如何在数据库中创建这个新用户以及表单是什么样的?
class MyUser(models.Model):
user = models.OneToOneField(User)
custcode = models.CharField(max_length=30)
//这显然不起作用,但它是一个开始
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class UserCreateForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'custcode')
答案 0 :(得分:2)
由于你有两个模型,你需要两种形式。
auth.User
的一种表单和yourapp.MyUser
的一种表单。
在您看来,您将:
这应该有类似的东西
class MyUserCreationForm(forms.ModelForm):
class Meta:
model = User
exclude = ('user',)
# Exclude 'user' because we will set it manually
class MyView(View):
def get(self, request):
user_form = UserCreationForm(prefix='user')
myuser_form = MyUserCreationForm(prefix='myuser')
# Use prefix to avoid name conflicts
return render(...)
def post(self, request):
user_form = UserCreationForm(request.POST, prefix='user')
myuser_form = MyUserCreationForm(request.POST, prefix='myuser')
user_form_is_valid = user_form.is_valid()
myuser_form_is_valid = myuser_form.is_valid()
# Do form.is_valid() here in order to always call both
if user_form_is_valid and myuser_form_is_valid:
user = user_form.save()
myuser = myuser_form.save(commit=False)
myuser.user = user
myuser.save()
...
...
return ...
为了保持一致性,表单保存也应包含在事务中。但这是另一个话题。
答案 1 :(得分:1)
你可以这样做
class UserCreateForm(UserCreationForm):
custcode = form.CharField()
class Meta:
model = User
fields = ('username', 'custcode')
并为您编写自定义保存功能
def save(self, commit=True):
user = super(UserCreateForm, self).save(commit=True)
myuser = MyUser.objects.get_or_create(user=user)[0]
myuser.save()