基于另一个模型外键<user>填充表单字段-Django

时间:2019-02-05 14:23:04

标签: python django django-forms

我有2个模型,一个用于俱乐部,一个用于团队。俱乐部模型包含用户的外键。团队模型包含俱乐部的外键。我目前正在根据登录的用户自动填充并隐藏“团队”表单中的“ club_id”字段。因此,每个“用户”都与一个“俱乐部”相关联,并且每个“俱乐部”都有多个“团队”。可以在forms.py中完成此操作,还是必须在视图中执行某些操作?

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()

1 个答案:

答案 0 :(得分:0)

我还试图做类似的事情,然后我通过基于request.user对数据库进行查询来自动填充Team模型的Club名称,因为每个用户只能链接到一个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})