Django,手动设置 formset/object 日期

Django, set formset/object date manually

我想为汽车修理工制作一个简单的应用程序,但我有一个问题,因为我是新手,所以我无法自己解决。从一开始,我就有一份汽车服务清单,以及使用的零件,按天分组 bootstrap 手风琴(像这样 https://ibb.co/8XWJx1S). In my edit view i grab all of services and parts from one certain day. In edit template i can add formsets dynamically (https://ibb.co/qBKL4Tk)。问题是当我在编辑时添加新服务或部分时,它会以不同的日期保存,然后在列表视图中它不会与我想要的服务分组,因为它的日期不同。有没有办法手动将此日期设置为与其他对象相同?第二种选择,不想要但可以接受的是根据新对象更新 DATE.FIELD 其他对象,我试过但失败了

models.py

class Service(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    car = models.ForeignKey(Car, on_delete=models.CASCADE)
    service_name = models.CharField(max_length=150, verbose_name='Service', default=None)
    service_price = models.DecimalField(max_digits=20, decimal_places=2, default=None)
    date_added = models.DateField(auto_now_add=True)

    def __str__(self):
        return self.service_name

    def save(self, *args, **kwargs):
        """Update parent model date_updated field whenever child object is added/edited"""
        self.car.save(update_fields=['date_updated'])
        super(Service, self).save(*args, **kwargs)


class CarPart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    car = models.ForeignKey(Car, on_delete=models.CASCADE)
    car_part = models.CharField(max_length=30, blank=True, null=True, verbose_name='Part')
    part_price = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True)
    pdate_added = models.DateField(auto_now_add=True)

    def __str__(self):
        return f"Part: {self.car_part}  Price: {self.part_price}"

views.py

@method_decorator(login_required, name='dispatch')
class ServiceAddView(CreateView):
    model = Service
    template_name = 'san_diego/service_add.html'

    def get(self, request, *args, **kwargs):
        self.object = None
        car = Car.objects.get(uuid=self.kwargs.get('uuid'))
        service_formset = ServiceFormSet(queryset=Service.objects.none(), prefix='service_formset')
        formset = CarPartFormSet(queryset=CarPart.objects.none(), prefix='carpart_formset')
        return self.render_to_response(
            self.get_context_data(form=service_formset, formset=formset, car=car))

    def post(self, request, *args, **kwargs):
        self.object = None
        car = Car.objects.get(uuid=self.kwargs.get('uuid'))
        service_formset = ServiceFormSet(self.request.POST, prefix='service_formset')
        formset = CarPartFormSet(self.request.POST, prefix='carpart_formset')
        if service_formset.is_valid() and formset.is_valid():
            return self.form_valid(service_formset, formset)
        else:
            return self.form_invalid(service_formset, formset, car)

    def form_valid(self, service_formset, formset):
        form = service_formset.save(commit=False)
        formset = formset.save(commit=False)
        for f in form:
            f.car = Car.objects.get(uuid=self.kwargs.get('uuid'))
            f.user = self.request.user
            f.save()
        for f in formset:
            f.car = Car.objects.get(uuid=self.kwargs.get('uuid'))
            f.user = self.request.user
            f.save()
        return redirect(self.get_success_url())

    def form_invalid(self, service_formset, formset, car):
        return self.render_to_response(self.get_context_data(form=service_formset, formset=formset, car=car))

    def get_success_url(self):
        """If statement is adding funcionality to SAVE AND ADD ANOTHER button."""
        car = get_object_or_404(Car, uuid=self.kwargs.get('uuid'), user=self.request.user)
        if "another" in self.request.POST:
            return reverse_lazy('service_add', kwargs={'uuid': car.uuid})
        return reverse_lazy('service_history', kwargs={'uuid': car.uuid})

import datetime

@method_decorator(login_required, name='dispatch')
class ServiceEditView(UpdateView):
    model = Service
    template_name = 'san_diego/service_add.html'

    def get_object(self):
        """Pass UUID"""
        return Car.objects.get(uuid=self.kwargs.get("uuid"))

    def get(self, request, *args, **kwargs):
        self.object =self.get_object()
        service_formset = ServiceFormSet(queryset=Service.objects.filter(
            car=self.get_object(), user=self.request.user, date_added=self.kwargs.get('date')), prefix='service_formset')
        formset = CarPartFormSet(queryset=CarPart.objects.filter(
            car=self.get_object(), user=self.request.user, pdate_added=self.kwargs.get('date')), prefix='carpart_formset')
        return self.render_to_response(
            self.get_context_data(form=service_formset, formset=formset))

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        service_formset = ServiceFormSet(self.request.POST, prefix='service_formset')
        formset = CarPartFormSet(self.request.POST, prefix='carpart_formset')
        if service_formset.is_valid() and formset.is_valid():
            return self.form_valid(service_formset, formset)
        else:
            return self.form_invalid(service_formset, formset)

    def form_valid(self, service_formset, formset):
        form = service_formset.save(commit=False)
        formset = formset.save(commit=False)
        for f in form:
            f.car = self.get_object()
            f.user = self.request.user
            f.save()
        for f in formset:
            f.car = self.get_object()
            f.user = self.request.user
            f.save()
        return redirect(self.get_success_url())

    def form_invalid(self, service_formset, formset):
        return self.render_to_response(self.get_context_data(form=service_formset, formset=formset))
    
    def get_success_url(self):
        car = get_object_or_404(Car, uuid=self.kwargs.get('uuid'), user=self.request.user)
        return reverse_lazy('service_history', kwargs={'uuid': car.uuid})

如果将来有人对此有疑问,请弄清楚。我的第一种方法是正确的,即将这些行添加到 UpdateView BEFORE CALLING f.save()

f.date_added = self.kwargs.get('date')

因此在模型中无法正常工作 date_added = models.DateField(auto_now_add=True) 我研究了一下,似乎 auto_now_add 是不可编辑的。 所以我把它改成了date_added = models.DateField(default=datetime.date.today)