简体   繁体   中英

Django - Pass Session Variables From One View To Another ('request' is undefined)

I have looked at this ( django variable of one view to another from session ), but I believe the desired outcome is quite different.

I have two views in my views.py file: projectcreation and projectconfirm. After the user fills out a form in the projectcreation view, I want them to be directed to a confirmation page that gives a read-only view of the variables before proceeding with the project creation.

My views.py file looks like this:

from django.shortcuts import render
from django.http import HttpResponse
from .projectform import ProjectForm
from .projectconfirm import ProjectConfirm

def projectcreation(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            request.session['projectname'] = form.cleaned_data['client'] + "-" + form.cleaned_data['stage'] + "-" + form.cleaned_data['purpose']
            request.session['computeapi'] = form.cleaned_data['computeapi']
            request.session['deploymentmanapi'] = form.cleaned_data['deploymentmanapi']
            request.session['storagecompapi'] = form.cleaned_data['storagecompapi']
            request.session['monitorapi'] = form.cleaned_data['monitorapi']
            request.session['loggingapi'] = form.cleaned_data['loggingapi']
            return render(request,'projectconfirm.html')
    else:
        form = ProjectForm()
    return render(request, 'projectform.html', {'form': form})

def projectconfirm(request):
    if request.method =='POST':
        print("Now beginning deployment...")
    else:
        form = ProjectConfirm()
    return render(request, 'projectconfirm.html', {'form': form})

The problem I'm facing and admittedly not understanding is how to load the session variables in the projectconfirm.py script. I thought something like the following would work, but it's complaining that 'request' is an undefined variable:

from django import forms
from django.shortcuts import render
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, Row, Column, Field, Fieldset

class ProjectConfirm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': request.session['projectname']}))
    computeapi = forms.CharField(widget=forms.TextInput(attrs={'placeholder': request.session['computeapi']}))
    deploymentmanapi = forms.CharField(widget=forms.TextInput(attrs={'placeholder': request.session['deploymentmanapi']}))
    storagecompapi = forms.CharField(widget=forms.TextInput(attrs={'placeholder': request.session['storagecompapi']}))
    monitorapi = forms.CharField(widget=forms.TextInput(attrs={'placeholder': request.session['monitorapi']}))
    loggingapi = forms.CharField(widget=forms.TextInput(attrs={'placeholder': request.session['loggingapi']}))

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Fieldset(
                'Project Name',
                Row(
                    Column('name', css_class='form-group col-md-4 mb-0', readonly=True),
                )
            ),
            Fieldset(
                'APIs To Enable',
                Row(
                    Column('computeapi', css_class='form-group col-md-4 mb-0', readonly=True),
                    Column('deploymentmanapi', css_class='form-group col-md-4 mb-0', readonly=True),
                    Column('storagecompapi', css_class='form-group col-md-4 mb-0', readonly=True),
                    Column('monitorapi', css_class='form-group col-md-4 mb-0', readonly=True),
                    Column('loggingapi', css_class='form-group col-md-4 mb-0', readonly=True)
                )
            ),
            Submit('Deploy', 'Deploy', css_class='btn-success')
        )

In constructor of Form request can be obtained by:

  1. Passing it through **kwargs , so:
# in your view:
form = ProjectConfirm(request=request)

# in ProjectConfirm
class ProjectConfirm(forms.ModelForm):
    name = forms.CharField(widget=forms.TextInput(attrs={}))
    # etc

    def __init__(self, *args, **kwargs):
        request = kwargs.pop("request")
        super().__init__(*args, **kwargs)
        # ... and then define your widgets inside your __init__
        self.fields['name'].widget.attrs['placeholder'] = request.session["projectname"]
        # etc
  1. By defining Form as a nested class of your view, but it has to be class-view instead of function.Then you can pass it to your form, still it's not an elegant solution as it's mixing views and forms in the same module. Anyway it will be something like that:
class YourView(FormView):
    def get_form_class(self):
        request = self.request
        class ProjectConfirm(forms.Form):
            # your existing form definition
        return ProjectConfirm

Let me know if it's helpful for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM