Success_url in django RedirectView

廉价感情. 提交于 2021-01-27 12:00:01

问题


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')

there is nothing happend.

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?


回答1:


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

Second question more complex I 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'),


来源:https://stackoverflow.com/questions/34597554/success-url-in-django-redirectview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!