本文介绍了Django RedirectView中的Success_url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道吗,我可以将SuccessMessageMixin与RedirectView一起使用吗?因为当我在视图中使用它时:

does somebody know, can I use SuccessMessageMixin with RedirectView? Because when I use it in my views:

class CarRentView(SuccessMessageMixin,RedirectView):
    success_message = "Well done!"
    permanent = False
    query_string = True
    model = Car


    def get_redirect_url(self, *args, **kwargs):
        car = get_object_or_404(Car, pk=kwargs['pk'])
        car.rent=True
        car.save()
        return reverse('cars')

什么也没发生.

我还有另一个问题-有什么办法可以封锁"汽车,这是为下一个用户租用的,并排成一列想要购买同一辆汽车的人吗?

And I've got another question - is there any way to 'block' car, which is rent for next user and make a queue of people who want the same car?

推荐答案

SuccessMessageMixin 用于"FormView"类, RedirectView 不具有表单功能

SuccessMessageMixin for 'FormView' classes, RedirectView does not have forms functionality

第二个问题比较复杂我认为您需要做一些类似的事情(未经测试)

Second question more complexI think you need to do some like (not tested)

models.py

class Car(models.Model):
     ...

class CarQueue(models.Model):
     car = models.ForeignKey(Car)
     user = models.ForeignKey(User)
     updated_at = models.DateTimeField(auto_now=True)
     state = models.PositiveSmallIntegerField(default=1)
     # 1 - user rent, 2 - user wait, 0 - archive
     ...
     class Meta:
            unique_together = [['car', 'user']]
            ordering = ['state', 'updated_at']

views.py

 class CarRentView(UpdateView):
       model = CarQueue
       fields = ['car'] 

       def get_object(self):
          return self.object

       def get_success_url(self):
           # return url according object.state

       def form_valid(self, form):
            # registered users can rent
            form.instance.user = self.request.user
            qset = self.model.objects.filter(car=self.car, state__gt=0)
            if self.object:
                qset = qset.exclude(pk=self.object.pk)
            form.instance.state = 1 if qset.exists() else 2

            return super(..).form_valid(form)

       @method_decorator(login_required)      
       def dispatch(self, request, *args, **kwargs)
            self.car = get_object_or_404(self.model, pk=kwargs['car_pk']) 
            try:
                self.object = self.model.objects.get(car=car, user=request.user)
            except ObjectDoesNotExist:
                self.object = None
            return super(..).dispatch(..)

car_rent_view.html

<form method="post">
     {% csrf_token %} 
     {{ form }}
     <input type="submit">
</form>

urls.py

 url(r'^rent/(?P<car_pk>[^\/]+)/', views.CartRentView.as_view(), name='CartRentView'),

这篇关于Django RedirectView中的Success_url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:27