django foreignkey dropdown重定向到html页面

时间:2016-02-18 07:16:30

标签: python html django redirect django-forms

我尝试创建一个django页面,该页面具有单个下拉输入,引用包含数千个条目的数据库,当用户选择其中一个项目并点击时,提交",它将它们重定向到一个html页面,生成他们选择的项目的统计数据。我尝试过几件事而没有任何工作,我尝试过的最新事情就是我在这里找到的东西,虽然我也无法让它发挥作用,而且这个错误在于我:"本地变量' team_number'在分配之前引用"

views.py:

def team_stats(request):
    if request.method == 'POST':
        team_number = TeamStats(request.POST, request.FILES)
        if team_number.is_valid():
            # do stuff & add to database
            team_number.save()
            team_number = TeamStats.objects.create()
            # use my_file.pk or whatever attribute of FileField your id is
            # based on
            return HttpResponseRedirect('/team-stats/%i/' % team_number.pk)

    return render_to_response('team-stats.html', {
        'team_number': team_number,
    })

forms.py:

class TeamStats(forms.ModelForm):
    model = Team
    fields = 'team_number'

models.py:

class Team(models.Model):
    team_number = models.IntegerField()
    team_notes = models.CharField(max_length=150)
    event_id = models.ForeignKey(
        'Event', on_delete=models.CASCADE, unique=False)

    def __unicode__(self):
        return str(self.team_number)

    class Meta:
        db_table = 'teams'
        app_label = 'frcstats'

我希望我寻求帮助的是有道理的。如果没有,我会尝试更好地解释它。感谢

1 个答案:

答案 0 :(得分:0)

我注意到有一些问题,但导致问题的原因是,如果方法没有发布,你永远不会将team_number设置为某种东西,所以你不应该将它包含在上下文数据中

我还改变了你的视图以使用View类而不是基于函数的视图,这将允许视图针对不允许的请求引发不允许的响应

from django.views.generic import View
class TeamStatsView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'team-stats.html',
                      {'team_number': TeamStats()})

    def post(self, request, *args, **kwargs):
        team_number = TeamStats(request.POST, request.FILES)
        if team_number.is_valid():
            # do stuff & add to database
            team_number.save()
            team_number = TeamStats.objects.create()
            # use my_file.pk or whatever attribute of FileField your id is
            # based on
            return HttpResponseRedirect('/team-stats/%i/' % team_number.pk)
        return render(request, 'team-stats.html', {'team_number': team_number })

要使用此功能,您必须更改网址的目标

 url('your_url_regex', TeamStatsView.as_view(), name='should be here'),

我还将您的代码更改为使用render而不是render_to_response,因为后者不使用该请求而且可能会被删除

  

编辑后的版本现在抛出错误“ModelForm没有指定模型类。”

那是因为模型需要在表格的元数据上设置

class TeamStats(forms.ModelForm):    
    class Meta:
        model = Team
        fields = ['team_number']