Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Pass Request Data to Forms.py

The scenario;

We got a from with fields and inside form there is a combobox, it fills with items.

We have tenancy and every user got TenantID so when A1 user(tenantid 1) calls create form, we need to filter that combobox to filter only A1 UserItems with using Query Filtering.

Similarly for other tenants.

How can I pass that dynamic tenantid.

Btw for every user tenantid stored in abstracted class django core USER- added new field tenantid. Any advice Im open for it, thank you for your attention.

State: Solved !

Forms.py

class ItemForm(forms.ModelForm):
    class Meta:
        model = Items
        fields = ('id', 'item', 'start', 'end')
        widgets = {
            'start': DateTimePickerInput(format='%Y-%m-%d %H:%M'),
            'end': DateTimePickerInput(format='%Y-%m-%d %H:%M'),
        }

    def __init__(self, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        self.fields['item'].queryset = Items.objects.filter(tenantid=int(User.tenantid))

views.py

@login_required()
def create_item_record(request):
    if request.method == 'POST':
        form = ItemForm(request.POST)
    if request.method == 'GET':
        tenantidX = request.user.tenantid
        form = ItemForm()
    return save_item_form(request, form, 'items_create_partial.html')
like image 314
BCA Avatar asked Sep 25 '19 08:09

BCA


2 Answers

Just pass user from request to your form:

class ItemForm(forms.ModelForm):
    class Meta:
        model = Items
        fields = ('id', 'item', 'start', 'end')
        widgets = {
            'start': DateTimePickerInput(format='%Y-%m-%d %H:%M'),
            'end': DateTimePickerInput(format='%Y-%m-%d %H:%M'),
        }

    def __init__(self, user, *args, **kwargs):
        super(ItemForm, self).__init__(*args, **kwargs)
        self.fields['item'].queryset = Items.objects.filter(tenantid=int(user.tenantid))

@login_required()
def create_item_record(request):
    if request.method == 'POST':
        form = ItemForm(request.user, request.POST)
    if request.method == 'GET':
        form = ItemForm(request.user)
    return save_item_form(request, form, 'items_create_partial.html')
like image 164
GwynBleidD Avatar answered Nov 01 '22 04:11

GwynBleidD


the best and easy way of getting current request with using "django -crum" https://pypi.org/project/django-crum/ .

pip install django-crum

after that add to settings.py

# settings.py
MIDDLEWARE_CLASSES = (
 'crum.CurrentRequestUserMiddleware',
...
)

include lib

from crum import get_current_request

request = get_current_request()

Then you can reach active request inside with request.user.tenantid

like image 4
BCA Avatar answered Nov 01 '22 05:11

BCA