ModelChoiceField与ModelForm结合使用

时间:2018-04-10 11:56:16

标签: django modelform modelchoicefield

我希望用户能够从下拉列表中选择Solar Collector类型。此时,用户可以从SystemUpdateView()中的下拉列表中选择两种收集器类型,但是这个值显然没有存储到数据库中。 system.collector变量保持为空,下拉列表不记得所选的值。

简化示例有两个模型,太阳能收集器模型和太阳系模型,即:

class Collector(models.Model):
    system          = models.ForeignKey('system.System', related_name='collectors', on_delete=models.CASCADE)
    collector_name  = models.CharField(default='', max_length=200)
    collector_area  = models.FloatField(default=0)

    @classmethod
    def create( cls, 
                system, 
                collector_name,
                collector_area):

        collector = cls(system          = system, 
                        collector_name  = collector_name, 
                        collector_area  = collector_area)
        return collector


class System(models.Model):
    system_name     = models.CharField(default='', max_length=200)

    @classmethod
    def create( cls, system_name):

        system = cls(system_name = system_name)
        system.save()

        # Create the collector objects
        Collector.objects.all().delete()
        collectors = []

        collectors.append( Collector.create(system=system,
                                            collector_name = "Solarus PVT collector 11s",
                                            collector_area = 2.2))
        collectors.append( Collector.create(system=system,
                                            collector_name = "Solarus PVT collector 1.0",
                                            collector_area = 2.31))

        collectors_objects = Collector.objects.bulk_create(collectors)
        collector_objects.save()
        return system

SystemForm的名称为:

class SystemForm(forms.ModelForm):
    collector  = forms.ModelChoiceField(required=False, queryset=Collector.objects.all(), label='Collector')

    class Meta:
        model = System
        fields = [
            'collector',
            'system_name'
        ]

创建和更新视图由:

给出
class SystemUpdateView(LoginRequiredMixin, UpdateView):
    model = System
    template_name = 'system/detail-update.html'
    form_class = SystemForm

    def get_object(self):
        return get_object_or_404(System, pk=self.kwargs['pk_system'])

    def form_valid(self, form):
        system = self.get_object()
        system.system_name                  = form.cleaned_data['system_name']
        system.collector                    = form.cleaned_data['collector']
        system.save()
        return HttpResponseRedirect(reverse('system:detail', args=(system.id,)))    


class SystemCreateView(LoginRequiredMixin, CreateView):
    model = System
    template_name = 'system/create.html'
    form_class = SystemForm

    def form_valid(self, form):
        system = System.create(system_name                     = form.cleaned_data['system_name'])
        system.save()
        return HttpResponseRedirect(reverse('system:detail', args=(system.id,)))   

模板更新详细信息视图模板:

{% extends 'base.html' %}
{% block content %}
<h3>Selected collector: {{system.collector}}</h3>

<h2>Make changes</h2>
<form method='POST'> {% csrf_token %}
    {{ form.as_p }}
    <button type='submit'>Save</button>
</form>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

我不确定您的用途,但如果您使用ModelForm,我认为您没有正确设置model。使用django models

中定义的models.CharField()创建choices=YOUR_CHOICES