I'm writing a sports league app. I get a drop down list of all my teams. And I can display the wins/losses data on a separate view. But I can't get the StandingsView (with the form) to correct redirect to the TeamView (display information).
I've tried both POST and GET. I've run into a bunch of issues I don't understand. First, the url from the form is directed to
/teamview/?team_name=6
I don't understand why that is, even if my view specifies otherwise.
Second, the view doesn't redirect unless I do so in the form action. I think that's a product of the GET function, but I'm not sure. I'm hesitant to use POST because I'm not changing the DB
I've looked into RedirectView, but worry (as always) I'm overcomplicating this. Thank you much,
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 %}