0

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 ?

Abpostman1
  • 158
  • 1
  • 8
  • Does this answer your question? https://stackoverflow.com/questions/1238306/what-does-do-to-strings-in-python – Iain Shelvington Mar 05 '22 at 06:28
  • Thanks @IainShelvington. I understand and already use this. But I wonder how the link is done between **%(ref_id)s** and **% fiche.__dict__**. Does it automatically picks the **ref_id** key in the objects's dict ? – Abpostman1 Mar 05 '22 at 06:59

1 Answers1

1

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

Helge Schneider
  • 483
  • 5
  • 8