Get the user logged in form

0

Hello! I need to get the user that is logged in to my application, because in the form I have fields modelChoice, and the query need to bring by logged in user, as shown below:

Note: I work with class based view.

Obs2: Django 1.10

from django import forms
from core.models.documento import *
from core.models.forma_pagamento import *
from core.models.local_compra import *
from core.models.tipo_documento import *

class DocumentoForm(forms.ModelForm):
   descricao = forms.CharField(label='Descrição:')
   forma_pagamento = forms.ModelChoiceField(label='Forma de pagamento:',queryset=FormaPagamento.objects.all())

class Meta:
    model = Documento
    
asked by anonymous 30.03.2017 / 16:12

1 answer

0

You have to make an init override of your form.

class MeuForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(MeuForm, self).__init__(*args, **kwargs)
        usuario = kwargs['initial']['usuario']
        self.fields['forma_pagamento'].queryset = FormaPagamento.objects.filter(usuario=usuario)

I do not understand the filter you want to do but I believe you can understand.

In your view, since you are using class based view, it is worth reading the documentation. But you have to override an existing method for the user to be sent to the form.

class MinhaView(CreateView):
    ...
    def get_initial(self):
        return {'usuario':self.request.user}
    
10.04.2017 / 16:15