简体   繁体   中英

How do I filter values according to logged in user in Django forms?

I have Rank, UserProfile and Company models. These classes are connected with foreign keys. A user with Rank "Lead" can create new users from his dashboard. I want to filter Rank models according to UserProfile's company. In the sign up form there will be dropdown list to choose Rank for new user. There should only be ranks that belong to UserProfile's company. These are my models:

class CompanyProfile(models.Model):
    comp_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
    comp_name = models.CharField(max_length=200)
    country = models.CharField(max_length=200, default='')

    def __str__(self):
        return self.comp_name

class Rank(models.Model):
    rank_name = models.CharField(max_length=200)
    company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False)

    def __str__(self):
        return self.rank_name


class UserProfile(AbstractUser):

    company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE, null=True, unique=False)
    user_id = models.UUIDField(default=uuid.uuid4(), editable=False, unique=True)
    username = models.CharField(max_length=500, unique=True)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    password = models.CharField(max_length=250)
    email = models.EmailField(max_length=254)
    rank = models.ForeignKey(Rank, on_delete=models.CASCADE, null=True, unique=False)
    image = models.ImageField(upload_to='profile_image', blank=True, null= True, default='profile.png')

    def __str__(self):
        return self.username

This is my form:

class SignUpForm(forms.ModelForm):


    password1 = forms.CharField(max_length=250)
    password2 = forms.CharField(max_length=250)
    

    class Meta:
        model = UserProfile
        fields = (
             'username', 'first_name', 'last_name', 'email', 'password1', 'password2','rank', 'image')

And this is views.py:

@user_passes_test(is_lead)
@login_required
def signup(request):
    form_class = SignUpForm
    if request.method == 'POST':
  
        form = SignUpForm(request.POST)
        if form.is_valid() :

            user = form.save()
            user.refresh_from_db()  # load the profile instance created by the signal
            user.is_active = False
            if form.cleaned_data['password1'] != "":
                user.set_password(form.cleaned_data['password1'])
                user.save()
            return redirect('home')
    else:
        form = form_class()

    return render(request, 'signup.html', {'form': form})

You'll need to override rank in your SignUpForm .

Something along the lines of:

choices = [(rank.id, rank.name) for rank in Rank.objects.filter(company=...)]

rank = models.CharField(
    max_length=200,
    choices=choices,
)

I assume you're passing the company into the form somehow so you'll need to adjust the filter to filter for the company you're creating the profile for.

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