Странная ошибка Джанго - PullRequest
       1

Странная ошибка Джанго

0 голосов
/ 10 ноября 2011

Это мои views.py:

# Create your views here.

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.db import models

    from display.forms import CodeForm
    from display.forms import CodeFormSet
    from ExamPy.questions.models import QuestionBase


    def codepost(request):
        if request.method == 'POST':
            form = CodeFormSet(request.POST)
            if form.is_valid():
                titles = []
                for i in range(0, self.total_form_count()):
                            form = self.forms[i]
                            title = form.cleaned_data['title']
                            if title in titles:
                                raise forms.ValidationError("Articles in a set must have distinct titles.")
                                titles.append(title)
                return render_to_response('quesdisplay.html')
        else:
            form = CodeFormSet()

        return render_to_response('quesdisplay.html', {'form':form})

Таким образом, когда я нажимаю на кнопку «Отправить», она должна показывать Quesdisplay.html без какой-либо формы.Но он ведет меня на какую-то контактную страницу, которой даже не существует.

Ошибка:

The current URL, contact/, didn't match any of these.

Я испробовал все возможные способы отладки, но это невозможно, поскольку в этом нет никаких следов чего-либо, называемого «контактом».

Редактировать: Это предупреждение я получаю:

/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py:101: UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.
  warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value.  This is usually caused by not using RequestContext.")
[10/Nov/2011 05:34:17] "

1 Ответ

3 голосов
/ 10 ноября 2011

Как видно из предыдущего комментария, использование Requestcontext решит вашу проблему.

Вот документация о csrf_token: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#how-to-use-it

Как мы можем прочитать:

Используйте RequestContext, который всегда использует django.core.context_processors.csrf (независимо от того, какой у вас параметр TEMPLATE_CONTEXT_PROCESSORS). Если вы используете общие представления или приложения для вклада, вы уже охвачены, поскольку эти приложения повсеместно используют RequestContext.

Так что здесь, похоже, мы не используем универсальное представление,ни вклад приложенияИтак, что нам нужно, чтобы передать RequestContext, потому что похоже, что защита csrf работает в Django.

from django.core.context_processors import csrf
from django.shortcuts import render_to_response

def my_view(request):
    c = {}
    c.update(csrf(request))
    # ... view code here
    return render_to_response("a_template.html", c)

или

from django.views.generic.simple import direct_to_template

def app_view(request):             
    return direct_to_template(request, 'app_template.html', app_data_dictionary)

или

from django.shortcuts import render_to_response
from django.template import RequestContext

def app_view(request):
    return render_to_response('app_template.html', 
                              app_data_dictionary, 
                              context_instance=RequestContext(request))

ТакжеДокументация говорит о: скрипт extras / csrf_migration_helper.py.Кажется, будет полезным для вашего случая:)

Надеюсь, это поможет;)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...