Render items with Django Forms. Three Models involved, unico Forms

Asked

Viewed 697 times

0

Hello, I’m having doubts to render my model’s items.

The system works as follows:

  • User taking an exam Exame.
  • Within each exam has the types of exam ItemExame
  • User generates a report Laudo that pulls the patient and the doctor who generated the report.
  • The table ExameLaudo Amara the ItemExame with the Laudo

Ex: (table) Scanned

1 inserir a descrição da imagem aqui

I need to render on screen the exams and the types of exam for the user to choose the exams performed.

And then save (post) the same.

models.py

class Exame(models.Model):
    descricao = models.CharField('Descrição', max_length=200)
    data_cadastro = models.DateTimeField(auto_now_add=True)
    ativo = models.BooleanField(default=True)

class ItemExame(models.Model):
    exame = models.ForeignKey(Exame, on_delete=models.CASCADE, related_name='exame')
    descricao_item = models.CharField('Descrição', max_length=300)
    data_cadastro = models.DateTimeField(auto_now_add=True)

class Laudo(models.Model):
    paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, related_name='paciente')
    medico = models.ForeignKey(Medico, on_delete=models.CASCADE)
    data_cadastro = models.DateTimeField(auto_now_add=True)
    data_atualizacao = models.DateTimeField(auto_now=True)

class ExameLaudo(models.Model):
    """ ExameLaudo - Aqui é onde amarra os laudos com o exame """
    laudo = models.ForeignKey(Laudo, on_delete=models.CASCADE, related_name='laudo')
    item_exame = models.ForeignKey(ItemExame, on_delete=models.CASCADE, related_name='item_exame')
    data_cadastro = models.DateTimeField(auto_now_add=True)

views.py

class CreateLaudoView(CreateView):
""" Gerador do Laudo """

template_name = 'laudo/laudo_form.html'
model = Laudo
fields = '__all__'

def get(self, request, *args, **kwargs):
    self.object = None
    form_class = self.get_form_class()
    form = self.get_form(form_class)
    return self.render_to_response(
        self.get_context_data(
            form=form
        )
    )

def post(self, request, *args, **kwargs):
    self.object = None
    form_class = self.get_form_class()
    form = self.get_form(form_class)


def form_valid(self, form):
    print('entrei aqui no valid')
    self.object = form.save(commit=False)
    form.paciente = self.kwargs['pk']
    form.save()
    return HttpResponseRedirect(self.get_success_url())

def form_invalid(self, form):
    print('entrei aqui no INVALID')
    return self.render_to_response(
        self.get_context_data(form=form)
    )

def get_context_data(self, **kwargs):
    context = super(CreateLaudoView, self).get_context_data(**kwargs)
    context['paciente'] = get_object_or_404(Paciente, pk=self.kwargs['pk'])
    context['exames'] = Exame.objects.all()
    context['item_exame'] = ItemExame.objects.all()
    return context

def get_success_url(self):
    return reverse_lazy('paciente:paciente_list')   

I intend to render this screen inserir a descrição da imagem aqui

laudo_form.html

           {% for exame in exames  %}
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><EX></EX>{{ exame }}</h3>    
                    </div>
                    <div class="panel-body">
                        {% for item in item_exame %}
                            {% if item.exame_id == exame.id %}
                                <div class="checkbox">
                                    <label>
                                    <input type="checkbox"> {{ item }}
                                    </label>
                                </div>
                            {% endif %}
                        {% endfor %}
                        <div class="input-group">
                            <input type="text" class="form-control" placeholder="Novo...">
                            <span class="input-group-btn">
                                <button class="btn btn-success" type="button">Salvar</button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        {% endfor %}

1 answer

1


My friend Lucas Magnum (luizalabs.com) helped me.

The code of the model.py remained the same.

Follow the rest of the code Here’s how the code came out:

We had to create a "Form"

forms.py

class LaudoForm(forms.ModelForm):
    """ LaudoForm - """

    class Meta:
        model = Laudo
        exclude = ('data_cadastro', 'data_atualizacao', )


    def create_laudo_exames(self, laudo, item_exames_ids):
        for item_exame_id in item_exames_ids:
            ExameLaudo.objects.create(laudo=laudo, item_exame_id=item_exame_id)

The method we used was this:

class CreateLaudoView(FormView):
    """ Gerador do Laudo """

    template_name = 'laudo/laudo_form.html'
    model = Laudo
    form_class = LaudoForm

    def get_initial(self):
        return {
            "paciente" : self.kwargs['pk']
        }

    def form_valid(self, form):
        self.object = form.save()
        item_exames_ids = self.request.POST.getlist("item_exames")
        form.create_laudo_exames(self.object, item_exames_ids)

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form):
        return self.render_to_response(
            self.get_context_data(form=form)
        )

    def get_context_data(self, **kwargs):
        context = super(CreateLaudoView, self).get_context_data(**kwargs)
        context['paciente'] = get_object_or_404(Paciente, pk=self.kwargs['pk'])
        context['exames'] = Exame.objects.all()
        context['item_exame'] = ItemExame.objects.all()
        return context

    def get_success_url(self):
        return reverse_lazy('paciente:paciente_detail', kwargs={'pk': self.kwargs['pk']})

Finally the template:

  • We made a for on each registered examination context['exames'] of py views.
  • Every test had its items context['item_exame']
  • And in the report you had the patient’s data context['paciente']

        {% for exame in exames  %}
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title"><EX></EX>{{ exame }}</h3>    
                    </div>
                    <div class="panel-body">
                        {% for item in item_exame %}
                            {% if item.exame_id == exame.id %}
                                <div class="checkbox">
                                    <label>
                                    <input type="checkbox" name="item_exames" value="{{ item.id }}"> {{ item }}
                                    </label>
                                </div>
                            {% endif %}
                        {% endfor %}
                        <div class="input-group">
                            <input type="text" class="form-control" placeholder="Novo...">
                            <span class="input-group-btn">
                                <button class="btn btn-success" type="button">Salvar</button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        {% endfor %}
    

Browser other questions tagged

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