我有两个由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
我想更改用户模板中的已启用属性,但我只能访问User
的字段(名称,电子邮件...)。
我该怎么做呢?
答案 0 :(得分:6)
您可以在模板中渲染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})
答案 1 :(得分:4)
如果您只想添加一个额外字段,则可以将其添加到UserForm
。
class UserForm(ModelForm):
enabled = forms.BooleanField(default=True)
class Meta:
model = User
fields = ['name', 'email', ...]
然后,在form_valid
方法中,您可以设置base_user
的值。由于它是一个创建视图,我假设你必须先创建它。
class UserCreate(generic.CreateView):
def form_valid(self, form):
base_user = BaseUser.objects.create(
enabled=form.cleaned_data['enabled']
)
form.instance.base = base_user
return super(UserCreate, self).form_valid(form)
如果您想添加多个额外字段,则可能需要BaseUser
和User
的单独表单。在这种情况下,扩展CreateView
会有点棘手,使用基于函数的视图可能更简单,就像在Rohit的回答中一样。