Django Form - 设置数据

问题描述 投票:0回答:1

我正在提高我的英语,请耐心等待

我的表单是 ModelForm,所有必要的数据均由用户发送,但我想使用查询集中的最后一个对象动态设置字段 [“viagem”]。

发送数据后如何设置字段

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>

django forms django-forms
1个回答
2
投票

那么您不应该将其添加为表单字段。因此,您将其从 fields

 中的 
ModelForm
 中排除并使用:

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)


注意:使用 get_object_or_404(…)

 [Django-doc] 通常会更好,
然后直接使用 .get(…)
 [Django-doc]
。如果该对象不存在, 例如,因为用户自己更改了 URL,
get_object_or_404(…)
 将导致返回 
HTTP 404 Not Found 响应,而使用 .get(…)
 将导致 
HTTP 500 服务器错误


注意:您可以使用以下命令将视图限制为经过身份验证的用户 @login_required

装饰器[Django-doc].

© www.soinside.com 2019 - 2024. All rights reserved.