How to pass active user to Django ModelForms

  django, python

In my form, I must filter the "tenant" choice field so that it displays only tenants associated to the active user’s organization. So I’m simply passing an extra argument to the form constructor. This works as expected when I load (GET) the form.

But when I submit (POST) the form, I keep getting the following error:

AttributeError: 'NoneType' object has no attribute 'organization_profile'

Any idea what’s provoking this?

Views.py

def create_booking(request):
    if request.method == "POST":
        form = BookingCreateForm(data=request.POST)
        if form.is_valid():
            data = form.cleaned_data
            booking = Booking.objects.create(
                status=data['status'],
                tenant = data['tenant'],
                apartment = data['apartment'],
                check_in = data['check_in'],
                check_out = data['check_out'],
                rent = data['rent'],
            )
            booking.save()

            return redirect('dashboard:dashboard')

    else:
        form = BookingCreateForm(user=request.user)
    return render(request, 'accounts/booking_form.html', {'form': form})

Forms.py

class BookingCreateForm(forms.ModelForm):
    class Meta():
        model = Booking
        fields = '__all__'
    
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user',None)
        super(BookingCreateForm, self).__init__(*args, **kwargs)
        organization = self.user.organization_profile
        self.fields['tenant'] = forms.ChoiceField(choices=[
            (tenant.id, tenant.name)) for tenant in TenantProfile.objects.filter(organization=organization)
        ])

Source: Python Questions

LEAVE A COMMENT