问题
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