Error in the user’s Manytomanyfield link

Asked

Viewed 25 times

-1

I’ve created a routine where you register a cost center. This cost center is linked through a Manytomanyfield when I register the User. Below the models.py of these registration:

user models:

class Usuario(models.Model):
    primeiro_nome = models.CharField(max_length=70)
    ultimo_nome = models.CharField(max_length=70)
    email = models.EmailField(max_length=100)
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    centrodecusto_usuario = models.ManyToManyField(CentroDeCusto, blank=True)
    perfil_usuario = models.ForeignKey(Perfil, on_delete=models.PROTECT, null=True, blank=True)
    permissao_usuario = models.ForeignKey(Permissao, on_delete=models.PROTECT, null=True, blank=True)


    def get_absolute_url(self):
        return reverse('list_usuario')


    def __str__(self):
        return self.primeiro_nome

And this is the cost center model:

class CentroDeCusto(models.Model):
    numero_centro = models.CharField(max_length=70)
    nome_centro = models.CharField(max_length=70)
    centro_de_custo = models.CharField(max_length=70)
    user_respon = models.OneToOneField(User, on_delete=models.PROTECT)
    vinculo_natureza = models.ManyToManyField(NaturezaOrcamentaria)

    def get_absolute_url(self):
        return reverse('list_centrodecusto')


    def __str__(self):
        return self.centro_de_custo

After that I created a model where a budget will be registered. This budget is registered informing the cost center, a budget nature, the date and the value. According to the Model below:

class  CadastroOrcamento(models.Model):
    cc_cadastro_orcamento = models.ForeignKey(CentroDeCusto, on_delete=models.PROTECT, null=True, blank=True)
    no_cadastro_orcamento = models.ForeignKey(NaturezaOrcamentaria, on_delete=models.PROTECT, null=True, blank=True)
    valor_cadastro_orcamento = models.DecimalField(max_digits=10, decimal_places=2)
    data_cadastro_orcamento = models.DateField(null=True, blank=True)
    obs_cadastro_orcamento = models.CharField(max_length=1000)


    def get_absolute_url(self):
        return reverse('list_cadastro_orcamento')


    def __str__(self):
        return self.obs_cadastro_orcamento

What I want to do: when the user enters to register the budget, where he will inform the cost center, will only appear the cost centers that he was linked in the user registration models.

What I tried to do: I created a Forms.py inside my app where I register my budget. In it I put the condition to appear only the cost center that the user was linked, as below:

class CadastroOrcamentoForm(ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(CadastroOrcamentoForm, self).__init__(*args, **kwargs)
        self.fields['cc_cadastro_orcamento'].queryset = Usuario.objects.filter(centrodecusto_usuario=user.usuario.centrodecusto_usuario)

    class Meta:
        model = CadastroOrcamento
        fields = ['cc_cadastro_orcamento', 'no_cadastro_orcamento', 'no_cadastro_orcamento', 'valor_cadastro_orcamento', 'data_cadastro_orcamento', 'obs_cadastro_orcamento']

In my views where I edit and create the budget I put the following codes:

Budget edit:

class CadastroOrcamentoEdit(LoginRequiredMixin, UpdateView):
    model = CadastroOrcamento
    form_class = CadastroOrcamentoForm

    def get_form_kwargs(self):
        kwargs = super(CadastroOrcamentoList, self).get_form_kwargs()
        kwargs.update({'user': self.request.user})
        return kwargs

budget:

class CadastroOrcamentoCreate(LoginRequiredMixin, CreateView):
    model = CadastroOrcamento
    form_class = CadastroOrcamentoForm

    def get_form_kwargs(self):
        kwargs = super(CadastroOrcamentoCreate, self).get_form_kwargs()
        kwargs.update({'user': self.request.user})
        return kwargs

do the makemigrations and migrate and all is well. When I enter to register the budget give me the following error track:

System check identified no issues (0 silenced).
February 07, 2020 - 19:56:08
Django version 3.0.2, using settings 'financial_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Internal Server Error: /cadastro-orcamento/novo/
Traceback (most recent call last):
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1768, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'ManyRelatedManager'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch
    return super().dispatch(request, *args, **kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/views/generic/edit.py", line 168, in get
    return super().get(request, *args, **kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/views/generic/edit.py", line 133, in get
    return self.render_to_response(self.get_context_data())
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/views/generic/edit.py", line 66, in get_context_data
    kwargs['form'] = self.get_form()
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/views/generic/edit.py", line 33, in get_form
    return form_class(**self.get_form_kwargs())
  File "/Users/felipegomes/financial_project/apps/cadastro_orcamento/forms.py", line 9, in __init__
    self.fields['cc_cadastro_orcamento'].queryset = Usuario.objects.filter(centrodecusto_usuario=user.usuario.centrodecusto_usuario)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/query.py", line 904, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1350, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1381, in _add_q
    check_filterable=check_filterable,
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1311, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1165, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/lookups.py", line 22, in __init__
    self.rhs = self.get_prep_lookup()
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/fields/related_lookups.py", line 115, in get_prep_lookup
    self.rhs = target_field.get_prep_value(self.rhs)
  File "/Users/felipegomes/financial_project/venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1772, in get_prep_value
    ) from e
TypeError: Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x10bb44fd0>.
[07/Feb/2020 19:56:17] "GET /cadastro-orcamento/novo/ HTTP/1.1" 500 151588

I’ve searched everything on the Internet and found nothing to help me.

If you can help me it will be well worth.

1 answer

0

I set the filter on Forms and it worked. It stayed that way:

self.fields['cc_cadastro_orcamento'].queryset = user.usuario.centrodecusto_usuario.all()

Browser other questions tagged

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