Django - 如何根据用户ID过滤下拉列表?

时间:2016-10-04 11:40:49

标签: python django

我不确定如何根据用户ID过滤下拉列表。

我不想要用户ID 2。

enter image description here

对于用户ID 2,我想要这样。

enter image description here

模型

@python_2_unicode_compatible  # only if you need to support Python 2
class PredefinedMessage(models.Model):
    user = models.ForeignKey(User)
    list_name = models.CharField(max_length=50)
    list_description = models.CharField(max_length=50)

    def __str__(self):
        return self.list_name

class PredefinedMessageDetail(models.Model):
    predefined_message_detail = models.ForeignKey(PredefinedMessage)
    message = models.CharField(max_length=5000)

查看

class PredefinedMessageDetailForm(ModelForm):
    class Meta:
        model = PredefinedMessageDetail
        fields = ['predefined_message_detail', 'message']
        exclude = ('user',)

def predefined_message_detail_update(request, pk, template_name='predefined-message/predefined_message_detail_form.html'):
    if not request.user.is_authenticated():
        return redirect('home')
    predefined_message_detail = get_object_or_404(PredefinedMessageDetail, pk=pk)
    form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail)
    if form.is_valid():
        form.save()
        return redirect('predefined_message_list')
    return render(request, template_name, {'form':form})

html文件

{% extends "base.html" %}
{% load i18n %}

{% block content %}
<form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
</form>
{% endblock %}

1 个答案:

答案 0 :(得分:1)

您可以使用

在视图中进行操作
<?php

class MyTest extends \PHPUnit_Framework_TestCase {

    /** @dataProvider dataProviderA */
    public function testA() {}

    /** @dataProvider dataProviderB */
    public function testB() {}

    public function dataProviderA() 
    { 
        $dataProvider = $this->getProviderData();
        // Caller is A ...
        // Mutate base provider data as necessary...
    }

    public function dataProviderB() 
    { 
        $dataProvider = $this->getProviderData();
        // Caller is B ...
        // Mutate base provider data as necessary...
    }

    public function getProviderData() 
    {
        // ...
    }
}

但过滤基于form = PredefinedMessageDetailForm(request.POST or None, instance=predefined_message_detail) form.fields["predefined_message_detail"].queryset= PredefinedMessage.objects.filter(user=request.user) 发生,因此应该登录。同样考虑。希望这有帮助