我有两个模型链接OneToOneField
:
class User(models.Model): name = models.CharField(max_length=100, unique=True) email = models.EmailField(blank=True) base = models.OneToOneField(BaseUser) ... class BaseUser(models.Model): enabled = models.BooleanFiled(default=True) ...
我使用ModelForm来显示用户的属性:
class UserForm(ModelForm): class Meta: model = User fields = ['name', 'email', ...]
在我看来:
class UserCreate(generic.CreateView): model = User template_name = 'user/create.html' success_url = reverse_lazy('users:list') form_class = UserForm
我想更改用户模板中的enabled属性,但我只能访问User
的字段(名称,电子邮件...).
我该怎么做呢?
您可以在模板中渲染2个表单:
def user_create(request): if request.method == "POST": user_form = UserForm(data=request.POST) baseuser_form = BaseUserForm(data=request.POST) if user_form.is_valid() and baseuser_form.is_valid(): base_user = baseuser_form.save() user = user_form.save(commit=False) user.base = base_user user.save() return redirect(reverse_lazy('users:list')) else: .... else: user_form = UserForm() baseuser_form = BaseUserForm() return render_to_response('user/create.html', {'user_form': user_form, 'baseuser_form': baseuser_form})