Django – Retrieve a session value to a form

Question:

I have a Django aplication and need to get a value from the session and put it in a HiddenInput.

I have this code in my view:

@login_required(redirect_field_name='login')
def obra_open_view(request, obra_id):
    obra = get_object_or_404(Obra, pk=obra_id)

    if obra:
        request.session['obra_aberta_id'] = obra.id
        request.session['obra_aberta_name'] = obra.nome
        return redirect('obra_detail_url')
    else:
        request.session['obra_aberta_id'] = 0
        request.session['obra_aberta_name'] = ""
        return redirect('obra_lista_url')

When I have some value on ‘obra_aberta_id’ I need to put this value on a HiddenInput:

class FormCarga(ModelForm):
    class Meta:
        model = Carga
        fields = ('__all__')
        
        widgets = {
            'tag': forms.TextInput(attrs={'class': 'form-control'}),
            'nome': forms.TextInput(attrs={'class': 'form-control'}),
            'descricao': forms.Textarea(attrs={'class': 'form-control'}),
            'potencia': forms.TextInput(attrs={'class': 'form-control'}),
            'unidade_medida_potencia': forms.Select(attrs={'class': 'form-control'}),
            'area': forms.Select(attrs={'class': 'form-control'}),
            'tensao': forms.Select(attrs={'class': 'form-control'}),
            'fonte': forms.Select(attrs={'class': 'form-control'}),
            'atividade': forms.Select(attrs={'class': 'form-control'}),
            'fator_potencia': forms.Select(attrs={'class': 'form-control'}),
            'condutores_carregados': forms.Select(attrs={'class': 'form-control'}),
            'obra': forms.HiddenInput(attrs={'class': 'form-control','initial' : request.session['obra_aberta_id']}),

        }

But I’m getting an error on ‘request’: name ‘request’ is not defined

How can I get a value from the session e set os this HiddenInput?

I don’t know if the models will help, but there it is anyway:

class Carga(models.Model):
    tag = models.CharField(max_length=10)
    nome = models.CharField(max_length=100)
    descricao = models.TextField(blank=True,
                                verbose_name='Descrição')
    potencia = models.CharField(blank=True,
                                max_length=10,
                                verbose_name='Potência')
    unidade_medida_potencia = models.ForeignKey(UnidadeMedidaPotencia,
                                                on_delete=models.DO_NOTHING,
                                                null=True,
                                                blank=True,
                                                verbose_name='Unidade de Medida')
    area = models.ForeignKey(Area,
                            on_delete=models.DO_NOTHING,
                            null=True,
                            verbose_name='Área')    
    tensao = models.ForeignKey(Tensao,
                                on_delete=models.DO_NOTHING,
                                null=True,
                                verbose_name='Tensão')
    fonte = models.ForeignKey(Fonte,
                            on_delete=models.DO_NOTHING,
                            null=True)
    atividade = models.ForeignKey(Atividade,
                                on_delete=models.DO_NOTHING,
                                null=True)

    fator_potencia = models.ForeignKey(FatorPotencia,
                                        on_delete=models.DO_NOTHING,
                                        null=True,
                                verbose_name='Fator de Potência')
    condutores_carregados = models.ForeignKey(CondutoresCarregados,
                                            on_delete=models.DO_NOTHING,
                                            null=True)
    obra = models.ForeignKey(Obra,
                            on_delete=models.DO_NOTHING,
                            null=False)

class Obra(models.Model):
    nome = models.CharField(max_length=255)
    descricao = models.TextField(blank=True,
                                verbose_name='Descrição')  # opcional
    cnpj = models.CharField(max_length=15,
                            blank=True)
    revisao = models.CharField(max_length=10,
                                blank=True,
                                verbose_name='Revisão')  # opcional
    descricao_revisao = models.TextField(blank=True,
                                        verbose_name='Descrição da Revisão')
    bloqueado = models.BooleanField(default=False)
    # Se o externo for apagado, não apaga a obra
    cliente = models.ForeignKey(PessoaJuridica,
                                on_delete=models.DO_NOTHING,
                                null=True)
    participantes = models.ManyToManyField(PessoaFisica,
                                        through='FuncaoPessoaObra')
    contato = models.ManyToManyField(Contato)

    # (equivalente ao tostring) aparecer o nome no site admin
    def __str__(self):
        return self.nome

Edit:

Here is my template:

{% extends 'base.html' %}

{% block titulo %}
  {{ nome_pagina }}
{% endblock %}

{% block conteudo %} 

  {% include 'parciais/_messages.html' %}

  <h1 class="mt-3 mb-3">
    {{ nome_pagina }}
  </h1>
  
    <form method="post">
      {% csrf_token %}
      {{ form.as_p }}
      {% if editavel %}
        <button type="submit" class="btn btn-primary float-right">Salvar</button>
      {% else %}
        <a class="btn btn-primary float-right" href="{% url url_lista %}">Lista</a>
      {% endif %}
    </form>
    </br>

{% endblock %}

And here is the view where I will use it:

@login_required(redirect_field_name='login')
def carga_new_view(request):
    if request.method == 'POST':

        form = FormCarga(request.POST)

        if form.is_valid():
            form.save()
            messages.success(request, 'Carga cadastrada com sucesso!')

            # Redirect para a lista de cargas
            return redirect('carga_list_url')
    else:
        form = FormCarga()
        nome_pagina = 'Nova Carga'

    page_dictionary = {
        'form': form,
        'nome_pagina': nome_pagina,
        'editavel': True,
        'url_lista': 'carga_list_url',
    }

    return render(request, 'item.html', page_dictionary)
Asked By: rohrigme

||

Answers:

Please remove from obra widget initial dict.

class FormCarga(ModelForm):

    class Meta:
        model = Carga
        widgets = {
            'obra': forms.HiddenInput(),
            # other staff
        }

After that you can do:

def carga_new_view(request):
    initial={'obra': request.session.get('obra_aberta_id')}
    if request.method == 'POST':

        form = FormCarga(request.POST, initial=initial)

        if form.is_valid():
            form.save()
            messages.success(request, 'Carga cadastrada com sucesso!')

            # Redirect para a lista de cargas
            return redirect('carga_list_url')
    else:
        form = FormCarga(initial=initial)
        nome_pagina = 'Nova Carga'

    page_dictionary = {
        'form': form,
        'nome_pagina': nome_pagina,
        'editavel': True,
        'url_lista': 'carga_list_url',
    }

    return render(request, 'item.html', page_dictionary)

But PLEASE read about Django-GCBV FormView. In your case:

class CargaNewView(FormView):
    template = 'item.html'
    success_url = 'carga_list_url'
    form_class = FormCarga

    def get_initial(self, *args, **kwargs):
        return super().get_initial(*args, **kwargs) | {'obra': request.session['obra_aberta_id']}

    def get_context_data(self, *args, **kwargs):
        return super().get_context_data(*args, **kwargs) | {'nome_pagina': 'Nova Carga', 'editavel': True, 'url_lista': self.success_url}

I pass, your have a ModelForm. In this case you can use Django-GCBV EditView.

Answered By: Maxim Danilov

This is my first question here on StackOverflow. How can I tag my question as solved?

Answered By: rohrigme
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.