Django ModelForm:如何在下拉字段中显示用户特定的数据?

时间:2019-04-09 07:19:53

标签: python django django-forms

我有一个名为 Label 的下拉字段,它是名为 Birthday 的模型的一部分。我的问题是,下拉字段显示所有用户的标签。如何确保它只显示特定于用户的标签?

我认为表单模型中需要查询,但是我不知道如何执行此操作。

表格

class BirthdayForm(forms.ModelForm):

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

class LabelForm(forms.ModelForm):

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

模型

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

视图

@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 })

模板

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

1 个答案:

答案 0 :(得分:3)

尝试

 componentDidMount = async() => {
      await ref.once('value', async (snapshot) => {
      let imageUrl = [];
      snapshot.forEach(function(urlSnapshot) {
        imageUrl.push(urlSnapshot)
      });
      this.setState({ items : imageUrl});
    });
  }

希望有帮助