jribault
jribault

Reputation: 31

django updateview preview button

I'm wondering how to build a "Preview" button for a django UpdateView page.

I first add a second button to my form in my template:

<button type="preview" class="btn btn-default" value="preview" name="preview">{% trans 'Preview' %}</button>

Then I overwrite the method form_valid in my code :

 def form_valid(self, form):
    if 'preview' in self.request.POST:
        #??? Don't know what to do here
    return super(SongEditView, self).form_valid(form)

But I don't know which method to call to refresh the UpdateView while using current form value instead of database value. It probably as something to do with the context ... but I didn't find what method to call to refresh (render ?) my page.

PS: The preview from "stackoverflow" is pretty awesome, how to do that, using ajax ?

Upvotes: 2

Views: 744

Answers (1)

jribault
jribault

Reputation: 31

I found a solution (probably not the best) :

I have 2 buttons in my template (same name, but different value):

<button type="submit" class="btn btn-default" value="submit" name="submit">{% trans 'Submit' %}</button>
<button type="preview" class="btn btn-default" value="preview" name="submit">{% trans 'Preview' %}</button>

In the form_valid(), I put the preview in session if user hit the preview button and then call my page again.

def form_valid(self, form):
    if self.request.POST['submit'] == 'preview':
        self.request.session['previewsong'] = self.request.POST['body']
        return HttpResponseRedirect(reverse('editsong', args={self.object.id, self.object.nice_url}))
    return super(SongEditView, self).form_valid(form)

Finally, I also overwrite the get_context_data method to read the session information and fill the form and preview with value from the session.

    def get_context_data(self, **kwargs):
    context = super(SongEditView, self).get_context_data(**kwargs)
    if('previewsong' in self.request.session):
        context['preview'] = self.request.session['previewsong']
        context['form'].initial['body'] = self.request.session['previewsong']
        del self.request.session['previewsong']
    return context

Is there a better way to do it ? I can't do it using javascript because I have some django filter to display the render.

Upvotes: 1

Related Questions