Django form with fields from two different models

I need to display one form with several fields from two different models. The form will contain only part of the fields from the models, and the layout will be made using crispy forms.

My models:

class Company(BaseModel):
    title = models.CharField(_('Company'), max_length=128)
    domain = models.CharField(_('Domain'), max_length=128)
class Account(BaseModel):
    company = models.ForeignKey(Company)
    user = models.OneToOneField(User)
    role = models.CharField(_('Role'), choices=ROLES, default='member', max_length=32)

Fields that I want to display in the form: company name, username, user name, user email address

Is it possible? How can i do this?

+4
source share
2 answers

Other answers on this page include the rejection of the benefits of model forms and perhaps the need to duplicate some of the features that you get for free.

, html!= django. , html.

, . Django , POST , - .

:

class CompanyForm(forms.ModelForm):
    class Meta:
        fields = [...]
        model = Company

class AccountForm(forms.ModelForm):
    class Meta:
        fields = [...]
        model = Account

:

if request.method == 'POST':

    company_form = CompanyForm(request.POST)
    account_form = AccountForm(request.POST)

    if company_form.is_valid() and account_form.is_valid():

        company_form.save()
        account_form.save()
        return HttpResponseRedirect('/success')        

    else:
        context = {
            'company_form': company_form,
            'account_form': account_form,
        }

else:
    context = {
        'company_form': CompanyForm(),
        'account_form': AccountForm(),
    }

return TemplateResponse(request, 'your_template.html', context)

:

<form action="." method="POST">
    {% csrf_token %}
    {{ company_form.as_p }}
    {{ account_form.as_p }}
    <button type="submit">
</form>
+4

forms.py

from django import forms


class YourForm(forms.Form):
    title = forms.CharField()
    first_name = forms.CharField()
    last_name = ...

view.py

from forms import YourForm
from django import views
from models import Company, Account

class YourFormView(views.FormView)
    template_name = 'some_template.html'
    form_class = YourForm
    success_url = '/thanks/'

    def form_valid(self, form):
        title = form.cleaned_data['title']
        ...
        # do your processing here using Company and Account
        # i.e. company = Company.objects.create(title=title, ...)
        #      account = Account.objects.get_or_create(
        #      user=..., company=company ...)
        #      ... more processing
        #
        # Call company.save() and account.save() after adding
        # your processed details to the relevant instances
        #  and return a HttpResponseRedirect(self.success_url)

    def is_valid(self):
        # don't forget to validate your fields if need be here

, . https://docs.djangoproject.com/en/1.7/topics/forms/

+1

All Articles