I got a form page to edit my objects from database, but when I access them with the edit button it goes to the url http://localhost:8000/acoes/edit/1 , but I cannot see the object details in the form field. It is just empty as if I was going to create a new object (and it creates if I try)
Any suggestion? Every post and question that I found online states that the code would work being just like this, but it isnt.
on the template acoes_form.html
<form method="post">
<div class="form-group">
{% csrf_token %}
{{form.as_p}}
</div>
<input type="submit" value="Gravar dados" class="btn btn-success" />
</form>
on views.py
@login_required(login_url="/login")
def acoes_edit(request, pk, template_name='acoes/acoes_form.html'):
if request.user.is_superuser:
acoes= get_object_or_404(Acoes, pk=pk)
else:
acoes= get_object_or_404(Acoes, pk=pk, user=request.user)
form = AcoesForm(request.POST or None, instance=acoes)
if form.is_valid():
form.save()
return redirect('acoes_list')
return render(request, template_name, {'form':AcoesForm})
on forms.py
class AcoesForm(ModelForm):
#bunch of fields definitions
#...
#
class Meta:
model = Acoes
fields = ['id_pedido','bl_msg','tb_msg','bl_shell','tb_shell','obs','ativo']
Change your view as follows:
@login_required(login_url="/login")
def acoes_edit(request, pk, template_name='acoes/acoes_form.html'):
if request.user.is_superuser:
acoes= get_object_or_404(Acoes, pk=pk)
else:
acoes= get_object_or_404(Acoes, pk=pk, user=request.user)
form = AcoesForm(request.POST or None, instance=acoes)
if form.is_valid():
form.save()
return redirect('acoes_list')
return render(request, template_name, {'form': form})
You were accidentally referring to the form class rather than the form instance.
On a side note you may want to only save the form if the person POSTed data to the view eg
@login_required(login_url="/login")
def acoes_edit(request, pk, template_name='acoes/acoes_form.html'):
if request.user.is_superuser:
acoes= get_object_or_404(Acoes, pk=pk)
else:
acoes= get_object_or_404(Acoes, pk=pk, user=request.user)
form = AcoesForm(request.POST or None, instance=acoes)
if request.method == 'POST' and form.is_valid():
form.save()
return redirect('acoes_list')
return render(request, template_name, {'form': form})
错误在最后一行,您传递的是表单类,而不是表单对象。
return render(request, template_name, {'form':form})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.