通过视图修改模型字段不起作用

Modify models field via view doesn't work

在我的 Django 应用程序中,我想使用表单所在的 "EventDetailView" 视图在 "Event" 模型中减去 1 个 "free_places" 字段。每次表单OK时(当用户订阅事件时),"free_places"字段应该减1。

我不知道为什么我的代码不起作用。

我的看法:

class EventDetailView(DetailView, ModelFormMixin):
    model = models.Event
    form_class = forms.RegisterForm
    context_object_name = 'event'

    def get_success_url(self):
        return reverse('events:list')

    def get_initial(self):
        return {'event': self.kwargs['pk']}

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            self.object = self.get_object()
            self.object.free_places - 1
            self.object.save()
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

型号:

class Event(models.Model):
    title = models.CharField(max_length=500)
    date = models.DateField()
    text = models.TextField()
    image = FilerImageField(null=True, blank=True)
    flag = models.ForeignKey(Flag)
    free_places = models.IntegerField()

    class Meta:
        ordering = ['-date']

    def __str__(self):
        return self.title

    @property
    def slug(self):
        return slugify(self.title)

    def get_absolute_url(self):
        return reverse('events:detail', args=[self.slug, self.id])

    def get_model_id(self):
        return self.id


class Register(models.Model):
    event = models.ForeignKey(Event)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    company = models.CharField(max_length=30, blank=True)
    street = models.CharField(max_length=50, blank=True)
    post_code = models.CharField(max_length=30, blank=True)
    city = models.CharField(max_length=30, blank=True)
    email = models.EmailField()
    phone_number = models.IntegerField()

    def __str__(self):
        return self.first_name

    def get_event_name(self):
        return self.event

您需要分配self.object.free_places - 1的结果。目前你没有对它做任何事情。

将行更改为:

self.object.free_places -= 1

self.object.free_places = self.object.free_places - 1

如果多个用户同时提交表单,代码容易受到竞争条件的影响。您可以使用 F() objects.

来解决这个问题
from django.db.models import F
self.object.free_places = F('free_places') - 1
self.object.save()