Search code examples
pythondjangosessioncookiesdjango-sessions

Store name value with Django sessions for another view


The error that Django throws at me when I fill in the form is: 'GetSessionName' object has no attribute 'name' and I have never worked with sessions before so I don't know how to solve this problem. The idea of the site is to have a small Login screen where you type your name then move to the chat.

views.py

from django.shortcuts import render, redirect
from django.utils import timezone
from .models import *
from .forms import Chat, GetSessionName

def chat(request):

    Messages = Message.objects.all().order_by('-created')

    form = Chat()


    if request.method == "POST":
        form = Chat(request.POST)
        if form.is_valid():
            form.save()
        return redirect ("chat")

    name = request.session['name']

    context = {"Message": Messages, "form": form, 'name': name}


    return render(request, 'chat/chat_messages.html', context)

def login(request):

    form = GetSessionName()

    if request.method == "POST":
        form = GetSessionName(request.POST)
        if form.is_valid():
            request.session['name'] = form.name
            return redirect('chat')

    context={'form': form}

    return render(request, 'chat/chat_login.html', context)  

forms.py

from django import forms
from django.forms import ModelForm
from .models import Message
from .models import *

class Chat(forms.ModelForm):

    class Meta:

        model = Message
        fields = "__all__"

class GetSessionName(forms.Form):

    name = forms.CharField(max_length=30)

chat_login.html

{% extends 'chat/base.html' %}
{% block content %}

<form method="POST" action="">
    {% csrf_token %}
    {{form}}
</form>

{% endblock content %}

Solution

  • you clearly right used sessions but the problem is getting field name in dicts of forms. You just should add 'cleaned_data' def login(request):

    form = GetSessionName()
    
    if request.method == "POST":
        form = GetSessionName(request.POST)
        if form.is_valid():
            request.session['name'] = form.cleaned_data['name']
            return redirect('chat')
    
    context={'form': form}
    
    return render(request, 'chat/chat_login.html', context)    
    

    Best regards