0👍
✅
In order to get the behavior you want, you have to use the values from anuncioForm
:
<form method="post" action="" enctype="multipart/form-data">{% csrf_token %}
<div class="panel panel-default">
<div class = "panel-heading">
Informações de Contato
</div>
<div class = "panel-body">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input type="text" class="form-control"
id="id_{{ anuncioForm.nome_contato.name }}"
name="{{ anuncioForm.nome_contato.name }}"
value= "{{ anuncioForm.nome_contato.value or (request.user.first_name + ; ' + request.user.last_name) }}"
placeholder="Nome">
</div>
<p class="help-text">{{anuncioForm.nome_contato.help_text }} </p>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input type="text" class="form-control"
id="id_{{ anuncioForm.email_contato.name }}"
name="{{ anuncioForm.email_contato.name }}"
value="{{ anuncioForm.email_contato.value or request.user.email }} "
placeholder="E-mail">
</div>
<p class="help-text">{{ anuncioForm.email_contato.help_text }}</p>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-glyphicon glyphicon-phone"></i></span>
<input type="text" class="form-control"
id="id_{{ anuncioForm.telefone_contato.name }}"
name="{{ anuncioForm.telefone_contato.name }}"
value="{{ anuncioForm.telefone_contato.value }}"
placeholder="Telefone ou Celular">
</div>
<p class="help-text">{{ anuncioForm.telefone_contato.help_text }} </p>
</div>
</div>
👤2ps
1👍
In your view, if the form is not valid a new blank form is being sent to the template. You need to send the form that the user filled in so that the errors can be displayed properly.
You also need to adjust your template to show the errors – right now it is not doing that.
To fix the view:
def anunciar_imovel(request):
ImageFormSet = modelformset_factory(ImagensAnuncio,
form=ImagensForm, extra=3)
anuncioForm = AnuncioForm(request.POST or None, request.FILES or None)
formset = ImageFormSet(request.POST or None, request.FILES or None,
queryset=ImagensAnuncio.objects.none())
if anuncioForm.is_valid() and formset.is_valid():
novo_anuncio = anuncioForm.save(commit=False)
novo_anuncio.user = request.user
novo_anuncio.save()
for form in formset.cleaned_data:
imagem = form['imagem']
photo = ImagensAnuncio(anuncio=novo_anuncio, imagem=imagem)
photo.save()
return render(request, 'account/index.html')
return render(request, 'imoveis/anunciar.html',
{'anuncioForm':anuncioForm,'formset':formset })
To fix the template, you need to check if there are any error on the formset and the individual form itself. I leave this exercise up to you, as it is detailed in the documentation.
- Django model name in save() method
- Error in charging a one-off payment in pinax-stripe module of django python
Source:stackexchange.com