Issue
I have a model for booking table that has a onetoone relation with another model table. And i want to be able to change the value of a field of table before deleting the model booking.
Here is my BookingTable model...
class BookingTable(models.Model):
table = models.OneToOneField(Table, on_delete=models.CASCADE)
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
time = models.TimeField(auto_now_add=True)
def __str__(self) -> str:
return self.user.get_username() + " - " + self.table.name
def get_absolute_url(self):
return reverse("list_tables")
Here is my Table model...
class Table(models.Model):
name = models.CharField(max_length=100, unique=True)
ocupation_status = models.BooleanField(default=False)
size = models.PositiveIntegerField()
image = models.ImageField(upload_to='static/media/images/', default='static/media/images/default.jfif')
description = models.TextField(null=False, blank=False, default="This is a very beatiful table")
def __str__(self) -> str:
return self.name[:50]
def get_absolute_url(self):
return reverse("list_tables")
And here is my view
class CancelBookingView(DeleteView):
model = BookingTable
template_name = 'cancel_booking.html'
success_url = reverse_lazy('list_tables')
def form_valid(self, form):
form.instance.table.ocupation_status = False
return super().form_valid(form)
I tried to use form_valid and accessing the table field using the instance attr but it gave an error saying that form has no attr instance.
class CancelBookingView(DeleteView):
model = BookingTable
template_name = 'cancel_booking.html'
success_url = reverse_lazy('list_tables')
def form_valid(self, form):
form.instance.table.ocupation_status = False
return super().form_valid(form)
Solution
You were quite close, you use the object
, so:
class CancelBookingView(DeleteView):
model = BookingTable
template_name = 'cancel_booking.html'
success_url = reverse_lazy('list_tables')
def form_valid(self, form):
table = self.object.table
table.ocupation_status = False
table.save()
return super().form_valid(form)
Answered By - willeM_ Van Onsem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.