gpt4 book ai didi

python - Django : ModelForm with OneToOneField

转载 作者:太空宇宙 更新时间:2023-11-03 12:38:23 27 4
gpt4 key购买 nike

我有 2 个模型通过 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})

关于python - Django : ModelForm with OneToOneField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34357081/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com