过滤Django用户选择字段用于表单

时间:2018-06-03 05:35:54

标签: python django django-models django-forms

我正在开展一项艰苦的django项目,我再次陷入困境。我在userprofile中有一个名为troop的字段:

class UserProfile(models.Model):

    scout_username = models.OneToOneField(User, on_delete=models.CASCADE)
    Group_Choice = Groups.Scout_Groups()
    troop = models.SlugField(max_length=27, choices=Group_Choice, default='None', blank=False)
    date_of_birth = models.DateField(default=date.today)


    def __str__(self):
        return '%s'% (self.scout_username)

def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = UserProfile.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=User)

然后我有一个表单,填写发送到我的stData模型的数据。在表单中,用户可以选择添加有关其他用户的详细信息。除了他们只能向具有相同troop详细信息的其他用户添加详细信息。 forms.py

from django import forms
from leaders.models import stData
from django.contrib.auth.models import User
from accounts.models import UserProfileManager, UserProfile

st_username_list=[
    (None, 'Choose a user'),
    (user1, 'user1'),
    (i, 'no progress'),
    ]

class BadgeForm(forms.ModelForm):
    def set_user(self, user):
        global st_username_list
        troop = user.userprofile.troop
        userprofile = UserProfile.objects.all()
        selected_st = userprofile.filter(troop=troop)
        for st in selected_st:
            username = str(st.st_username)
            st_username_list.append((username, username))
    st_username = forms.ChoiceField(choices=st_username_list)
    class Meta:
        model = stData
        fields = ('st_username', 'Pioneer_Badge', 'Explorer_Badge', 'Adventurer_Badge', 'Proficiency_Badge', 'Other_Badge') 

请注意 在上面的例子中,我使用了一个全局变量。我明白这远非理想。由于解释了正确的过滤方式(在换行后找到),我已经删除了它。我只是出于教育原因将其保留给可能发现他们有类似问题的其他人。

我在我的观看中传递用户:

user = request.user
user_form_setting = BadgeForm.set_user(self, user)

models.py

from django.db import models
from django.contrib.auth.models import User

from accounts.st_badge_list import st_List

class stData(models.Model):

    Pioneer_Choices = st_List.Target_Badges()
    Blue_Choices = st_List.Target_Badges()
    Black_Choices = st_List.Target_Badges()
    Proficiency_Choices = st_List.Proficiency_Badges()
    Other_Choice = st_List.Other_Badges()

    Pioneer_Badge = models.CharField(max_length=16, choices=Pioneer_Choices, default='None', blank=True)
    Blue_Star = models.CharField(max_length=16, choices=Blue_Choices, default='None', blank=True)
    Black_Star = models.CharField(max_length=16, choices=Black_Choices, default='None', blank=True)
    Proficiency_Badge = models.CharField(max_length=22, choices=Proficiency_Choices, default='None', blank=True)
    Other_Badge = models.CharField(max_length=27, choices=Other_Choice, default='None', blank=True)


    st_username = models.ForeignKey(User, on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now=True)
    print (User)

    def __str__(self):
        return '%s'% (self.st_username)

我将如何使用它,以便任何用户具有相同的troop详细信息将作为选择出现在st_username_list中? 在研究和尝试使用代码后,我得到了: ValueError Cannot assign "'user1'": "stData.st_username" must be a "User" instance. 我希望这不会太混乱。

修改 好的,我发现我可以通过

过滤st_username的选项
def __init__(self, *args, **kwargs):

        super().__init__(*args, **kwargs)
        self.fields['st_username'].queryset = UserProfile.objects.filter(troop='''user's troop''')

问题更新 我现在的主要问题是我无法通过模型中的用户实例。我见过这个question here。所以我把这个添加到了我的表格的主要方法中:

    self.user = kwargs.pop('user')

然而,当我尝试通过self.user使用用户时,我得到一个无用的错误KeyError,说user。 shell表明这可能是由于self.user = kwargs.pop(user) 我相信这可能是因为我没有通过用户。因此,当我在观看中调用表单时,我尝试了form = BadgeForm(user=request.user)并得到了同样的错误。

我的查询集现在看起来像这样:

self.fields['scout_username'].queryset=UserProfile.objects.filter(troop=user.userprofile.troop)

更多信息: 为了更好地理解这个问题,我在queryset中传递了一个部队变量。所以在这种情况下

self.fields['scout_username'].queryset=UserProfile.objects.filter(troop='BC')

虽然现在我得到Error AttributeError:     ' BadgeForm'对象没有属性' 名称' shell将其与我使用表单的formset链接。我提供的详细信息是:

line 435, in formset_factory
    return type(form.__name__ + 'FormSet', (formset,), attrs)

我希望这对你来说比对我更有意义!任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

最后一个问题是使用了formset。 根据{{​​3}},添加kwargs的正确方法是这样做:

    BadgeFormsSet = formset_factory(BadgeForm)
    formset = BadgeFormsSet(form_kwargs={'user': request.user})

希望这有助于其他任何人!

相关问题