aman goyal
aman goyal

Reputation: 301

How to send dictionary context data to view from template in django

I am passing a dict object to template and using that dict object to fill up table data. But depending on the need I want to send that dictionary data to another view for processing. I tried sending data using URL parameter which is affecting data in dictionary.

View

class GeneratedReportView(View):
    """
    View to display all details about a single patient

    @param:
    is_single_document: bool, if true it means only single document exist for patient
                        and to display only one col in html page
    """
    
    model = Patient
    template_name = 'patient/patient_generated_report.html'
    context_object_name = 'object'
    form = GeneratedReportForm()

    # helper function
    def create_final_report(self, doc1_obj: Document, doc2_obj: Document = None, is_single_document: bool = False) :

        # template of how data is passed on to html page
        table = {
            'doc1_name':'',
            'doc2_name':'',
            'label':{
                'doc1': {'value':'value', 'unit':'unit'},
                'doc2': {'value':'value', 'unit':'unit'},
                'remark':  '', #`doc1_value - doc2_value`,
                'remark_color': '', #`red or green`,
            }
        }

        #
        # some code to populate table data 
        #

        return table, is_single_document

    def get(self, request, pk):
        # instantiating form for selected particular user
        form = GeneratedReportForm(pk=pk)
        patient_obj = Patient.objects.get(pk=pk)
        # retrieving all document of patient.pk = pk from latest to oldest
        documents = Document.objects.filter(patient__id=pk).order_by('-uploaded_at')
        table, is_single_document = None, None
        doc1_obj, doc2_obj = None, None
        try:
            doc2_obj = documents[0]  # most recent report
            doc1_obj = documents[1]  # second most recent report
        except Exception as e:
            print('ERROR while getting doc2, doc2 obj', e)

        if doc2_obj is not None:
            table, is_single_document = self.create_final_report(doc2_obj, doc1_obj)
        
        if table is not None:
            table = dict(table)   # <-- NOTICE HERE

        context = {
        
        'table':table,           # <-- NOTICE HERE, table variable is dict type
        
        'patient_obj':patient_obj,
        'doc1_obj':doc1_obj,
        'doc2_obj':doc2_obj,
        'is_single_document' : is_single_document,
        'form':form ,
        }
        return render(request, self.template_name, context)

Template

        <table id="example" class="table table-striped">
            <thead>
                <tr>
                    <th>Label</th>
                    {% if not is_single_document %}
                    {% if doc1_obj %} <th>{{doc1_obj}}</th> {% else %} <th>Old Report</th> {% endif %}
                    {% endif %}
                    {% if doc2_obj %}<th>{{doc2_obj}}</th> {% else %} <th>Latest Report</th> {% endif %}
                    <th>remark</th>
                </tr>
            </thead>
            <tbody>
                {% if table %}
                {% for label, docs in table.items %}
                <tr>
                    <td>{{label}}</td>
                    <td>{{docs.doc1.value}}</td>
                    {% if not is_single_document %}
                    <td>&nbsp;&nbsp;&nbsp;&nbsp;{{docs.doc2.value}}</td>
                    {% endif %}
                    <td {% if not is_single_document %}bgcolor="{{docs.remark_color}}" {% endif %}>{{docs.remark}}</td>
                </tr>
                {% endfor %}
                {% endif %}

            </tbody>
        </table>
            <a href='{% url 'save' table %}'>
                <button class="GFG">
                    Approve now
                </button>
            </a>


I am trying to send the table to another view using this URL conf but data obtained in view is not proper, is contains % and other characters.

    url(r'^save/(?P<oid>.*)$', GeneratedReportSaveView.as_view(), name='save'),

I would appreciate some recommendation and suggestions. Thanks

Upvotes: 1

Views: 2799

Answers (1)

aman goyal
aman goyal

Reputation: 301

After searching a lot, found a suggestion that on Django-forum that lead me to develop a solution, the discussion can be seen here.

I found the solution by redefining the problem to say How to pass data between views? This can be done by using Django-session. Basically it's about saving data in request.session which can be accessed easily in any view as long as the session is active.

class GeneratedReportView(View):

    def create_final_report(self, doc1_obj: Document, doc2_obj: Document = None, is_single_document: bool = False) :
        #
        # ...No change here...
        #
        return table, is_single_document     

    def get(self, request, pk):
        # normal code ..
        
        request.session['table'] = table       # <--- NOTICE HERE

        context = {        
        'table':table,                   
        'patient_obj':patient_obj,
        'doc1_obj':doc1_obj,
        'doc2_obj':doc2_obj,
        'is_single_document' : is_single_document,
        'form':form ,
        }
        return render(request, self.template_name, context)

now this data can be accessed in any other view as long as this is not deleted or session is closed.

class AnotherView(View):
     def get(self, request):
         table = request.session['table']    # <- Getting table data from another view
         
          # further code

Upvotes: 1

Related Questions