2012-02-01 6 views
0

私はdjangoシェルから実行する場合、それは正常に私のdbを作成する機能があります。値をカスタム関数に渡しますか? djangoのnoob

私は3つのクラスを持っています。

Class League(models.Model): 
    LeagueName = models.CharField() 
    #class League explained below 


Class Fixture(models.Model): 
    League = models.ForeignKey(League) 
    home_team = models.ForeginKey(Team) 
    away_team = models.ForeginKey(Team) 

Class Teams(models.Model): 
    League = models.ForeignKey(League) 

私ができるように機能が一つだけリーグに対する治具テーブルを計算します。ここに私が今やっていることがあります。それは現時点では行っていません。の仕方?

class League(models.Model): 
    LeagueName = models.CharField(max_length=200) 
    FixturesGenerated = models.BooleanField(default=False) 

    def __unicode__(self): 
     return self.LeagueName 

    def CreateFixtures(self, print_only=True): 
     if self.FixturesGenerated==True: 
      return 

     from dateutil import rrule 
     from dateutil.relativedelta import * 
     from League.models import Team, Fixture 
     import itertools 
     import datetime 
     import random 

     """ 
     Instead of your array I will use actual objects from the Teams model 
     """ 
     teams = Team.objects.all() 

     fixcombos = list(itertools.combinations(teams,2)) 
     random.shuffle(fixcombos) 

     nofixtures = len(fixcombos) 

     datestart = datetime.date.today() 
     dateend = datestart + datetime.timedelta(days=125) 
     #calculate possible fixture dates, 
     fixdays = list(rrule.rrule(rrule.DAILY, byweekday=(rrule.SA,rrule.SU), dtstart=datestart, until=dateend)) 
     nofmatchdays = len(fixdays) 

    # perday = perday matches, and then moved it into array for for loop of dates available. 
     perday = nofixtures/nofmatchdays +1 
     perday = range(0,perday) 

     #for loop to extend the fixture days array to repeat dates. 
     for x in perday: 
      fixdays = fixdays + fixdays 

     fixarray = range(0, nofixtures) 

     # for loop for printing the possible functions 
    # this for loop number will give the database entry id number of a particular name. we still have to do some manipulation. 
     result = '' 
     for y in fixarray: 
      printline = 'Date: ' + str(fixdays[y]) + ': Teams Involved: ' + str(fixcombos[y]) 
      result += printline 
      # now the print array functionality needs to be replaced with p.save() functionality in the final program. 
     """ 
      Code to actually save the fixture if print_only is not True 
      """ 
      if not print_only: 
       f = Fixture() 
       f.league = self 
       f.fixture_date = fixdays[y] 
       f.team_one = fixcombos[y][0] 
       f.team_two = fixcombos[y][1] 
       f.save() 
     self.FixturesGenerated = True 
     self.save() 

は、[編集] furthur手の込んだ、ここで私のadmin.py

from League.models import League 
from League.models import Team 
from League.models import Fixture 
from django.contrib import admin 

from django.http import HttpResponseRedirect 
class ButtonableModelAdmin(admin.ModelAdmin): 
    buttons=() 

    def change_view(self, request, object_id, extra_context={}): 
     extra_context['buttons']=self.buttons 
     return super(ButtonableModelAdmin, self).change_view(request, object_id, extra_context) 

    def button_view_dispatcher(self, request, object_id, command): 
     obj = self.model._default_manager.get(pk=object_id) 
     return getattr(self, command)(request, obj) \ 
      or HttpResponseRedirect(request.META['HTTP_REFERER']) 

    def get_urls(self): 

     from django.conf.urls.defaults import patterns, url 
     from django.utils.functional import update_wrapper 

     def wrap(view): 
      def wrapper(*args, **kwargs): 
       return self.admin_site.admin_view(view)(*args, **kwargs) 
      return update_wrapper(wrapper, view) 

     info = self.model._meta.app_label, self.model._meta.module_name 

     return patterns('', 
      *(url(r'^(\d+)/(%s)/$' % but[0], wrap(self.button_view_dispatcher)) for but in self.buttons) 
     ) + super(ButtonableModelAdmin, self).get_urls() 

class TeamsInLeague(admin.StackedInline): 
    model = Team 
    extra = 1 

class FixturesInLeague(admin.TabularInline): 
    model = Fixture 
    extra = 0 

class LeagueAdmin(ButtonableModelAdmin): 
    fields = ['LeagueName', 'FixturesGenerated'] 
    inlines = [TeamsInLeague, FixturesInLeague, ] 
    def gen_fixtures(self, request, obj):   
     obj.CreateFixtures(print_only=False) 
    gen_fixtures.short_description = 'Generate Fixtures' 
    gen_fixtures.url = "gen_fixtures" 
    buttons = [ (gen_fixtures.func_name, gen_fixtures.short_description) ] 

admin.site.register(League,LeagueAdmin) 
admin.site.register(Team) 
admin.site.register(Fixture) 

であるために、ここでそれは私のテンプレート/../ change_form.htmlからです。

{% extends "admin/change_form.html" %} 
{% block object-tools %} 
{% if change %}{% if not is_popup %} 
<ul class="object-tools"> 
{% for button in buttons %} 
    <li><a href="{{ button.0 }}/">{{ button.1 }}</a></li> 
{% endfor %} 
<li><a href="history/" class="historylink">History ala bala</a></li> 
{% if has_absolute_url %}<li><a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink">View on site</a></li>{% endif%} 
</ul> 
{% endif %}{% endif %} 
{% endblock %} 

kyokou。

//マウス

+2

どうしていませんか?あなたがどのようにそれを呼び出すかを教えてください。 – Nix

+0

が私のadmin.pyを追加しました。瞬間、ボタンをクリックして灯具を生成すると、チームテーブルからすべてのチームが奪取されます。私は、特定のリーグに仲間を連れて行きたいです。 django APIでは 'p = League.objects.get(id =?)' .. idは動的でボタンはそれを設定する必要があります。 'p.team_set.all()' ..私のボタンがチームIDの値を渡すようにしたいのですが、Team.objects.all()を使うのではなく、私の関数を適応させます。 – debuggerpk

+0

これを基本コードだけにカットします。これは、誰かが作業するための相当量のコードです。 – Marcin

答えて

0

私の提案は(あなたがやろうとしているかを理解するために私の最善を尽くした後で)あなたのアンカーは、あなたのチームのIDのGETパラメータを使用することです。

{% for button in buttons %} 
    <li><a href="{{ button.0 }}?team_id={{team_id}}/">{{ button.1 }}</a></li> 
{% endfor %} 

そして、あなたの見解では、チームIDを要求から引き出してCreateFixturesを呼び出すことができます。

team = request.get('team_id') 
league.CreateFixtures(team, print_only=False) 

これは、貼り付けたコードに基づいて行うことができます。私は強く読めるようにいくつかのことを書き直すことを強くお勧めします。

関連する問題