2016-03-18 5 views
0

я пытаюсь установить тест Джанго куки на главной странице, но не получает набор set.I испробовали все от изменения классов промежуточного слоя для sessionengines моего индекс функцииДжанго печенья не получает набор

индекса четкости (запрос):

request.session.set_test_cookie() 
if request.method == 'POST': 
    # create a form instance and populate it with data from the request: 
    form = NameForm(request.POST) 
    # check whether it's valid: 
    if form.is_valid(): 
     # process the data in form.cleaned_data as required 
     # ... 
     # redirect to a new URL: 
     return HttpResponseRedirect('/thanks/') 

# if a GET (or any other method) we'll create a blank form 
else: 
    form = NameForm() 

return render(request, 'name.html', {'form': form}) 

вот моя другая функция, чтобы проверить Cookie

защиту регистр (запрос):

if request.session.test_cookie_worked(): 
    print ">>>> TEST COOKIE WORKED!" 
    request.session.delete_test_cookie() 
# Like before, get the request's context. 
context = RequestContext(request) 

# A boolean value for telling the template whether the registration was successful. 
# Set to False initially. Code changes value to True when registration succeeds. 
registered = False 

# If it's a HTTP POST, we're interested in processing form data. 
if request.method == 'POST': 
    # Attempt to grab information from the raw form information. 
    # Note that we make use of both UserForm and UserProfileForm. 
    user_form = UserForm(data=request.POST) 
    profile_form = UserProfileForm(data=request.POST) 

    # If the two forms are valid... 
    if user_form.is_valid() and profile_form.is_valid(): 
     # Save the user's form data to the database. 
     user = user_form.save() 

     # Now we hash the password with the set_password method. 
     # Once hashed, we can update the user object. 
     user.set_password(user.password) 
     user.save() 

     # Now sort out the UserProfile instance. 
     # Since we need to set the user attribute ourselves, we set commit=False. 
     # This delays saving the model until we're ready to avoid integrity problems. 
     profile = profile_form.save(commit=False) 
     profile.user = user 

     # Did the user provide a profile picture? 
     # If so, we need to get it from the input form and put it in the UserProfile model. 


     # Now we save the UserProfile model instance. 
     profile.save() 

     # Update our variable to tell the template registration was successful. 
     registered = True 

    # Invalid form or forms - mistakes or something else? 
    # Print problems to the terminal. 
    # They'll also be shown to the user. 
    else: 
     print user_form.errors, profile_form.errors 

# Not a HTTP POST, so we render our form using two ModelForm instances. 
# These forms will be blank, ready for user input. 
else: 
    user_form = UserForm() 
    profile_form = UserProfileForm() 

# Render the template depending on the context. 
return render_to_response(
     'register.html', 
     {'user_form': user_form, 'profile_form': profile_form, 'registered': registered}, 
     context) 

ответ

0

Вам не нужно делать все эти изменения среднего уровня в вашем файле настроек. Я только что попробовал создать простую демонстрацию вашего кода, и он отлично работает.

Прежде всего, попытайтесь свести к минимуму ваш код только в настройках cookie «эксперимент». Вы можете попробовать эту демонстрацию здесь.

Один вид, возможно, индекс домашнего вида, установленный в файле cookie. На другом представлении, возможно, индексный просмотр другого приложения проверяет файл cookie.

From the docs you can only test using another page request I quote 
    *test_cookie_worked()* "Returns either True or False, depending on whether the user’s  
    browser accepted the test cookie. Due to the way cookies work, 
    you’ll have to call set_test_cookie() on a previous, 
    separate page request. See Setting test cookies below for more information." 

    project/appxx/views ... request.session.set_test_cookie() #inside a view 
    project/appyy/views ... if request.session.test_cookie_worked(): 
           request.session.delete_test_cookie() 
           return HttpResponse(">>>> TEST COOKIE WORKED!") 

Тогда вы можете добавить логику позже. Я использовал метод HttResponse вместо используемого вами штампа печати.

Смежные вопросы