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:
JavaScript
x
13
13
1
@login_required(redirect_field_name='login')
2
def obra_open_view(request, obra_id):
3
obra = get_object_or_404(Obra, pk=obra_id)
4
5
if obra:
6
request.session['obra_aberta_id'] = obra.id
7
request.session['obra_aberta_name'] = obra.nome
8
return redirect('obra_detail_url')
9
else:
10
request.session['obra_aberta_id'] = 0
11
request.session['obra_aberta_name'] = ""
12
return redirect('obra_lista_url')
13
When I have some value on ‘obra_aberta_id’ I need to put this value on a HiddenInput:
JavaScript
1
21
21
1
class FormCarga(ModelForm):
2
class Meta:
3
model = Carga
4
fields = ('__all__')
5
6
widgets = {
7
'tag': forms.TextInput(attrs={'class': 'form-control'}),
8
'nome': forms.TextInput(attrs={'class': 'form-control'}),
9
'descricao': forms.Textarea(attrs={'class': 'form-control'}),
10
'potencia': forms.TextInput(attrs={'class': 'form-control'}),
11
'unidade_medida_potencia': forms.Select(attrs={'class': 'form-control'}),
12
'area': forms.Select(attrs={'class': 'form-control'}),
13
'tensao': forms.Select(attrs={'class': 'form-control'}),
14
'fonte': forms.Select(attrs={'class': 'form-control'}),
15
'atividade': forms.Select(attrs={'class': 'form-control'}),
16
'fator_potencia': forms.Select(attrs={'class': 'form-control'}),
17
'condutores_carregados': forms.Select(attrs={'class': 'form-control'}),
18
'obra': forms.HiddenInput(attrs={'class': 'form-control','initial' : request.session['obra_aberta_id']}),
19
20
}
21
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:
JavaScript
1
63
63
1
class Carga(models.Model):
2
tag = models.CharField(max_length=10)
3
nome = models.CharField(max_length=100)
4
descricao = models.TextField(blank=True,
5
verbose_name='Descrição')
6
potencia = models.CharField(blank=True,
7
max_length=10,
8
verbose_name='Potência')
9
unidade_medida_potencia = models.ForeignKey(UnidadeMedidaPotencia,
10
on_delete=models.DO_NOTHING,
11
null=True,
12
blank=True,
13
verbose_name='Unidade de Medida')
14
area = models.ForeignKey(Area,
15
on_delete=models.DO_NOTHING,
16
null=True,
17
verbose_name='Área')
18
tensao = models.ForeignKey(Tensao,
19
on_delete=models.DO_NOTHING,
20
null=True,
21
verbose_name='Tensão')
22
fonte = models.ForeignKey(Fonte,
23
on_delete=models.DO_NOTHING,
24
null=True)
25
atividade = models.ForeignKey(Atividade,
26
on_delete=models.DO_NOTHING,
27
null=True)
28
29
fator_potencia = models.ForeignKey(FatorPotencia,
30
on_delete=models.DO_NOTHING,
31
null=True,
32
verbose_name='Fator de Potência')
33
condutores_carregados = models.ForeignKey(CondutoresCarregados,
34
on_delete=models.DO_NOTHING,
35
null=True)
36
obra = models.ForeignKey(Obra,
37
on_delete=models.DO_NOTHING,
38
null=False)
39
40
class Obra(models.Model):
41
nome = models.CharField(max_length=255)
42
descricao = models.TextField(blank=True,
43
verbose_name='Descrição') # opcional
44
cnpj = models.CharField(max_length=15,
45
blank=True)
46
revisao = models.CharField(max_length=10,
47
blank=True,
48
verbose_name='Revisão') # opcional
49
descricao_revisao = models.TextField(blank=True,
50
verbose_name='Descrição da Revisão')
51
bloqueado = models.BooleanField(default=False)
52
# Se o externo for apagado, não apaga a obra
53
cliente = models.ForeignKey(PessoaJuridica,
54
on_delete=models.DO_NOTHING,
55
null=True)
56
participantes = models.ManyToManyField(PessoaFisica,
57
through='FuncaoPessoaObra')
58
contato = models.ManyToManyField(Contato)
59
60
# (equivalente ao tostring) aparecer o nome no site admin
61
def __str__(self):
62
return self.nome
63
Edit:
Here is my template:
JavaScript
1
27
27
1
{% extends 'base.html' %}
2
3
{% block titulo %}
4
{{ nome_pagina }}
5
{% endblock %}
6
7
{% block conteudo %}
8
9
{% include 'parciais/_messages.html' %}
10
11
<h1 class="mt-3 mb-3">
12
{{ nome_pagina }}
13
</h1>
14
15
<form method="post">
16
{% csrf_token %}
17
{{ form.as_p }}
18
{% if editavel %}
19
<button type="submit" class="btn btn-primary float-right">Salvar</button>
20
{% else %}
21
<a class="btn btn-primary float-right" href="{% url url_lista %}">Lista</a>
22
{% endif %}
23
</form>
24
</br>
25
26
{% endblock %}
27
And here is the view where I will use it:
JavaScript
1
25
25
1
@login_required(redirect_field_name='login')
2
def carga_new_view(request):
3
if request.method == 'POST':
4
5
form = FormCarga(request.POST)
6
7
if form.is_valid():
8
form.save()
9
messages.success(request, 'Carga cadastrada com sucesso!')
10
11
# Redirect para a lista de cargas
12
return redirect('carga_list_url')
13
else:
14
form = FormCarga()
15
nome_pagina = 'Nova Carga'
16
17
page_dictionary = {
18
'form': form,
19
'nome_pagina': nome_pagina,
20
'editavel': True,
21
'url_lista': 'carga_list_url',
22
}
23
24
return render(request, 'item.html', page_dictionary)
25
Advertisement
Answer
Please remove from obra
widget initial dict.
JavaScript
1
9
1
class FormCarga(ModelForm):
2
3
class Meta:
4
model = Carga
5
widgets = {
6
'obra': forms.HiddenInput(),
7
# other staff
8
}
9
After that you can do:
JavaScript
1
25
25
1
def carga_new_view(request):
2
initial={'obra': request.session.get('obra_aberta_id')}
3
if request.method == 'POST':
4
5
form = FormCarga(request.POST, initial=initial)
6
7
if form.is_valid():
8
form.save()
9
messages.success(request, 'Carga cadastrada com sucesso!')
10
11
# Redirect para a lista de cargas
12
return redirect('carga_list_url')
13
else:
14
form = FormCarga(initial=initial)
15
nome_pagina = 'Nova Carga'
16
17
page_dictionary = {
18
'form': form,
19
'nome_pagina': nome_pagina,
20
'editavel': True,
21
'url_lista': 'carga_list_url',
22
}
23
24
return render(request, 'item.html', page_dictionary)
25
But PLEASE read about Django-GCBV FormView. In your case:
JavaScript
1
11
11
1
class CargaNewView(FormView):
2
template = 'item.html'
3
success_url = 'carga_list_url'
4
form_class = FormCarga
5
6
def get_initial(self, *args, **kwargs):
7
return super().get_initial(*args, **kwargs) | {'obra': request.session['obra_aberta_id']}
8
9
def get_context_data(self, *args, **kwargs):
10
return super().get_context_data(*args, **kwargs) | {'nome_pagina': 'Nova Carga', 'editavel': True, 'url_lista': self.success_url}
11
I pass, your have a ModelForm. In this case you can use Django-GCBV EditView.