I am programming a cities backend in which I need to add a function to disable the cities that are marked, similar to the functionality of Django's admin.
City Model
class City(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey(Country)
region = models.ForeignKey(Region)
cod_dane = models.CharField(max_length=8)
desactivado = models.BooleanField(default=False)
aereo = models.BooleanField(default=False)
def __str__(self):
return self.name
Form
class CityForm(forms.ModelForm):
class Meta:
model = City
fields = ['id']
View
class CityView(ListView):
model = City
form_class = CityForm
template_name = "backend/ciudad/ciudades.html"
def post(self, request, *args, **kwargs):
for r in request.POST.get('id'):
ciudad = City.objects.get(id=r)
ciudad.desactivado = True
ciudad.save()
return redirect('ciudades')
The important thing to understand to achieve what you want is your form. When you create the form the way you have it, you're telling Django, "Hey, this form (CityForm) will only work for a model of type City" and the problem is that you want to affect many models of type City to apply them later the deactivated.
So there are many ways to make a single form accept many City so you can manipulate them in a
for
, one can be formsets, but this way is much faster and less complex:This way you have a form that expects to receive from the client under the parameter of
cities
a list ofid
the City model.And from your view it is much easier to do an update than a
for
, like this:If any part of the code doesn't work for you, let me know and I'll help you with the problem, I haven't tested the code I sent you so I can't tell you if it works correctly. I hope I've helped