Home Ask Login Register

Developers Planet

Your answer is one click away!

Yunti February 2016

django view Session ID -missing for user not logged in

On my current project I want the user to be able to fill in forms without having to sign up first (to make them more likely to use the service).

On the below view I'm trying to either save the registered user with the form data, or if the user isn't registered save the Session ID as a temporary user id.

However when I try to use the session ID it returns none. I'm not sure why the data is missing? (Session have the default django setup in apps and middleware as per the docs). Note when a user is logged in it seem to have a user id but not when no user is logged in.


class ServiceTypeView(CreateView):
    form_class = ServiceTypeForm
    template_name = "standard_form.html"
    success_url = '/'

    def form_valid(self, form):
        if self.request.user.is_authenticated():
            form.instance.user = self.request.user
            form.instance.temp_user = self.request.session.session_key
        online_account = form.cleaned_data['online_account']
        if online_account:
            return redirect('../online')
            return redirect('../address')


class EUser(models.Model):

    supplier1 = models.OneToOneField(SupplierAccount)
    supplier2 = models.OneToOneField(SupplierAccount)
    supplier3 = models.OneToOneField(SupplierAccount)
    online_account = models.BooleanField()
    address = models.OneToOneField(Address, null=True)
    temp_user = models.CharField(max_length=255, null=True)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, default=None)

class SupplierAccount(models.Model):
    supplier = models.ForeignKey(Supplier)
    username = models.CharField(max_length=255)
    password = models.CharField(max_length=255)


class ServiceTypeForm(forms.ModelForm):
    # BOOL_CHOICES = ((False, 'No'), (True, 'Yes'))

    # online_account = f        


Kevin Brown February 2016

The session key will exist if there is data set in the session dictionary already. Logged in users have a session key because Django stores authentication related data in the session by default, so a key will always be assigned because of that.

You can ensure that a key always exists by tossing some data into the session storage before trying to get the key.

Post Status

Asked in February 2016
Viewed 3,105 times
Voted 6
Answered 1 times


Leave an answer

Quote of the day: live life