有人知道,我可以将SuccessMessageMixin与RedirectView一起使用吗?因为当我在视图中使用它时:
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')
什么也没发生
我还有另一个问题-有什么办法可以“封锁”汽车,这是下一个用户的租金,并且使想要购买同一辆汽车的人排成一列?
最佳答案
SuccessMessageMixin
用于“ FormView”类,RedirectView
没有表单功能
第二个问题比较复杂
我认为您需要做一些类似的事情(未经测试)
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 - Django RedirectView中的Success_url,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34597554/