[Django]-Django : ModelForm with OneToOneField

4👍

If you only have one additional field you want to add, you could add it to the UserForm.

class UserForm(ModelForm):

    enabled = forms.BooleanField(default=True)

    class Meta:
        model = User
        fields = ['name', 'email', ...]

Then, in your form_valid method you can set the value for the base_user. Since it’s a create view, I’m assuming you have to create it first.

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)

If you want to add more than one extra field, then you probably want separate forms for BaseUser and User. In this case, extending CreateView gets a bit tricky, and it might be simpler to use a function based view like in Rohit’s answer.

6👍

You can render 2 forms in your template:

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})

Leave a comment