我有一个模型Sachbearbeiter
,它扩展了我的用户模型。
from django.contrib.auth.models import User
class Sachbearbeiter(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
verein = models.ForeignKey(Verein)
现在,我需要CreateView表单来创建一个新 Sachbearbeiter
实例,该实例会立即链接到新 User
实例。
表单应包含以下字段:
First Name: [textfield]
Last Name: [textfield]
Email Address: [textfield]
Verein: [Dropdown that lists `Vereine`]
我试过的是:
class SachbearbeiterForm(ModelForm):
class Meta:
model = Sachbearbeiter
fields = '__all__' # Go into detail once it's working
class UserForm(ModelForm):
class Meta:
model = User
fields = '__all__' # Go into detail once it's working
SachbearbeiterFormSet = inlineformset_factory(User, Sachbearbeiter, fields='__all__')
class SachbearbeiterCreate(CreateView):
form_class = SachbearbeiterFormSet
但这给了我一个看起来像这样的表格:
Verein: [Dropdown that lists `Vereine`]
Delete? [checkbox]
这是否可行,或者我是否必须为此创建自定义表单?
答案 0 :(得分:0)
这不是我想要的解决方案,但效果很好。因此,我不会将其标记为答案。
我必须创建一个自定义视图,并且只能在其中使用两个表单。 (在代码示例中,我省略了不重要的内容。
在ModelForms中,我只将fields
属性更改为只包含我想要显示的字段。
def my_view(request):
...
if request.method == 'POST':
if user_form.is_valid() and sachbearbeiter_form.is_valid():
user = user_form.save(commit=False)
user.username = user.email
user.save()
sachbearbeiter = sachbearbeiter_form.save(commit=False)
sachbearbeiter.user = user
sachbearbeiter.save()
...
return redirect('sachbearbeiter_create_or_edit', username=user.username)
模板看起来像这样:
{% if user_form.errors or sachbearbeiter_form.errors %}
<div class="alert alert-danger" role="alert">
Please correct the errors indicated by red color.
</div>
{% endif %}
<form method="post" action="#">
{{ user_form.as_p }}
{{ sachbearbeiter_form.as_p }}
</form>