Django Session变量未正确更新

时间:2016-11-30 16:17:25

标签: python django forms session

我想弄清楚会话是如何运作的。基本上我正在尝试制作餐馆菜单并将有序食品存入会议以供进一步使用。但是,我遇到了一个问题,我无法弄清楚可能是什么问题。

问题是如果我第一次提交表格。成功视图显示正确的数据。

I click Submit (pridat) and it works correctly

输出结果为:

('2', 1)

其中数字2是食物ID,1是数量。 然后我回到菜单,我想更新数量,让我们说3

I change quantity (mnozstvo) to 3 and submit

但输出仍然是:

('2', 1)

令我困惑的最奇怪的事情是,例如不同的食物,即使它应该以相同的方式生成和更新就好了。

如果我想"订购"多个东西它可以正常工作,有时一个或多个只是拒绝正确更新。正如我写的那样,这4件作品中的3件就好了。

('3', 5)('4', 8)('1', 15)('2', 1)

我可以改变3-5,4-8和1-15但是2-1永远不会改变。

如果我重新启动内置的django服务器,有时不同的对不能正确更新。这次是2-1,但我也有一个3-5不会更新的问题。

如果有人能告诉我我做错了什么,我会很高兴的吗?我知道我不会让django生成表单,但我宁愿在html中手动执行,但这应该不是问题,是吗?

menu.html,表单分隔,以提高可见性

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'restaurant/style.css' %}" />
{% if all_food_list %}
     <center>
     <ul>
        <li><a href="http://127.0.0.1:8000/">Home</a></li>
        <li><a href="/menu/">Menu</a></li>
        <li style="float:right"><a class="active" href="#about">Objednavka</a></li>
     </ul>
    <div class="clearfix">
    {% for food in all_food_list %}
    <div class="div1">
    <center>
        <img src="{{ MEDIA_URL }}{{ food.picture.url }}" alt="{{ food.name }}">
        <h2> {{ food.name}} </h2>
        <p>Cena: {{ food.price }}czk</p>
        <p>Hmotnost: {{ food.weight}}g</p>
        <p>Zlozenie: {{ food.ingredients}}</p>



        <form action="/get_food/" method="post">
            {% csrf_token %}
        Mnozstvo: <input id="test" type="number" name="quantity" min="0" max="30" step="1" value="1">
        <input type="hidden" name="food_type" value="{{ food.id }}">
        <input type="submit" value="Pridat">
        </form>




    </center>
    </div>
    {% endfor %}
    TODO: Funkcny formular, view pre objednavku, nastavit limity div-ov.
    </div>
    </center>
{% else %}
    <p>No food available.</p>
{% endif %}

我的views.py

    from django.shortcuts import render
    from django.http import HttpResponse, HttpResponseRedirect
    from django.template import loader
    from .models import Food
    from .forms import FoodOrder

def index(request):
    template = loader.get_template('restaurant/index.html')
    request.session.flush()
    return HttpResponse(template.render(request))
def menu (request):
    all_food_list = Food.objects.order_by('name')
    template = loader.get_template('restaurant/menu.html')
    context = {
        'all_food_list': all_food_list,
    }
    return HttpResponse(template.render(context, request))
def get_food(request):
    if request.method == 'POST':
        form = FoodOrder(request.POST)
        if form.is_valid():
            quantity = form.cleaned_data['quantity']
            #Food_type is db food id
            food_type = form.cleaned_data['food_type']
            #add to the session
            request.session[food_type] = quantity

            return HttpResponseRedirect('/success/')
        else:
            return HttpResponseRedirect('/index/')
def success(request):
    #just writes the content of session
    obsah = request.session.items()
    return HttpResponse(obsah)

# Create your views here.

forms.py

from django import forms

class FoodOrder(forms.Form):
    quantity = forms.IntegerField()
    food_type = forms.IntegerField()

settings.py

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'restaurant.apps.RestaurantConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'iis_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'iis_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

STATIC_URL = '/static/'
MEDIA_ROOT = 'D:\Škola\IIS\Projekt - Restaurace\media'
MEDIA_URL = '/media/'

0 个答案:

没有答案