简体   繁体   中英

Populating form field based on another models foreign key <user> - Django

I have 2 models one for a Club & one for a Team. The Club model contains a foreign key for the user. The Team model contains a foreign key to the Club. I am currently looking to auto populate and hide the "club_id" field in the Team form based on the logged in user. So each "User" is associated to a "Club" and each "Club" has multiple "Teams". Can this be accomplished in forms.py or must I do something in the view?

Models.py

class ClubInfo(models.Model):

   user = models.OneToOneField(User, on_delete=models.CASCADE)
   club_name = models.CharField(max_length=50, default='', unique=True)
   club_logo = models.ImageField(upload_to='profile_pics', blank=True)
   club_address1 = models.CharField(max_length=30)
   club_address2 = models.CharField(max_length=30, default='')
   club_address3 = models.CharField(max_length=30, default='')
   club_town = models.CharField(max_length=30)
   club_county = models.CharField(max_length=30)
   club_country = models.CharField(max_length=30)
   created_date = models.DateTimeField(default=timezone.now)

   def __str__(self):
      return self.club_name


class Team(models.Model):

    club_id = models.ForeignKey(ClubInfo, on_delete=models.CASCADE)
    team_name = models.CharField(max_length=30)
    manager_name = models.CharField(max_length=20)

    def __str__(self):
        return self.team_name

Forms.py

class ClubInfoForm(forms.ModelForm):

class Meta():
    model = ClubInfo
    fields = ('club_name', 'club_logo', 'club_address1', 'club_address2',
              'club_address3', 'club_town', 'club_county', 'club_country',)


class TeamForm(forms.ModelForm):

class Meta():
    model = Team
    fields = ('club_id', 'team_name', 'manager_name')

def __init__(self, *args, **kwargs):
    super(TeamForm, self).__init__(*args, **kwargs)
    self.fields['club_id'].widget = forms.HiddenInput()

I was also trying to do something similar then i ended up auto populating Club name of Team model by making a query to database on the bases of request.user as each user can only be linked to one club.

model.py

class Team(models.Model):

   club_name = model.CharField(max_length = 30)
   team_name = models.CharField(max_length=30)
   manager_name = models.CharField(max_length=20)

   def __str__(self):
     return self.team_name

views.py

def team_form_view(request):
     if not request.user.is_authenticated:
         return HttpRsponse("Login first")
     if request.method == 'POST':
         form = TeamForm(request.user)
         if form.is_valid():
           instance = form.save(commit="false")
           got_club = models.ClubInfo.objects.filter(user=request.user).values('club_name')
           instance.club_name=got_club[0]["club_name"]
           instance.save()
           return HttpResponse("team registered")
         else:
            return HttpResponse("form not valid")
      else:
         form = TeamForm()
         return render(request ,"RegisterTeam.html",{"form":form})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM