来自相关模型的Django M2M CreateView和UpdateView

时间:2017-04-02 18:58:38

标签: django python-2.7 django-forms many-to-many

我有这些模型:

class Company(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False, verbose_name=ugettext_lazy(u'Name'))
    building = models.ForeignKey(Building, null=False, blank=False, verbose_name=ugettext_lazy(u'Building'))
    parking_spaces_count = models.PositiveIntegerField(verbose_name=ugettext_lazy(u'Parking spaces count'))

    def __unicode__(self):
        return unicode(self.name)


class Car(models.Model):
    registration_number = models.CharField(max_length=10, blank=False, null=False, verbose_name=ugettext_lazy(u'Registration number'))

    def __unicode__(self):
        return unicode(self.registration_number)


class Employee(models.Model):
    first_name = models.CharField(max_length=50, null=False, blank=False, verbose_name=(ugettext_lazy(u'First name')))
    last_name = models.CharField(max_length=50, null=False, blank=False, verbose_name=(ugettext_lazy(u'Last name')))
    id_number = models.CharField(max_length=20, null=False, blank=False, verbose_name=(ugettext_lazy(u'Identification card number')))
    company = models.ForeignKey(Company, null=False, blank=False, verbose_name=ugettext_lazy(u'Company'), related_name='employees')
    cars = models.ManyToManyField(Car, verbose_name=ugettext_lazy(u'Cars'), related_name='owners')

    def __unicode__(self):
        return unicode(' '.join([self.first_name, self.last_name]))

我希望能够实施:

1 - CarCreateView - 我将通过提供其registration_number和所有者(来自Employee模型的相关字段)字段在我的数据库中创建Car对象。当我尝试将“所有者”放在这样的字段中时(使用Django的CreateView):

fields = ('registration_number', 'owners')

我收到错误“为Car指定的未知字段(所有者)”。

我设法使用FormView模拟它:

class CarCreateView(FormView):
    model = Car
    template_name = 'companies/cars/add.html'
    form_class = CarCreateForm
    success_url = reverse_lazy('companies:cars:list')

    def form_valid(self, form):
        employees = form.cleaned_data['owners']
        registration_number = form.cleaned_data['registration_number']
        car = Car(registration_number=registration_number)
        car.save()
        car.owners = employees
        return super(CarCreateView, self).form_valid(form)

我的问题是 - 这是干还是可能更好?

2 - CarEditView - 我可以通过提供其registration_number和所有者来编辑汽车的现有对象。到目前为止,我已经尝试过使用FormView,但我没有做任何事情,所以请你指导我该怎么做?我最好只使用UpdateView,但我想这与M2M关系并不那么简单。

丹尼尔

0 个答案:

没有答案