扩展Django用户模型并访问它

时间:2015-07-17 18:39:01

标签: python django

我使用名为Client的模型在Django中扩展了User模型。

看起来像这样:

@python_2_unicode_compatible
class Client(models.Model):
    user = models.OneToOneField(User)
    company = models.CharField(max_length=100)

    def __str__(self):
        return self.company

    class Meta:
        verbose_name_plural = _("Clients")
        verbose_name = _("Client")
        permissions = (
            ("can_upload", _("Can upload files.")),
            ("can_access_uploads", _("Can access upload dashboard.")),
            ("is_client", _("Is a client.")),
        )

但是,我无法弄清楚如何通过视图中的当前用户访问此模型,例如:

def dashboard(request):
    current_user = request.user
    current_client = Client.objects.filter(user__icontains=current_user)

    files = ClientUpload.objects.filter(client__icontains=current_client)

    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            new_file = UploadFile(file = request.FILES['file'])
            new_file.save()

        return HttpResponsePermanentRedirect('/dashboard/')
    else:
        form = UploadFileForm()

    data = {'form': form, 'client': current_client, 'files': files}
    return render_to_response('dashboard.html', data, context_instance=RequestContext(request))

ClientUpload Model:

@python_2_unicode_compatible
class ClientUpload(models.Model):

    client = models.OneToOneField(Client)

    def generate_filename(self, filename):
        url = "uploads/%s/%s" % (self.client.company, filename)
        return url

    file_upload = models.FileField(upload_to=generate_filename)

    def __str__(self):
        return self.client.company

    class Meta:
        verbose_name_plural = _("Client Uploads")
        verbose_name = _("Client Upload")

我使用request.user获取当前用户,但我无法弄清楚如何让客户端与该用户相关。当我加载仪表板视图时,我收到错误:

“相关字段无效查找:icontains”

当我根据文档以这种方式扩展用户模型时,如何访问与用户关联的客户端模型?

感谢您提供任何帮助或建议。

1 个答案:

答案 0 :(得分:3)

您可以像这样访问给定Client的{​​{1}}对象:

User