CSRF令牌丢失或不正确

时间:2012-03-14 22:28:20

标签: django django-forms

我收到403禁止错误。我已经尝试过在论坛上解释过的上下文内容,但我还是在第一个方面。

我做错了什么?我的views.py

def add_player(request, team_id):
    template = get_template('cricket/addplayer.html')
    loggedinuser = request.user
    team = Team.objects.get(id=team_id)
    if request.method== 'POST':
        form = PlayerForm(request.POST)
        if form.is_valid():
            player = Player.objects.create(
                name = form.cleaned_data['name'],
                team = Team.objects.get(id=team_id),
                role = form.cleaned_data['role'],
                position = form.cleaned_data['position']
            )

            return HttpResponseRedirect('/team/%s/' % team_id)
    else:
        form = PlayerForm

    page_vars = Context({
        'form': form,
        'loggedinuser': loggedinuser,
        'team': team,
    })

    output = template.render(page_vars)
    return HttpResponse(output)

和我的模板。如你所见,它有{%csrf_token%}

{% extends 'cricket/base.html' %}
{% block title %}
    {{ loggedinuser }}
{% endblock %}

{% block username %}
    {{ loggedinuser }}
{% endblock %}

{% block date %}
    {{ today }}
{% endblock %}

{% block content %}
    <div class="span7">
        <h2>Adding player for {{ team }}</h2>
        <form method="post" action=".">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit">
        </form>
    </div>
{% endblock %}

我很确定我很快就会把事情搞砸了。

//小鼠

哦,我解决了它。你必须使用RequestContext。这是我的解决方案,更改orignal代码中的最后两行以包含crsfcontext

page_vars = Context({
    'form': form,
    'loggedinuser': loggedinuser,
    'team': team,
})

crsfcontext = RequestContext(request, page_vars)

output = template.render(crsfcontext)
return HttpResponse(output)

2 个答案:

答案 0 :(得分:0)

您还可以在django中使用基于类的通用视图。 在你的情况下可能是这样的:(我没有测试过它)

urls.py

urlpatterns = patterns('',
    url(r'^your-url/(?P<teamId>\d+)/$', AddPlayerView.as_view(), name="add-player"),
)

views.py

from django.views.generic import FormView
from django.core.urlresolvers import reverse
 .....

class AddPlayerView(FormView):

    template_name = 'cricket/addplayer.html'
    form_class = PlayerForm 

    def form_valid(self, form):
    """ Code if the form is valid """
                ...
        player = Player.objects.create(
            name = form.cleaned_data['name'],
            team = Team.objects.get(id=form.cleaned_data['team_id']),
            role = form.cleaned_data['role'],
            position = form.cleaned_data['position']
        )

        # You could use url reverse here
        url = reverse('your-view-name', args=[form.cleaned_data['team_id']])
        return HttpResponseRedirect(url)


    def form_invalid(self, form):
    """ Code if the form is invalid """
        .....


    def get_context_data(self, **kwargs):
        context = super(AddPlayerView, self).get_context_data(**kwargs)
        loggedinuser = self.request.user
        team = Team.objects.get(id=self.kwargs['teamId'])
        context['loggedinuser'] = loggedinuser
        context['team'] = team
        return context

答案 1 :(得分:0)

尝试使用render_to_response函数而不是HttpResponse和一些RequestContext。