How can I store form input in a session in Django?

6.7k views Asked by At

Who can help me with the following challenge?

I have a registration template where users can sign up. They are then redirected to an url with a payment button and activated when a successful payment is made. In the HTML template I store the username in a custom field within the payment button which is used to later activate the account. Now since the user is not activated/logged in yet, I can't call the user object yet like {{user.username}}. So I want to try sessions to solve this and capture the username during registration to retrieve this session variable and put it in my custom field on a different page. But how? I tried using request.session but I’m not sure where to fit this the files below and then how to call this variable in the html template.

Any advise or help is greatly appreciated!

Here is my regbackend.py

class MyRegistrationView(RegistrationView):  
    form_class = UserProfileRegistrationForm
def register(self, form_class):
    user_package.username = form_class.cleaned_data['username']

And here my forms.py

class SignUpForm(forms.ModelForm):
class Meta:
    model = SignUp
    fields = ['username', 'email']

Here my registration.html

<form method="post" action=".">
{% csrf_token %}
{{ form.username|as_crispy_field }}
 <input class="btn btn-success" type="submit" value="{% trans 'Submit' %}" /></form>

And finally my HTML Template for after registration with the payment button and custom field.

 <form action="some-url" method="post" target="_top">
 <input type="hidden" name="custom" value="{{ session.username? }}">
 </form>

Im using Django 1.9x and Django-registration-redux

1

There are 1 answers

0
Horai Nuri On

This is how I keep the session to use it on another view.

On your registration form :

def registration(request):
    initial={'username': request.session.get('username', None)}
    form = RegistrationForm(request.POST or None, initial=initial)
    if request.method == 'POST':
        if form.is_valid():
            request.session['username'] = form.cleaned_data['username']
            return HttpResponseRedirect(reverse('your_checkout_view'))
    return render(request, 'registration.html', {'form': form})

Once the username field is completed and the form submited it goes to the second view in which you can take the username that is stored in your session.

Just like this :

def your_checkout_view(request):
    username = request.session['username']
    ...

From there you can take the stored username and do what you have to do.