YMY
YMY

Reputation: 13

Render context data to generic.DetailView

How can i render data or redirect with context data to generic.DetailView. I have model Note

class Note(models.Model):
    key = models.CharField(max_length=50, primary_key=True)
    text = models.TextField()

and my view is

class ShowNote(generic.DetailView):
    model = Note
    template_name = 'notes/show_note.html'

    def get(self, request, *args, **kwargs):
        try:
            self.object = self.get_object()
        except Http404:
            # redirect here
            return render(request, 'notes/index.html', {'error': 'Note doesnt exist', })
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)

url(r'^show/(?P.*)/$', views.ShowNote.as_view(), name='show_note'),

The page show the key of the note and its text also there is a button which save the text if it was changed.

def save_note(request):
    key = request.POST['key']
    selected_note = Note.objects.get(pk=key)
    selected_note.text = request.POST['text']
    selected_note.save()
    //back to show_note

How can i render a data {'message' : 'note was saved successfully'} in 'notes/show_note.html' but with same primary key

Upvotes: 0

Views: 1763

Answers (1)

Arpit Solanki
Arpit Solanki

Reputation: 9931

You can override get_context_data method for this. Put the below method in your class based view.

def get_context_data(self, **kwargs):
    data = super().get_context_data(**kwargs)
    data['message'] = 'note was saved successfully'
    return data

Then in the template

{{ message }}

docs will be a good help here.

Another method would be to use messages module from django.contrib.messages.

you can use something like below in your code

def get(self, request, *args, **kwargs):
.... # your code    
    messages.success(request, "Note was added successfully")

then in templates

{% for message in messages%}
    {{ message }}
{% endfor %}

Upvotes: 5

Related Questions