Django:从表单

时间:2016-12-10 13:56:57

标签: django django-forms django-views django-generic-views

我正在写一个体育联盟应用程序。我得到了所有团队的下拉列表。我可以在单独的视图中显示赢/输数据。但是我无法使用StandingsView(带有表单)来纠正重定向到TeamView(显示信息)。

我已尝试过POST和GET。我遇到了一些我不明白的问题。首先,表单中的URL指向

/teamview/?team_name=6

我不明白为什么会这样,即使我的观点另有说明。

其次,视图不会重定向,除非我在表单操作中这样做。我认为这是GET功能的产物,但我不确定。我对使用POST犹豫不决,因为我没有更改数据库

我查看了RedirectView,但担心(一如既往)我过于复杂了。 非常感谢,

Views.py

class StandingsView(FormView):
    form_class = SelectTeam
    template_name = 'teamsports/standings.html'
    model = Teams
    success_url = '/teamview/'

    def form_valid(self, form):
       team = form.cleaned_data['team']
       return redirect('teamview', team = team)

    def form_invalid(self,form):
        HttpResponse ("This didn't work")

def TeamView(request, team):
    try:
        team = Teams.objects.filter(team=team).values()
    except Teams.DoesNotExist:
        raise Http404("Team does not exist")
    return render(request, 'teamview.html', {'team':team})

urls.py

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', admin.site.urls),
    url(r'^standings/$', views.StandingsView.as_view(), name="standings"),
    url(r'teamview/(?P<team>[0-9]+)/$', views.TeamView, name="teamview")

forms.py

class SelectTeam(ModelForm):
    team_name = forms.ModelChoiceField(queryset=Teams.objects.all(), initial=0)

    class Meta:
        model = Teams
        fields = ['team', 'team_name']

standings.html

<form action= "/teamview/" method="GET">
   {{ form }}
<input type="submit" value="Submit" />
{{ form.errors }}
</form>
{% endblock %}

0 个答案:

没有答案