We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Erreurs 500 pour "Ajouter en Une"
Sur certains contenus, "Ajouter en Une" renvoie une erreur 500

Sujet : https://zestedesavoir.com/forums/sujet/11676/ajouter-en-une/#p195045
*Envoyé depuis Zeste de Savoir*

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `zds/featured/views.py`
Content:
```
1 from datetime import datetime
2 
3 from django.contrib import messages
4 from django.contrib.auth.decorators import login_required, permission_required
5 from django.urls import reverse
6 from django.db import transaction
7 from django.shortcuts import redirect
8 from django.utils.decorators import method_decorator
9 from django.utils.translation import ugettext as _
10 from django.views.generic import CreateView, RedirectView, UpdateView, FormView, DeleteView
11 from django.views.generic.list import MultipleObjectMixin
12 
13 from django.conf import settings
14 from zds.featured.forms import FeaturedResourceForm, FeaturedMessageForm
15 from zds.featured.models import FeaturedResource, FeaturedMessage
16 from zds.forum.models import Topic
17 from zds.tutorialv2.models.database import PublishedContent
18 from zds.utils.paginator import ZdSPagingListView
19 
20 
21 class FeaturedResourceList(ZdSPagingListView):
22     """
23     Displays the list of featured resources.
24     """
25 
26     context_object_name = 'featured_resource_list'
27     paginate_by = settings.ZDS_APP['featured_resource']['featured_per_page']
28     queryset = FeaturedResource.objects.all().order_by('-pubdate')
29     template_name = 'featured/index.html'
30 
31     @method_decorator(login_required)
32     @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))
33     def dispatch(self, request, *args, **kwargs):
34         return super(FeaturedResourceList, self).dispatch(request, *args, **kwargs)
35 
36 
37 class FeaturedResourceCreate(CreateView):
38     """
39     Creates a new featured resource.
40     """
41 
42     form_class = FeaturedResourceForm
43     template_name = 'featured/resource/create.html'
44     context_object_name = 'featured_resource'
45     initial_error_message = _('Le contenu est introuvable')
46     displayed_content_type = {'TUTORIAL': _('Un tutoriel'),
47                               'ARTICLE': _('Un article'),
48                               'OPINION': _('Un billet'),
49                               'TOPIC': _('Un sujet')}
50 
51     @method_decorator(login_required)
52     @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))
53     def dispatch(self, request, *args, **kwargs):
54         return super(FeaturedResourceCreate, self).dispatch(request, *args, **kwargs)
55 
56     def get_initial_topic_data(self, topic_id):
57         try:
58             content = Topic.objects.get(pk=int(topic_id))
59         except (Topic.DoesNotExist, ValueError):
60             messages.error(self.request, self.initial_error_message)
61             return {}
62         return {'title': content.title,
63                 'type': self.displayed_content_type['TOPIC'],
64                 'authors': str(content.author),
65                 'url': self.request.build_absolute_uri(content.get_absolute_url())}
66 
67     def get_initial_content_data(self, content_id):
68         try:
69             content = PublishedContent.objects.get(content__pk=int(content_id))
70         except (PublishedContent.DoesNotExist, ValueError):
71             messages.error(self.request, self.initial_error_message)
72             return {}
73         displayed_authors = ', '.join([str(x) for x in content.authors.all()])
74         if content.content.image:
75             image_url = self.request.build_absolute_uri(content.content.image.physical['featured'].url)
76         else:
77             image_url = None
78         return {'title': content.title(),
79                 'type': self.displayed_content_type[content.content_type],
80                 'authors': displayed_authors,
81                 'url': self.request.build_absolute_uri(content.content.get_absolute_url_online()),
82                 'image_url': image_url}
83 
84     def get_initial(self):
85         initial = super(FeaturedResourceCreate, self).get_initial()
86         content_type = self.request.GET.get('content_type', None)
87         content_id = self.request.GET.get('content_id', None)
88         if content_type == 'topic' and content_id:
89             initial.update(**self.get_initial_topic_data(content_id))
90         elif content_type == 'published_content' and content_id:
91             initial.update(**self.get_initial_content_data(content_id))
92         return initial
93 
94     def get_form_kwargs(self):
95         kw = super(FeaturedResourceCreate, self).get_form_kwargs()
96         kw['hide_major_update_field'] = True
97         return kw
98 
99     def form_valid(self, form):
100         featured_resource = FeaturedResource()
101         featured_resource.title = form.cleaned_data.get('title')
102         featured_resource.type = form.cleaned_data.get('type')
103         featured_resource.authors = form.cleaned_data.get('authors')
104         featured_resource.image_url = form.cleaned_data.get('image_url')
105         featured_resource.url = form.cleaned_data.get('url')
106 
107         if form.cleaned_data.get('major_update', False):
108             featured_resource.pubdate = datetime.now()
109         else:
110             featured_resource.pubdate = form.cleaned_data.get('pubdate')
111 
112         featured_resource.save()
113 
114         messages.success(self.request, _('La une a été créée.'))
115         return redirect(reverse('featured-resource-list'))
116 
117 
118 class FeaturedResourceUpdate(UpdateView):
119     """
120     Updates a featured resource.
121     """
122 
123     form_class = FeaturedResourceForm
124     template_name = 'featured/resource/update.html'
125     queryset = FeaturedResource.objects.all()
126     context_object_name = 'featured_resource'
127 
128     @method_decorator(login_required)
129     @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))
130     def dispatch(self, request, *args, **kwargs):
131         return super(FeaturedResourceUpdate, self).dispatch(request, *args, **kwargs)
132 
133     def get_initial(self):
134         initial = super(FeaturedResourceUpdate, self).get_initial()
135         initial.update({
136             'title': self.object.title,
137             'type': self.object.type,
138             'authors': self.object.authors,
139             'image_url': self.object.image_url,
140             'url': self.object.url,
141             'pubdate': self.object.pubdate,
142         })
143 
144         return initial
145 
146     def form_valid(self, form):
147 
148         self.object.title = form.cleaned_data.get('title')
149         self.object.type = form.cleaned_data.get('type')
150         self.object.authors = form.cleaned_data.get('authors')
151         self.object.image_url = form.cleaned_data.get('image_url')
152         self.object.url = form.cleaned_data.get('url')
153         if form.cleaned_data.get('major_update', False):
154             self.object.pubdate = datetime.now()
155         else:
156             self.object.pubdate = form.cleaned_data.get('pubdate')
157 
158         messages.success(self.request, _('La une a été mise à jour.'))
159         self.success_url = reverse('featured-resource-list')
160         return super(FeaturedResourceUpdate, self).form_valid(form)
161 
162     def get_form(self, form_class=None):
163         form = super(FeaturedResourceUpdate, self).get_form(form_class)
164         form.helper.form_action = reverse('featured-resource-update', args=[self.object.pk])
165         return form
166 
167 
168 class FeaturedResourceDeleteDetail(DeleteView):
169     """
170     Deletes a featured resource.
171     """
172 
173     model = FeaturedResource
174 
175     @method_decorator(login_required)
176     @method_decorator(transaction.atomic)
177     @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))
178     def dispatch(self, request, *args, **kwargs):
179         self.success_url = reverse('featured-resource-list')
180         return super(FeaturedResourceDeleteDetail, self).dispatch(request, *args, **kwargs)
181 
182     def post(self, request, *args, **kwargs):
183         r = super(FeaturedResourceDeleteDetail, self).post(request, *args, **kwargs)
184         messages.success(request, _('La une a été supprimée avec succès.'))
185         return r
186 
187 
188 class FeaturedResourceDeleteList(MultipleObjectMixin, RedirectView):
189     """
190     Deletes a list of featured resources.
191     """
192     permanent = False
193 
194     @method_decorator(login_required)
195     @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))
196     def dispatch(self, request, *args, **kwargs):
197         return super(FeaturedResourceDeleteList, self).dispatch(request, *args, **kwargs)
198 
199     def get_queryset(self):
200         items_list = self.request.POST.getlist('items')
201         return FeaturedResource.objects.filter(pk__in=items_list)
202 
203     def post(self, request, *args, **kwargs):
204         for featured_resource in self.get_queryset():
205             featured_resource.delete()
206 
207         messages.success(request, _('Les unes ont été supprimées avec succès.'))
208 
209         return redirect(reverse('featured-resource-list'))
210 
211 
212 class FeaturedMessageCreateUpdate(FormView):
213     """
214     Creates or updates the featured message.
215     """
216 
217     form_class = FeaturedMessageForm
218     template_name = 'featured/message/create.html'
219     last_message = None
220 
221     @method_decorator(login_required)
222     @method_decorator(permission_required('featured.change_featuredmessage', raise_exception=True))
223     def dispatch(self, request, *args, **kwargs):
224         self.last_message = FeaturedMessage.objects.get_last_message()
225         return super(FeaturedMessageCreateUpdate, self).dispatch(request, *args, **kwargs)
226 
227     def get_initial(self):
228         init = super(FeaturedMessageCreateUpdate, self).get_initial()
229 
230         if self.last_message is not None:
231             init.update({
232                 'hook': self.last_message.hook,
233                 'message': self.last_message.message,
234                 'url': self.last_message.url,
235             })
236 
237         return init
238 
239     def form_valid(self, form):
240         if self.last_message:
241             self.last_message.delete()
242 
243         featured_message = FeaturedMessage()
244         featured_message.hook = form.data.get('hook')
245         featured_message.message = form.data.get('message')
246         featured_message.url = form.data.get('url')
247         featured_message.save()
248 
249         messages.success(self.request, _('Le message a été changé'))
250         return redirect(reverse('featured-resource-list'))
251
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/zds/featured/views.py b/zds/featured/views.py
--- a/zds/featured/views.py
+++ b/zds/featured/views.py
@@ -66,7 +66,7 @@
 
     def get_initial_content_data(self, content_id):
         try:
-            content = PublishedContent.objects.get(content__pk=int(content_id))
+            content = PublishedContent.objects.filter(must_redirect=False, content__pk=int(content_id)).first()
         except (PublishedContent.DoesNotExist, ValueError):
             messages.error(self.request, self.initial_error_message)
             return {}
@@ -79,7 +79,7 @@
                 'type': self.displayed_content_type[content.content_type],
                 'authors': displayed_authors,
                 'url': self.request.build_absolute_uri(content.content.get_absolute_url_online()),
-                'image_url': image_url}
+                'image_url': self.request.build_absolute_uri(image_url)}
 
     def get_initial(self):
         initial = super(FeaturedResourceCreate, self).get_initial()

{"golden_diff": "diff --git a/zds/featured/views.py b/zds/featured/views.py\n--- a/zds/featured/views.py\n+++ b/zds/featured/views.py\n@@ -66,7 +66,7 @@\n \n     def get_initial_content_data(self, content_id):\n         try:\n-            content = PublishedContent.objects.get(content__pk=int(content_id))\n+            content = PublishedContent.objects.filter(must_redirect=False, content__pk=int(content_id)).first()\n         except (PublishedContent.DoesNotExist, ValueError):\n             messages.error(self.request, self.initial_error_message)\n             return {}\n@@ -79,7 +79,7 @@\n                 'type': self.displayed_content_type[content.content_type],\n                 'authors': displayed_authors,\n                 'url': self.request.build_absolute_uri(content.content.get_absolute_url_online()),\n-                'image_url': image_url}\n+                'image_url': self.request.build_absolute_uri(image_url)}\n \n     def get_initial(self):\n         initial = super(FeaturedResourceCreate, self).get_initial()\n", "issue": "Erreurs 500 pour \"Ajouter en Une\"\nSur certains contenus, \"Ajouter en Une\" renvoie une erreur 500\r\n\r\nSujet : https://zestedesavoir.com/forums/sujet/11676/ajouter-en-une/#p195045\r\n*Envoy\u00e9 depuis Zeste de Savoir*\n", "before_files": [{"content": "from datetime import datetime\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.urls import reverse\nfrom django.db import transaction\nfrom django.shortcuts import redirect\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic import CreateView, RedirectView, UpdateView, FormView, DeleteView\nfrom django.views.generic.list import MultipleObjectMixin\n\nfrom django.conf import settings\nfrom zds.featured.forms import FeaturedResourceForm, FeaturedMessageForm\nfrom zds.featured.models import FeaturedResource, FeaturedMessage\nfrom zds.forum.models import Topic\nfrom zds.tutorialv2.models.database import PublishedContent\nfrom zds.utils.paginator import ZdSPagingListView\n\n\nclass FeaturedResourceList(ZdSPagingListView):\n    \"\"\"\n    Displays the list of featured resources.\n    \"\"\"\n\n    context_object_name = 'featured_resource_list'\n    paginate_by = settings.ZDS_APP['featured_resource']['featured_per_page']\n    queryset = FeaturedResource.objects.all().order_by('-pubdate')\n    template_name = 'featured/index.html'\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceList, self).dispatch(request, *args, **kwargs)\n\n\nclass FeaturedResourceCreate(CreateView):\n    \"\"\"\n    Creates a new featured resource.\n    \"\"\"\n\n    form_class = FeaturedResourceForm\n    template_name = 'featured/resource/create.html'\n    context_object_name = 'featured_resource'\n    initial_error_message = _('Le contenu est introuvable')\n    displayed_content_type = {'TUTORIAL': _('Un tutoriel'),\n                              'ARTICLE': _('Un article'),\n                              'OPINION': _('Un billet'),\n                              'TOPIC': _('Un sujet')}\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceCreate, self).dispatch(request, *args, **kwargs)\n\n    def get_initial_topic_data(self, topic_id):\n        try:\n            content = Topic.objects.get(pk=int(topic_id))\n        except (Topic.DoesNotExist, ValueError):\n            messages.error(self.request, self.initial_error_message)\n            return {}\n        return {'title': content.title,\n                'type': self.displayed_content_type['TOPIC'],\n                'authors': str(content.author),\n                'url': self.request.build_absolute_uri(content.get_absolute_url())}\n\n    def get_initial_content_data(self, content_id):\n        try:\n            content = PublishedContent.objects.get(content__pk=int(content_id))\n        except (PublishedContent.DoesNotExist, ValueError):\n            messages.error(self.request, self.initial_error_message)\n            return {}\n        displayed_authors = ', '.join([str(x) for x in content.authors.all()])\n        if content.content.image:\n            image_url = self.request.build_absolute_uri(content.content.image.physical['featured'].url)\n        else:\n            image_url = None\n        return {'title': content.title(),\n                'type': self.displayed_content_type[content.content_type],\n                'authors': displayed_authors,\n                'url': self.request.build_absolute_uri(content.content.get_absolute_url_online()),\n                'image_url': image_url}\n\n    def get_initial(self):\n        initial = super(FeaturedResourceCreate, self).get_initial()\n        content_type = self.request.GET.get('content_type', None)\n        content_id = self.request.GET.get('content_id', None)\n        if content_type == 'topic' and content_id:\n            initial.update(**self.get_initial_topic_data(content_id))\n        elif content_type == 'published_content' and content_id:\n            initial.update(**self.get_initial_content_data(content_id))\n        return initial\n\n    def get_form_kwargs(self):\n        kw = super(FeaturedResourceCreate, self).get_form_kwargs()\n        kw['hide_major_update_field'] = True\n        return kw\n\n    def form_valid(self, form):\n        featured_resource = FeaturedResource()\n        featured_resource.title = form.cleaned_data.get('title')\n        featured_resource.type = form.cleaned_data.get('type')\n        featured_resource.authors = form.cleaned_data.get('authors')\n        featured_resource.image_url = form.cleaned_data.get('image_url')\n        featured_resource.url = form.cleaned_data.get('url')\n\n        if form.cleaned_data.get('major_update', False):\n            featured_resource.pubdate = datetime.now()\n        else:\n            featured_resource.pubdate = form.cleaned_data.get('pubdate')\n\n        featured_resource.save()\n\n        messages.success(self.request, _('La une a \u00e9t\u00e9 cr\u00e9\u00e9e.'))\n        return redirect(reverse('featured-resource-list'))\n\n\nclass FeaturedResourceUpdate(UpdateView):\n    \"\"\"\n    Updates a featured resource.\n    \"\"\"\n\n    form_class = FeaturedResourceForm\n    template_name = 'featured/resource/update.html'\n    queryset = FeaturedResource.objects.all()\n    context_object_name = 'featured_resource'\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceUpdate, self).dispatch(request, *args, **kwargs)\n\n    def get_initial(self):\n        initial = super(FeaturedResourceUpdate, self).get_initial()\n        initial.update({\n            'title': self.object.title,\n            'type': self.object.type,\n            'authors': self.object.authors,\n            'image_url': self.object.image_url,\n            'url': self.object.url,\n            'pubdate': self.object.pubdate,\n        })\n\n        return initial\n\n    def form_valid(self, form):\n\n        self.object.title = form.cleaned_data.get('title')\n        self.object.type = form.cleaned_data.get('type')\n        self.object.authors = form.cleaned_data.get('authors')\n        self.object.image_url = form.cleaned_data.get('image_url')\n        self.object.url = form.cleaned_data.get('url')\n        if form.cleaned_data.get('major_update', False):\n            self.object.pubdate = datetime.now()\n        else:\n            self.object.pubdate = form.cleaned_data.get('pubdate')\n\n        messages.success(self.request, _('La une a \u00e9t\u00e9 mise \u00e0 jour.'))\n        self.success_url = reverse('featured-resource-list')\n        return super(FeaturedResourceUpdate, self).form_valid(form)\n\n    def get_form(self, form_class=None):\n        form = super(FeaturedResourceUpdate, self).get_form(form_class)\n        form.helper.form_action = reverse('featured-resource-update', args=[self.object.pk])\n        return form\n\n\nclass FeaturedResourceDeleteDetail(DeleteView):\n    \"\"\"\n    Deletes a featured resource.\n    \"\"\"\n\n    model = FeaturedResource\n\n    @method_decorator(login_required)\n    @method_decorator(transaction.atomic)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        self.success_url = reverse('featured-resource-list')\n        return super(FeaturedResourceDeleteDetail, self).dispatch(request, *args, **kwargs)\n\n    def post(self, request, *args, **kwargs):\n        r = super(FeaturedResourceDeleteDetail, self).post(request, *args, **kwargs)\n        messages.success(request, _('La une a \u00e9t\u00e9 supprim\u00e9e avec succ\u00e8s.'))\n        return r\n\n\nclass FeaturedResourceDeleteList(MultipleObjectMixin, RedirectView):\n    \"\"\"\n    Deletes a list of featured resources.\n    \"\"\"\n    permanent = False\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceDeleteList, self).dispatch(request, *args, **kwargs)\n\n    def get_queryset(self):\n        items_list = self.request.POST.getlist('items')\n        return FeaturedResource.objects.filter(pk__in=items_list)\n\n    def post(self, request, *args, **kwargs):\n        for featured_resource in self.get_queryset():\n            featured_resource.delete()\n\n        messages.success(request, _('Les unes ont \u00e9t\u00e9 supprim\u00e9es avec succ\u00e8s.'))\n\n        return redirect(reverse('featured-resource-list'))\n\n\nclass FeaturedMessageCreateUpdate(FormView):\n    \"\"\"\n    Creates or updates the featured message.\n    \"\"\"\n\n    form_class = FeaturedMessageForm\n    template_name = 'featured/message/create.html'\n    last_message = None\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredmessage', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        self.last_message = FeaturedMessage.objects.get_last_message()\n        return super(FeaturedMessageCreateUpdate, self).dispatch(request, *args, **kwargs)\n\n    def get_initial(self):\n        init = super(FeaturedMessageCreateUpdate, self).get_initial()\n\n        if self.last_message is not None:\n            init.update({\n                'hook': self.last_message.hook,\n                'message': self.last_message.message,\n                'url': self.last_message.url,\n            })\n\n        return init\n\n    def form_valid(self, form):\n        if self.last_message:\n            self.last_message.delete()\n\n        featured_message = FeaturedMessage()\n        featured_message.hook = form.data.get('hook')\n        featured_message.message = form.data.get('message')\n        featured_message.url = form.data.get('url')\n        featured_message.save()\n\n        messages.success(self.request, _('Le message a \u00e9t\u00e9 chang\u00e9'))\n        return redirect(reverse('featured-resource-list'))\n", "path": "zds/featured/views.py"}], "after_files": [{"content": "from datetime import datetime\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.urls import reverse\nfrom django.db import transaction\nfrom django.shortcuts import redirect\nfrom django.utils.decorators import method_decorator\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic import CreateView, RedirectView, UpdateView, FormView, DeleteView\nfrom django.views.generic.list import MultipleObjectMixin\n\nfrom django.conf import settings\nfrom zds.featured.forms import FeaturedResourceForm, FeaturedMessageForm\nfrom zds.featured.models import FeaturedResource, FeaturedMessage\nfrom zds.forum.models import Topic\nfrom zds.tutorialv2.models.database import PublishedContent\nfrom zds.utils.paginator import ZdSPagingListView\n\n\nclass FeaturedResourceList(ZdSPagingListView):\n    \"\"\"\n    Displays the list of featured resources.\n    \"\"\"\n\n    context_object_name = 'featured_resource_list'\n    paginate_by = settings.ZDS_APP['featured_resource']['featured_per_page']\n    queryset = FeaturedResource.objects.all().order_by('-pubdate')\n    template_name = 'featured/index.html'\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceList, self).dispatch(request, *args, **kwargs)\n\n\nclass FeaturedResourceCreate(CreateView):\n    \"\"\"\n    Creates a new featured resource.\n    \"\"\"\n\n    form_class = FeaturedResourceForm\n    template_name = 'featured/resource/create.html'\n    context_object_name = 'featured_resource'\n    initial_error_message = _('Le contenu est introuvable')\n    displayed_content_type = {'TUTORIAL': _('Un tutoriel'),\n                              'ARTICLE': _('Un article'),\n                              'OPINION': _('Un billet'),\n                              'TOPIC': _('Un sujet')}\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceCreate, self).dispatch(request, *args, **kwargs)\n\n    def get_initial_topic_data(self, topic_id):\n        try:\n            content = Topic.objects.get(pk=int(topic_id))\n        except (Topic.DoesNotExist, ValueError):\n            messages.error(self.request, self.initial_error_message)\n            return {}\n        return {'title': content.title,\n                'type': self.displayed_content_type['TOPIC'],\n                'authors': str(content.author),\n                'url': self.request.build_absolute_uri(content.get_absolute_url())}\n\n    def get_initial_content_data(self, content_id):\n        try:\n            content = PublishedContent.objects.filter(must_redirect=False, content__pk=int(content_id)).first()\n        except (PublishedContent.DoesNotExist, ValueError):\n            messages.error(self.request, self.initial_error_message)\n            return {}\n        displayed_authors = ', '.join([str(x) for x in content.authors.all()])\n        if content.content.image:\n            image_url = self.request.build_absolute_uri(content.content.image.physical['featured'].url)\n        else:\n            image_url = None\n        return {'title': content.title(),\n                'type': self.displayed_content_type[content.content_type],\n                'authors': displayed_authors,\n                'url': self.request.build_absolute_uri(content.content.get_absolute_url_online()),\n                'image_url': self.request.build_absolute_uri(image_url)}\n\n    def get_initial(self):\n        initial = super(FeaturedResourceCreate, self).get_initial()\n        content_type = self.request.GET.get('content_type', None)\n        content_id = self.request.GET.get('content_id', None)\n        if content_type == 'topic' and content_id:\n            initial.update(**self.get_initial_topic_data(content_id))\n        elif content_type == 'published_content' and content_id:\n            initial.update(**self.get_initial_content_data(content_id))\n        return initial\n\n    def get_form_kwargs(self):\n        kw = super(FeaturedResourceCreate, self).get_form_kwargs()\n        kw['hide_major_update_field'] = True\n        return kw\n\n    def form_valid(self, form):\n        featured_resource = FeaturedResource()\n        featured_resource.title = form.cleaned_data.get('title')\n        featured_resource.type = form.cleaned_data.get('type')\n        featured_resource.authors = form.cleaned_data.get('authors')\n        featured_resource.image_url = form.cleaned_data.get('image_url')\n        featured_resource.url = form.cleaned_data.get('url')\n\n        if form.cleaned_data.get('major_update', False):\n            featured_resource.pubdate = datetime.now()\n        else:\n            featured_resource.pubdate = form.cleaned_data.get('pubdate')\n\n        featured_resource.save()\n\n        messages.success(self.request, _('La une a \u00e9t\u00e9 cr\u00e9\u00e9e.'))\n        return redirect(reverse('featured-resource-list'))\n\n\nclass FeaturedResourceUpdate(UpdateView):\n    \"\"\"\n    Updates a featured resource.\n    \"\"\"\n\n    form_class = FeaturedResourceForm\n    template_name = 'featured/resource/update.html'\n    queryset = FeaturedResource.objects.all()\n    context_object_name = 'featured_resource'\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceUpdate, self).dispatch(request, *args, **kwargs)\n\n    def get_initial(self):\n        initial = super(FeaturedResourceUpdate, self).get_initial()\n        initial.update({\n            'title': self.object.title,\n            'type': self.object.type,\n            'authors': self.object.authors,\n            'image_url': self.object.image_url,\n            'url': self.object.url,\n            'pubdate': self.object.pubdate,\n        })\n\n        return initial\n\n    def form_valid(self, form):\n\n        self.object.title = form.cleaned_data.get('title')\n        self.object.type = form.cleaned_data.get('type')\n        self.object.authors = form.cleaned_data.get('authors')\n        self.object.image_url = form.cleaned_data.get('image_url')\n        self.object.url = form.cleaned_data.get('url')\n        if form.cleaned_data.get('major_update', False):\n            self.object.pubdate = datetime.now()\n        else:\n            self.object.pubdate = form.cleaned_data.get('pubdate')\n\n        messages.success(self.request, _('La une a \u00e9t\u00e9 mise \u00e0 jour.'))\n        self.success_url = reverse('featured-resource-list')\n        return super(FeaturedResourceUpdate, self).form_valid(form)\n\n    def get_form(self, form_class=None):\n        form = super(FeaturedResourceUpdate, self).get_form(form_class)\n        form.helper.form_action = reverse('featured-resource-update', args=[self.object.pk])\n        return form\n\n\nclass FeaturedResourceDeleteDetail(DeleteView):\n    \"\"\"\n    Deletes a featured resource.\n    \"\"\"\n\n    model = FeaturedResource\n\n    @method_decorator(login_required)\n    @method_decorator(transaction.atomic)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        self.success_url = reverse('featured-resource-list')\n        return super(FeaturedResourceDeleteDetail, self).dispatch(request, *args, **kwargs)\n\n    def post(self, request, *args, **kwargs):\n        r = super(FeaturedResourceDeleteDetail, self).post(request, *args, **kwargs)\n        messages.success(request, _('La une a \u00e9t\u00e9 supprim\u00e9e avec succ\u00e8s.'))\n        return r\n\n\nclass FeaturedResourceDeleteList(MultipleObjectMixin, RedirectView):\n    \"\"\"\n    Deletes a list of featured resources.\n    \"\"\"\n    permanent = False\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredresource', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        return super(FeaturedResourceDeleteList, self).dispatch(request, *args, **kwargs)\n\n    def get_queryset(self):\n        items_list = self.request.POST.getlist('items')\n        return FeaturedResource.objects.filter(pk__in=items_list)\n\n    def post(self, request, *args, **kwargs):\n        for featured_resource in self.get_queryset():\n            featured_resource.delete()\n\n        messages.success(request, _('Les unes ont \u00e9t\u00e9 supprim\u00e9es avec succ\u00e8s.'))\n\n        return redirect(reverse('featured-resource-list'))\n\n\nclass FeaturedMessageCreateUpdate(FormView):\n    \"\"\"\n    Creates or updates the featured message.\n    \"\"\"\n\n    form_class = FeaturedMessageForm\n    template_name = 'featured/message/create.html'\n    last_message = None\n\n    @method_decorator(login_required)\n    @method_decorator(permission_required('featured.change_featuredmessage', raise_exception=True))\n    def dispatch(self, request, *args, **kwargs):\n        self.last_message = FeaturedMessage.objects.get_last_message()\n        return super(FeaturedMessageCreateUpdate, self).dispatch(request, *args, **kwargs)\n\n    def get_initial(self):\n        init = super(FeaturedMessageCreateUpdate, self).get_initial()\n\n        if self.last_message is not None:\n            init.update({\n                'hook': self.last_message.hook,\n                'message': self.last_message.message,\n                'url': self.last_message.url,\n            })\n\n        return init\n\n    def form_valid(self, form):\n        if self.last_message:\n            self.last_message.delete()\n\n        featured_message = FeaturedMessage()\n        featured_message.hook = form.data.get('hook')\n        featured_message.message = form.data.get('message')\n        featured_message.url = form.data.get('url')\n        featured_message.save()\n\n        messages.success(self.request, _('Le message a \u00e9t\u00e9 chang\u00e9'))\n        return redirect(reverse('featured-resource-list'))\n", "path": "zds/featured/views.py"}]}