简体   繁体   中英

Django ModelForm: How to display user specific data in a drop-down field?

I have a drop-down field called Label as part of a model called Birthday . My problem is that the drop-down field shows the Labels from all users. How can I make sure it only shows the Labels specific to the User?

I assume that a query is required in the form model but I have no clue how to do this.

forms

class BirthdayForm(forms.ModelForm):

    class Meta:
        model = Birthday
        fields = ('name', 'day', 'label')

class LabelForm(forms.ModelForm):

    class Meta:
        model = Label
        fields = ('tag',)

models

class Label(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    tag = models.CharField(max_length=25)

    def __str__(self):
        return self.tag

class Birthday(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=25, default="")
    day = models.DateField()
    label = models.ForeignKey(Label, on_delete=models.SET_NULL, default=0, null=True, blank=True) 

    def __str__(self):  
        return self.name

view

@login_required
def index(request):
    if request.method == "POST":
        form = BirthdayForm(request.POST)
        if form.is_valid():
            birthday = form.save(commit=False)
            birthday.user = request.user
            birthday.save()
            return redirect('index')
    else:
        form = BirthdayForm()
    birthday = Birthday.objects.filter(user=request.user)
    username = request.user
    return render(request, 'bd_calendar/index.html', {'form': form, 'birthday': birthday, 'username': username })

template

            <form method="POST">{% csrf_token %}
                <table border="0">
                    {{ form }}
                </table>
                <button class="submitButton" type="submit">Submit</button>
            </form>

try this

class BirthdayForm(forms.ModelForm):

    class Meta:
        model = Birthday
        fields = ('name', 'day', 'label')
    def __init__(self, user, *args, **kwargs):
        super(BirthdayForm, self).__init__(*args, **kwargs)
        self.fields['label'].queryset = Label.objects.filter(user=user)

hope it helps

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