Since I've been leaning Python, I have often seen and used :
class FicheDeleteView(LoginRequiredMixin, DeleteView):
model = Fiche
success_url = reverse_lazy('fiche-list')
success_messages = "La Fiche %(ref_id)s a bien été supprimée"
def delete(self, request, *args, **kwargs):
fiche = self.get_object()
messages.success(self.request, self.success_messages %
fiche.__dict__)
return super(FicheDeleteView, self).delete(request, *args, **kwargs)
Even if I see this mechanic's effects, I'm not really sure to understand.
Does it mean : I send to the "reverse-lazy" all the FICHE dict and in my message.success I retrieve the fiche.ref_id with %(ref_id)s ?
CodePudding user response:
The %
operator is an old string formatting placeholder, which lets you include variables in your string. So if you would want to include the variable name
in your string then you could use the %
operator as a placeholder.
name = 'world'
print('Hello, %s' % name)
>>> Hello, world
In your example, the %
operator in success_message
is taking a dictionary as variable and then accessing the value from the key ref_id
in this dictionary.
success_messages = "La Fiche %(ref_id)s a bien été supprimée"
example_dict = {'key_1': 'value_1', 'ref_id': 'value_2'}
print(success_messages % example_dict)
>>> La Fiche value_2 a bien été supprimée
From Python >= 3.6 you can use f-strings which makes it more readable:
example_dict = {'key_1': 'value_1', 'ref_id': 'value_2'}
print(f"La Fiche {example_dict['ref_id']} a bien été supprimée")
>>> La Fiche value_2 a bien été supprimée
You can read more about python string formatting here