2

I have a model Sachbearbeiter which extends my User model.

from django.contrib.auth.models import User

class Sachbearbeiter(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    verein = models.ForeignKey(Verein)

Now I need CreateView form to create a new Sachbearbeiter instance that is immediately linked to a new User instance.

The form should have the following fields:

First Name:    [textfield]  
Last Name:     [textfield]
Email Address: [textfield]
Verein:        [Dropdown that lists `Vereine`]

What I tried is this:

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

But this gives me a form that looks like this:

Verein:        [Dropdown that lists `Vereine`]
Delete?        [checkbox]

Is this even possible, or do I have to create a custom form for that?

Daniel
  • 3,092
  • 3
  • 32
  • 49

1 Answers1

0

This is not the solution I was looking for, but works well. Because of that, I won't mark it as an answer, though.


I had to create a custom view and was able to simply use both forms inside it. (In the code example I omitted the unimportant stuff.

In the ModelForms I only changed the fields attribute to have only the fields I want to show.

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)

The template looks something like that:

{% 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>
Daniel
  • 3,092
  • 3
  • 32
  • 49