I'm improving my English, be patient
My form is a ModelForm and all the necessary data is sent by the user, but I want dynamically set the field ["viagem"] with the last object in the queryset.
How to set a field after sending the data
def cadastro(request):
dono = Dono.objects.get(user=request.user)
if request.method == "POST":
form = VendaForm(dono, request.POST)
# Here I get the necessary data to call my qs
colocador_id = form["colocador"].value()
viagem = Colocador.objects.get(pk=colocador_id).viagem_set.last()
# I want something like this
form["viagem"] = viagem
if form.is_valid():
form.save()
else:
print('error')
print(form.errors)
else:
form = VendaForm(dono)
context = {"form": form, }
return render(request, 'dashboard/cadastro.html', context)
print(form.errors) => <ul class="errorlist"><li>viagem<ul class="errorlist"><li>This field is required</li></ul></li></ul>
Then you should not add this as a Form field. You thus exclude it from the fields
in your ModelForm
and work with:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
@login_required
def cadastro(request):
dono = get_object_or_404(Dono, user=request.user)
if request.method == 'POST':
form = VendaForm(dono, request.POST)
if form.is_valid():
form.instance.viagem = form.cleaned_data['colocador'].viagem_set.last()
form.save()
else:
print('error')
print(form.errors)
else:
form = VendaForm(dono)
context = {'form': form, }
return render(request, 'dashboard/cadastro.html', context)
Note: It is often better to use
get_object_or_404(…)
[Django-doc], then to use.get(…)
[Django-doc] directly. In case the object does not exists, for example because the user altered the URL themselves, theget_object_or_404(…)
will result in returning a HTTP 404 Not Found response, whereas using.get(…)
will result in a HTTP 500 Server Error.
Note: You can limit views to a view to authenticated users with the
@login_required
decorator [Django-doc].