Hanny
Hanny

Reputation: 692

Django: Save forms cleaned_data with foreign key as session items

I've got a ModelForm with a number of attributes - in the CreateView form_valid method I'm trying to save a users form inputs as session data (which I check for in the get_initial method if they visit the form again)

ModelForm:

class OrgForm(forms.ModelForm):
    """Form definition for a Org."""

    class Meta:
        """Meta definition for OrgForm."""

        model = Org
        fields = (
            "full_name",
            "short_name",
            "feature",
            "state",
            "email",
        )

View:

class OrgCreateView(CreateView):
    "CreateView for OrgForm"
    model = Org
    form_class = OrgForm
    success_url = "/home/"

    def form_valid(self, form):
        response = super().form_valid(form)
        # Set the form data to session variables
        responses = {}
        for k, v in form.cleaned_data.items():
            responses[k] = v
        self.request.session["org_form_data"] = responses
        return super().form_valid(form)

    def get_initial(self):
        initial = super(OrgCreateView, self).get_initial()
        # Check for any existing session data
        # This is present if they had filled this out
        # and then came back again later to fill out again
        if "org_form_data" in self.request.session:
            # They have data - loop through and fill it out
            for key, value in self.request.session["org_form_data"]:
                initial[key] = value
        return initial

Model:

class Org(models.Model):
    """Model definition for Org."""

    full_name = models.CharField(max_length=150)
    short_name = models.CharField(max_length=25, blank=True, null=True)
    state = models.CharField(max_length=50)
    is_active = models.BooleanField(default=False)
    feature = models.ForeignKey(Feature, on_delete=models.PROTECT)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    email = models.EmailField()

I have an attribute in there that has a Foreign Key - so when I save the form I get the error:

Object of type Feature is not JSON serializable

I'm not sure how best to go about getting around that error - or even if this is the right way to go about it.

Any help is appreciated!

Upvotes: 1

Views: 330

Answers (1)

Chris
Chris

Reputation: 41

You can use sessions in Django:

Session Configuration

To set up a session in Django, You need to add two things in your settings.py:

‘django.contrib.sessions.middleware.SessionMiddleware   'to MIDDLEWARE
'django.contrib.sessions   'to INSTALLED_APPS.

Run python manage.py migrate to populate the table. The table has three columns:

  • session_key
  • session_data
  • expire_date

Reading and Writing Session Data

A Django request object has a session attribute that acts like a dictionary.

Set session data

request.session['user_id'] = ‘20’
request.session['team'] = ‘Barcelona’

like request.session['your cookie name'] = your value

Read session data

request.session.get('user_id') # returns ‘20’
request.session.get('team') # returns ‘Barcelona’ 

Delete session data

del request.session['user_id']
del request.session['user_id']

I've tried this method, and it works perfectly! You can ask Django for session values:

if request.session('cookiename') == True:
    print("It is TRUE!")

Upvotes: 1

Related Questions