简体   繁体   English

在 Django 表单中设置初始值

[英]Setting an initial value in a Django Form

I have to setup an initial value in a form and somehow is not working, it is extremely strange as I have exactly the same code in another view, but in this case my approach is not working:我必须在表单中设置一个初始值,但不知何故不起作用,这非常奇怪,因为我在另一个视图中有完全相同的代码,但在这种情况下,我的方法不起作用:

views.py视图.py


@login_required
def add_lead(request):
    if request.method == 'POST':
        lead_form = LeadsForm(request.POST)
        if lead_form.is_valid():
            lead_form.save()
            messages.success(request, 'You have successfully added a new lead')


            return HttpResponseRedirect(reverse('add_lead'))
        else:
            messages.error(request, 'Error updating your Form')

    else:

        user = {"agent":request.user}
        lead_form = LeadsForm(request.POST or None, initial = user)


    return render(request,
                  'account/add_lead.html',
                  {'lead_form': lead_form}
                   )

forms.py表格.py

class LeadsForm(forms.ModelForm):
    class Meta:
        model = Leads
        fields = ('project_id','company','agent','point_of_contact','services','expected_licenses',
                  'expected_revenue','country', 'status', 'estimated_closing_date'
                  )
        widgets = {'estimated_closing_date': DateInput(),
                   }

Essentially, the agent is the logged user, so I'm passing request.user as a variable, but I have not succeeded, which is very strange because I have that same logic in another form本质上,代理是登录用户,所以我将 request.user 作为变量传递,但我没有成功,这很奇怪,因为我在另一种形式中有相同的逻辑

Any help will be appreciated任何帮助将不胜感激

If you want to make a form with a foreign key you can use ModelChoiceField .如果要使用外键制作表单,可以使用ModelChoiceField In your case you can use:在您的情况下,您可以使用:

class LeadsForm(forms.ModelForm):
    agent = forms.ModelChoiceField(queryset=User.objects.all())

    class Meta:
        model = Leads
        fields = ('project_id','company','agent','point_of_contact','services','expected_licenses',
                  'expected_revenue','country', 'status', 'estimated_closing_date'
                  )
        widgets = {'estimated_closing_date': DateInput(),
                   }

Then you can assign data with user_id in your form initial.然后,您可以在表单初始值中使用 user_id 分配数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM