Get the user logged in to the form

Asked

Viewed 321 times

0

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

Note: Working with class based view.

Note: 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

1 answer

0


You have to override your form’s init.

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 don’t understand the filter you want to make but I believe I can understand.

In your view, as you are using class based view, it is worth taking a look at the documentation. But you have to overwrite an existing method to send the user to the form.

class MinhaView(CreateView):
    ...
    def get_initial(self):
        return {'usuario':self.request.user}
  • I have already solved, reading a lot the doc. I did so, vlw.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.