I set an UpdateView class to update data of user's markers. I have a Marker model with a field category. I want to have one and only "Where I live" category marker in all the user's markers. Is there a way to create a function in the UpdateView class to invalidate the form if there are more than one "Where I live" markers.
class UpdateMarkerView(UpdateView):
model = Marker
fields = ["name", "description", "category"]
template_name = "map/detail.html"
success_url = "/"
class Marker(models.Model):
WIL = "WIL"
WIWG = "WIWG"
WIW = "WIW"
IDK = "IDK"
CATEGORY_MARKER = [(WIL,"Where I live"), (WIWG, "Where I want to go"),(WIW,"Where I went"),(IDK,"I don't know")]
user = models.ForeignKey(User,blank=True, null=True,on_delete = models.SET_NULL)
name = models.fields.CharField(max_length=100)
description = models.fields.CharField(max_length=100)
lat = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3)
lon = models.fields.DecimalField(default=False, max_digits=5, decimal_places=3)
category = models.CharField(max_length=50, choices = CATEGORY_MARKER, default = IDK)
I've already done it with a basic function but I can't find a way to do it with a generic view if it's possible.
CodePudding user response:
You can use the form_valid
method for the general answer.
But if you want to return an invalid form when there was more than 1 "Where I Live" category, you can write it like this:
class UpdateMarkerView(UpdateView):
model = Marker
fields = ["name", "description", "category"]
template_name = "map/detail.html"
success_url = "/"
def form_valid(self, form):
data = form.cleaned_data
if data.get("category") == "WIL":
if Marker.objects.filter(category="WIL").count() >= 1:
form.add_error('category', 'This category already exists.')
return self.form_invalid(form)
else:
return super().form_valid(form)
First we check that the category selected by the user is "WIL", then if there is more than 1 category(WIL), we add an error to the form and return the invalid form.
You can also change count
to the exists
in the query, because it means that one already exists and this is the second.