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

时间:2018-01-15 15:45:30

标签: python django forms models

在我的Django应用程序中,我想使用表单所在的“EventDetailView”视图在“Event”模型中减去1个“free_places”字段。每次表单都正常时(当用户订阅事件时),“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

1 个答案:

答案 0 :(得分:0)

您需要指定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()