Generate a context from another instance in Createview

Asked

Viewed 59 times

0

Hello! I need to render a context in the Createview template.

no requeste to passing an id, and I want to put the name of that id in the Createview template

py.url

urlpatterns = [
   path('editar_receita/<int:pk>', ReceitaEditar.as_view(), 
   name='add_ingrediente')
]

view py.

class ReceitaEditar(LoginRequiredMixin, CreateView):
    model = ProdutoReceita
    form_class = ProdutoRceitaForm


def get_form_kwargs(self):
    kwargs = super(ReceitaEditar, self).get_form_kwargs()
    kwargs.update({
        'empresa': self.request.user.cadastropessoas.id,
        'pk': self.kwargs['pk']
    })
    return kwargs

Forms.py

class ProdutoRceitaForm(forms.ModelForm):

    def __init__(self, empresa, pk, *args, **kwargs):
        super(ProdutoRceitaForm, self).__init__(*args, **kwargs)
        self.empresa_user = PessoasEmpresa.objects.get(pessoa=empresa)
        self.fields['produto'].queryset = Produto.objects.filter(
            ~Q(categoria=2),
            empresa=self.empresa_user.empresas
        )

    class Meta:
        model = ProdutoReceita
        fields = [
            'produto',
            'quantidade',
            'unidademedida',
            'obs'
        ]

productor_form.html

{% extends 'base.html' %}
{% load bootstrap %}

{% block principal%}
<div class="container">
   <form method="post">
       {% csrf_token %}
       {{ form |  bootstrap }}
       <button type="submit" class="btn btn-info">Adicionar</button>
   </form>
</div>

{% endblock %}

1 answer

1

CreateView should be used only to create objects. To edit them you must user UpdateView and then pass the id of the object you want to edit.

In the documentation of CreateView and UpdateView you can see the difference between them.

  • I passed the ID because I need this id to create an instance in the model. because the tables are N:M.

Browser other questions tagged

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