Render items with Django Forms. Three Models Involved, Single Forms

0

Hello, I'm having trouble rendering my model items.

The system works as follows:

  • User registers an exam Exame .
  • Within each exam you have the exam types ItemExame
  • User generates a report Laudo that pulls the patient and the doctor that generated the award.
  • The ExameLaudo table will love ItemExame with Laudo

Ex: (table) ExamLeague

1

Ineedtorenderonthescreentheexamsandthetypesofexamfortheusertochoosetheexamsdone.

Andthensave(post)thesame.

models.py

classExame(models.Model):descricao=models.CharField('Descrição',max_length=200)data_cadastro=models.DateTimeField(auto_now_add=True)ativo=models.BooleanField(default=True)classItemExame(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)classLaudo(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)classExameLaudo(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 want you to render this screen

laudo_form.html

{%forexameinexames%}<divclass="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 %}
    
asked by anonymous 25.02.2017 / 18:08

1 answer

0

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

The code of model.py has remained the same.

Follow the rest of the code Here is the code:

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 in every exam% co.de% of views.py
  • Each exam, had its items context['exames']
  • And in the report had the data of the patient context['item_exame']

        {% 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 %}
    
15.03.2017 / 23:53