如何在表单域中输入模型实例

时间:2015-07-25 19:30:33

标签: django django-models django-forms django-views

我有一个包含2个类的简单模型:

class Company(models.Model):
    company_name = models.CharField(default='', max_length=128, blank=True, null=True)

class Visitor(models.Model):
    visitor_company = models.ForeignKey(Company)
    visitor_name = models.CharField(default='', max_length=128, blank=False, null=False)

我也有一个简单的表格:

class VisitorForm(forms.ModelForm):
    visitor_company = forms.CharField()

    class Meta:
        model = Visitor
        fields = "__all__"

这是view.py代码:

def home(request):
    form = Visitor()

    if request.method == "POST":
            form = Visitor(request.POST)

            if form.is_valid():

                obj, created = Visitor.objects.get_or_create(**form.cleaned_data)

                if created:
                    messages.add_message(request, messages.SUCCESS, 'Visitor added.')
                else:
                    messages.add_message(request, messages.INFO, 'Visitor exists : %s' % obj.visitor_name)

                return redirect('visitors')

    context = { 'form': form }
    return render(request, "visitors/home.html", context)

我已将visitor_company设置为CharField,因为我想使用Typeahead来指定用户ForeignKey,而不是Django的内置下拉列表(如果我没有设置输入类型)。

但是,当我使用此方法时,即使我在company_name字段中输入了有效的visitor_company,我也会获得Cannot assign "XXX": "Visitor.visitor_company" must be a "Company" instance

如何输入公司实例?如果get_or_create记录不存在,是否也可以在ForeignKey Company上使用mouse_event(MOUSEEVENTF_ABSOLUTE, pixels_x, 0, 0, 0);

1 个答案:

答案 0 :(得分:1)

这是未经测试的代码,因此请考虑这是一个起点,没有真正的解决方案:

<强> forms.py

class VisitorForm(forms.ModelForm):
    visitor_company = forms.CharField()

    def clean_visitor_company(self):
        vc = self.cleanded_data['visitor_company']

        try:
            vc_object = Company.objects.get(company_name=vc)
        except Company.DoesNotExist:
            vc_object = Company.objects.create(company_name=vc)

        return vc_object

    class Meta:
        model = Visitor
        fields = "__all__"

<强> views.py

def home(request):
    form = VisitorForm(request.POST or None)

    if form.is_valid():
        form.save()
        return redirect('visitors')

    return render(request, "visitors/home.html", { 'form': form })